diff --git a/apps/web/src/app/(docs)/mintlify-docs/README.md b/apps/web/src/app/(docs)/mintlify-docs/README.md new file mode 100644 index 0000000000..4cbe0750c0 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/README.md @@ -0,0 +1,32 @@ +# Mintlify Starter Kit + +Click on `Use this template` to copy the Mintlify starter kit. The starter kit contains examples including + +- Guide pages +- Navigation +- Customizations +- API Reference pages +- Use of popular components + +### Development + +Install the [Mintlify CLI](https://www.npmjs.com/package/mintlify) to preview the documentation changes locally. To install, use the following command + +``` +npm i -g mintlify +``` + +Run the following command at the root of your documentation (where mint.json is) + +``` +mintlify dev +``` + +### Publishing Changes + +Install our Github App to auto propagate changes from your repo to your deployment. Changes will be deployed to production automatically after pushing to the default branch. Find the link to install on your dashboard. + +#### Troubleshooting + +- Mintlify dev isn't running - Run `mintlify install` it'll re-install dependencies. +- Page loads as a 404 - Make sure you are running in a folder with `mint.json` diff --git a/apps/web/src/app/(docs)/mintlify-docs/api-key/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/api-key/index.mdx new file mode 100644 index 0000000000..ce52f0884a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/api-key/index.mdx @@ -0,0 +1,41 @@ +--- +title: "API Key" +icon: "key" +--- + +To use the API key, you can either: + +- **Set the API key as the `E2B_API_KEY` environment variable** to avoid passing it each time you create a sandbox. +- Or pass it directly to the `Sandbox` constructor as shown below: + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create({ apiKey: 'YOUR_API_KEY' }) +``` +```python Python +from e2b_code_interpreter import Sandbox + +sbx = Sandbox.create(api_key="YOUR_API_KEY") +``` + + +## Where to find API key + +You can get your API key at [dashboard](https://e2b.dev/dashboard?tab=keys). + +
+ +# Access Token + +The access token is used only in the CLI and is **not needed in the SDK**. There's no need to set it when logging into the CLI using `e2b auth login`. + + +To authenticate without the browser, you can set `E2B_ACCESS_TOKEN` as an environment variable. This is useful for CI/CD pipelines. + + +## Where to find Access token + +You can get your **Access token key** at the [dashboard](https://e2b.dev/dashboard/account). + diff --git a/apps/web/src/app/(docs)/mintlify-docs/broken_links_report.mdx b/apps/web/src/app/(docs)/mintlify-docs/broken_links_report.mdx new file mode 100644 index 0000000000..a3a48b754f --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/broken_links_report.mdx @@ -0,0 +1,2 @@ +sandbox/metadata/index.mdx = https://e2b.dev/docs/sandbox/metadata + ⎿ the following page linked doesn't exist: [beta version of the SDK](/sandbox/installing-beta-sdks) = https://e2b.dev/docs/sandbox/installing-beta-sdks diff --git a/apps/web/src/app/(docs)/mintlify-docs/byoc/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/byoc/index.mdx new file mode 100644 index 0000000000..50b974fc15 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/byoc/index.mdx @@ -0,0 +1,70 @@ +--- +title: "BYOC (Bring Your Own Cloud)" +sidebarTitle: Bring Your Own Cloud +--- + +BYOC (Bring Your Own Cloud) allows you to deploy E2B sandboxes to your own cloud infrastructure within your VPC. + +BYOC is currently only available for AWS. We are working on adding support for Google Cloud and Azure. + + +BYOC is offered to enterprise customers only. +If you’re interested in BYOC offering, please book a call with our team [here](https://e2b.dev/contact) or contact us at [enterprise@e2b.dev](mailto:enterprise@e2b.dev). + + +## Architecture + +Sandbox templates, snapshots, and runtime logs are stored within the customer's BYOC VPC. +Anonymized system metrics such as cluster memory and cpu are sent to the E2B Cloud for observability and cluster management purposes. + +All potentially sensitive traffic, such as sandbox template build source files, +sandbox traffic, and logs, is transmitted directly from the client to the customer's BYOC VPC without ever touching the E2B Cloud infrastructure. + +### Glossary +- **BYOC VPC**: The customer's Virtual Private Network where the E2B sandboxes are deployed. For example your AWS account. +- **E2B Cloud**: The managed service that provides the E2B platform, observability and cluster management. +- **OAuth Provider**: Customer-managed service that provides user and E2B Cloud with access to the cluster. + + + + + +### BYOC Cluster Components +- **Orchestrator**: Represents a node that is responsible for managing sandboxes and their lifecycle. Optionally, it can also run the template builder component. +- **Edge Controller**: Routes traffic to sandboxes, exposes API for cluster management, and gRPC proxy used by E2B control plane to communicate with orchestrators. +- **Monitoring**: Collector that receives sandbox and build logs and system metrics from orchestrators and edge controllers. Only anonymized metrics are sent to the E2B Cloud for observability purposes. +- **Storage**: Persistent storage for sandbox templates, snapshots, and runtime logs. Image container repository for template images. + +## Onboarding + +Customers can initiate the onboarding process by reaching out to us. +Customers need to have a dedicated AWS account and know the region they will use. +After that, we will receive the IAM role needed for managing account resources. +For AWS account quota limits may need to be increased. + +Terraform configuration and machine images will be used for provisioning BYOC cluster. +When provisioning is done and running, we will create a new team under your E2B account that can be used by SDK/CLI the same way as it is hosted on E2B Cloud. + +## FAQ + + + + Cluster is forwarding anonymized metrics such as machine cpu/memory usage to E2B Control plane for advanced observability and alerting. + The whole observability stack is anonymized and does not contain any sensitive information. + + + A cluster can be scaled horizontally by adding more orchestrators and edge controllers. + The autoscaler is currently in V1 not capable of automatically scale orchestrator nodes that are needed for sandbox spawning. + This feature is coming in the next versions. + + + Yes. Load balancer that is handling all requests coming to sandbox can be configured as internal and VPC peering + with additional customer’s VPC can be configured so sandbox traffic can stay in the private network. + + + Data sent between the E2B Cloud and your BYOC VPC is encrypted using TLS. + + VPC peering can be established to allow direct communication between the E2B Cloud and your BYOC VPC. + When using VPC peering, the load balancer can be configured as private without a public IP address. + + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/cli/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/cli/auth/index.mdx new file mode 100644 index 0000000000..488b141cae --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/cli/auth/index.mdx @@ -0,0 +1,12 @@ +--- +title: "Authentication in CLI" +sidebarTitle: Authentication +--- + +You must authenticate with E2B CLI before using it. Run the following command to sign in into your E2B account: + + +```bash Terminal +e2b auth login +``` + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/cli/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/cli/index.mdx new file mode 100644 index 0000000000..d84fb32e0c --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/cli/index.mdx @@ -0,0 +1,36 @@ +--- +title: "E2B CLI" +sidebarTitle: Installation +--- + +E2B CLI is a command line tool that allows you to list, kill running sandboxes, and manage [sandbox templates](/sandbox-template). + +## Installation + +**Using Homebrew (on macOS)** + + +```bash Terminal +brew install e2b +``` + + +**Using NPM** + +You can install E2B CLI using the following command: + + +```bash Terminal +npm i -g @e2b/cli +``` + + +### Beta CLI + +The latest beta version of the CLI can be installed from NPM using the following command: + + +```bash Terminal +npm i -g @e2b/cli@beta +``` + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/cli/list-sandboxes/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/cli/list-sandboxes/index.mdx new file mode 100644 index 0000000000..4ecc837450 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/cli/list-sandboxes/index.mdx @@ -0,0 +1,55 @@ +--- +title: "List sandboxes" +--- + +You can list all sandboxes using the following command: + + +```bash Terminal +e2b sandbox list +``` + + +This will return running sandboxes, you can specify `--state` to get paused or both. + +### Filter by state + +To filter the sandboxes by their state you can specify the `--state` flag, which can either be "**running**", "**paused**" or both. + +```bash +e2b sandbox list --state running,paused +``` + +### Filter by metadata + +To filter the sandboxes by their metadata, use the `--metadata` flag. + +```bash +e2b sandbox list --metadata key1=value1,key2=value2 +``` + +### List limit + +To limit the amount of sandboxes returned by the command, use the `--limit` flag. + +```bash +e2b sandbox list --limit 10 +``` + +By default, the command will return all sandboxes. + +### Output format + +To output the sandboxes in JSON format, use the `--format` flag. + +**Pretty print (default)** + +```bash +e2b sandbox list --format pretty +``` + +**JSON** + +```bash +e2b sandbox list --format json +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/cli/shutdown-sandboxes/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/cli/shutdown-sandboxes/index.mdx new file mode 100644 index 0000000000..54c12f908a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/cli/shutdown-sandboxes/index.mdx @@ -0,0 +1,45 @@ +--- +title: "Shutdown running sandboxes" +--- + +You can shutdown single or all running sandboxes with the E2B CLI. + +## Shutdown single or multiple sandboxes + +To shutdown a single or multiple sandboxes, run the following command: + + +```bash Terminal +e2b sandbox kill +``` + + +## Shutdown all sandboxes + +To shutdown all running sandboxes, run the following command: + + +```bash Terminal +e2b sandbox kill --all +``` + + +Further, you can filter the sandboxes to be shutdown by state, metadata or both. + + +```bash Terminal +e2b sandbox kill --all --state=running,paused +``` + + + +```bash Terminal +e2b sandbox kill --all --metadata=key=value +``` + + + +```bash Terminal +e2b sandbox kill --all --state=running,paused --metadata=key=value +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/analyze-data-with-ai/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/analyze-data-with-ai/index.mdx new file mode 100644 index 0000000000..5fa78aea50 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/analyze-data-with-ai/index.mdx @@ -0,0 +1,532 @@ +--- +title: "Analyze data with AI" +sidebarTitle: Overview +--- + +You can use E2B Sandbox to run AI-generated code to analyze data. Here's how the AI data analysis workflow usually looks like: +1. Your user has a dataset in CSV format or other formats. +2. You prompt the LLM to generate code (usually Python) based on the user's data. +3. The sandbox runs the AI-generated code and returns the results. +4. You display the results to the user. + +--- + +## Example: Analyze CSV file with E2B and Claude 3.5 Sonnet +This short example will show you how to use E2B Sandbox to run AI-generated code to analyze CSV data. + +### Table of Contents +1. [Install dependencies](#1-install-dependencies) +2. [Set your API keys](#2-set-your-api-keys) +3. [Download example CSV file](#3-download-example-csv-file) +4. [Initialize the sandbox and upload the dataset to the sandbox](#4-initialize-the-sandbox-and-upload-the-dataset-to-the-sandbox) +5. [Prepare the method for running AI-generated code](#5-prepare-the-method-for-running-ai-generated-code) +6. [Prepare the prompt and initialize Anthropic client](#6-prepare-the-prompt-and-initialize-anthropic-client) +7. [Connect the sandbox to the LLM with tool calling](#7-connect-the-sandbox-to-the-llm-with-tool-calling) +8. [Parse the LLM response and run the AI-generated code in the sandbox](#8-parse-the-llm-response-and-run-the-ai-generated-code-in-the-sandbox) +9. [Save the generated chart](#9-save-the-generated-chart) +10. [Run the code](#10-run-the-code) +11. [Full final code](#full-final-code) + +### 1. Install dependencies +Install the E2B SDK and Claude SDK to your project by running the following command in your terminal. + + +```bash JavaScript & TypeScript +npm i @e2b/code-interpreter @anthropic-ai/sdk dotenv +``` +```bash Python +pip install e2b-code-interpreter anthropic python-dotenv +``` + + +### 2. Set your API keys +1. Get your E2B API key from [E2B Dashboard](https://e2b.dev/dashboard?tab=keys). +2. Get your Claude API key from [Claude API Dashboard](https://console.anthropic.com/settings/keys). +3. Paste the keys into your `.env` file. + + +```bash .env +E2B_API_KEY=e2b_*** +ANTHROPIC_API_KEY=sk-ant-*** +``` + + +### 3. Download example CSV file +{/* We'll be using the publicly available [AirBnB NYC dataset](https://www.kaggle.com/datasets/dgomonov/new-york-city-airbnb-open-data). */} + +We'll be using the publicly available [dataset of about 10,000 movies](https://www.kaggle.com/datasets/muqarrishzaib/tmdb-10000-movies-dataset). +1. Click the "Download" button at the top of the page. +2. Select "Download as zip (2 MB)". +3. Unzip the file and you should see `dataset.csv` file. Move it to the root of your project. + + +### 4. Initialize the sandbox and upload the dataset to the sandbox +We'll upload the dataset from the third step to the sandbox and save it as `dataset.csv` file. + + +```js index.ts +import 'dotenv/config' +import fs from 'fs' +import { Sandbox } from '@e2b/code-interpreter' + +// Create sandbox +const sbx = await Sandbox.create() + +// Upload the dataset to the sandbox +const content = fs.readFileSync('dataset.csv') +const datasetPathInSandbox = await sbx.files.write('dataset.csv', content) +``` +```python main.py +from dotenv import load_dotenv +load_dotenv() +from e2b_code_interpreter import Sandbox + +# Create sandbox +sbx = Sandbox.create() + +# Upload the dataset to the sandbox +dataset_path_in_sandbox = "" +with open("dataset.csv", "rb") as f: + dataset_path_in_sandbox = sbx.files.write("dataset.csv", f) + +``` + + +### 5. Prepare the method for running AI-generated code +Add the following code to the file. Here we're adding the method for code execution. + + +```js index.ts +// ... code from the previous step + +async function runAIGeneratedCode(aiGeneratedCode: string) { + console.log('Running the code in the sandbox....') + const execution = await sbx.runCode(aiGeneratedCode) + console.log('Code execution finished!') + console.log(execution) +} +``` +```python main.py +# ... code from the previous step + +def run_ai_generated_code(ai_generated_code: str): + print('Running the code in the sandbox....') + execution = sbx.run_code(ai_generated_code) + print('Code execution finished!') + print(execution) +``` + + +### 6. Prepare the prompt and initialize Anthropic client +The prompt we'll be using describes the dataset and the analysis we want to perform like this: + 1. Describe the columns in the CSV dataset. + 2. Ask the LLM what we want to analyze - here we want to analyze the vote average over time. We're asking for a chart as the output. + 3. Instruct the LLM to generate Python code for the data analysis. + + +```js index.ts +import Anthropic from '@anthropic-ai/sdk' + +const prompt = ` +I have a CSV file about movies. It has about 10k rows. It's saved in the sandbox at ${dataset_path_in_sandbox.path}. +These are the columns: +- 'id': number, id of the movie +- 'original_language': string like "eng", "es", "ko", etc +- 'original_title': string that's name of the movie in the original language +- 'overview': string about the movie +- 'popularity': float, from 0 to 9137.939. It's not normalized at all and there are outliers +- 'release_date': date in the format yyyy-mm-dd +- 'title': string that's the name of the movie in english +- 'vote_average': float number between 0 and 10 that's representing viewers voting average +- 'vote_count': int for how many viewers voted + +I want to better understand how the vote average has changed over the years. Write Python code that analyzes the dataset based on my request and produces right chart accordingly` + +const anthropic = new Anthropic() +console.log('Waiting for the model response...') +const msg = await anthropic.messages.create({ + model: 'claude-3-5-sonnet-20240620', + max_tokens: 1024, + messages: [{ role: 'user', content: prompt }], +}) +``` + +```python main.py +from anthropic import Anthropic + +prompt = ''' +I have a CSV file about movies. It has about 10k rows. It's saved in the sandbox at {datasetPathInSandbox.path}. +These are the columns: +- 'id': number, id of the movie +- 'original_language': string like "eng", "es", "ko", etc +- 'original_title': string that's name of the movie in the original language +- 'overview': string about the movie +- 'popularity': float, from 0 to 9137.939. It's not normalized at all and there are outliers +- 'release_date': date in the format yyyy-mm-dd +- 'title': string that's the name of the movie in english +- 'vote_average': float number between 0 and 10 that's representing viewers voting average +- 'vote_count': int for how many viewers voted + +I want to better understand how the vote average has changed over the years. Write Python code that analyzes the dataset based on my request and produces right chart accordingly''' + +anthropic = Anthropic() +msg = anthropic.messages.create( + model='claude-3-5-sonnet-20240620', + max_tokens=1024, + messages=[ + {"role": "user", "content": prompt} + ] +) +``` + + +### 7. Connect the sandbox to the LLM with tool calling +We'll use Claude's ability to [use tools (function calling)](https://docs.anthropic.com/en/docs/build-with-claude/tool-use) to run the code in the sandbox. + +The way we'll do it is by connecting the method for running AI-generated code we created in the previous step to the Claude model. + +Update the initialization of the Anthropic client to include the tool use like this: + +```js index.ts highlight={6-20} +const msg = await anthropic.messages.create({ + model: 'claude-3-5-sonnet-20240620', + max_tokens: 1024, + messages: [{ role: 'user', content: prompt }], + tools: [ + { + name: 'run_python_code', + description: 'Run Python code', + input_schema: { + type: 'object', + properties: { + code: { + type: 'string', + description: 'The Python code to run', + }, + }, + required: ['code'], + }, + }, + ], +}) +``` +```python main.py highlight={7-19} +msg = anthropic.messages.create( + model='claude-3-5-sonnet-20240620', + max_tokens=1024, + messages=[ + {"role": "user", "content": prompt} + ], + tools=[ + { + "name": "run_python_code", + "description": "Run Python code", + "input_schema": { + "type": "object", + "properties": { + "code": { "type": "string", "description": "The Python code to run" }, + }, + "required": ["code"], + }, + }, + ], +) +``` + + +### 8. Parse the LLM response and run the AI-generated code in the sandbox +Now we'll parse the `msg` object to get the code from the LLM's response based on the tool we created in the previous step. +Once we have the code, we'll pass it to the `runAIGeneratedCode` method in JavaScript or `run_ai_generated_code` method in Python we created in the previous step to run the code in the sandbox. + + +```js index.ts +// ... code from the previous steps + +interface CodeRunToolInput { + code: string +} + +for (const contentBlock of msg.content) { + if (contentBlock.type === 'tool_use') { + if (contentBlock.name === 'run_python_code') { + const code = (contentBlock.input as CodeRunToolInput).code + console.log('Will run following code in the sandbox', code) + // Execute the code in the sandbox + await runAIGeneratedCode(code) + } + } +} +``` +```python main.py +for content_block in msg.content: + if content_block.type == 'tool_use': + if content_block.name == 'run_python_code': + code = content_block.input['code'] + print('Will run following code in the sandbox', code) + # Execute the code in the sandbox + run_ai_generated_code(code) +``` + + +### 9. Save the generated chart +When running code in the sandbox for data analysis, you can get different types of results. +Including stdout, stderr, charts, tables, text, runtime errors, and more. + +In this example we're specifically asking for a chart so we'll be looking for the chart in the results. + +Let's update the `runAIGeneratedCode` method in JavaScript and `run_ai_generated_code` method in Python to check for the chart in the results and save it to the file. + +```js index.ts highlight={7-12,17-25} +async function runAIGeneratedCode(aiGeneratedCode: string) { + console.log('Running the code in the sandbox....') + const execution = await sbx.runCode(aiGeneratedCode) + console.log('Code execution finished!') + + // First let's check if the code ran successfully. + if (execution.error) { + console.error('AI-generated code had an error.') + console.log(execution.error.name) + console.log(execution.error.value) + console.log(execution.error.traceback) + process.exit(1) + } + + // Iterate over all the results and specifically check for png files that will represent the chart. + let resultIdx = 0 + for (const result of execution.results) { + if (result.png) { + // Save the png to a file + // The png is in base64 format. + fs.writeFileSync(`chart-${resultIdx}.png`, result.png, { encoding: 'base64' }) + console.log(`Chart saved to chart-${resultIdx}.png`) + resultIdx++ + } + } +} +``` +```python main.py highlight={7-12,15-23} +def run_ai_generated_code(ai_generated_code: str): + print('Running the code in the sandbox....') + execution = sbx.run_code(ai_generated_code) + print('Code execution finished!') + + # First let's check if the code ran successfully. + if execution.error: + print('AI-generated code had an error.') + print(execution.error.name) + print(execution.error.value) + print(execution.error.traceback) + sys.exit(1) + + # Iterate over all the results and specifically check for png files that will represent the chart. + result_idx = 0 + for result in execution.results: + if result.png: + # Save the png to a file + # The png is in base64 format. + with open(f'chart-{result_idx}.png', 'wb') as f: + f.write(base64.b64decode(result.png)) + print(f'Chart saved to chart-{result_idx}.png') + result_idx += 1 +``` + + +### 10. Run the code +Now you can run the whole code to see the results. + + +```bash JavaScript & TypeScript +npx tsx index.ts +``` +```bash Python +python main.py +``` + + +You should see the chart in the root of your project that will look similar to this: + + + + + +### Full final code +Check the full code in JavaScript and Python below: + +```js index.ts +import 'dotenv/config' +import fs from 'fs' +import Anthropic from '@anthropic-ai/sdk' +import { Sandbox } from '@e2b/code-interpreter' + +// Create sandbox +const sbx = await Sandbox.create() + +// Upload the dataset to the sandbox +const content = fs.readFileSync('dataset.csv') +const datasetPathInSandbox = await sbx.files.write('/home/user/dataset.csv', content) + +async function runAIGeneratedCode(aiGeneratedCode: string) { + const execution = await sbx.runCode(aiGeneratedCode) + if (execution.error) { + console.error('AI-generated code had an error.') + console.log(execution.error.name) + console.log(execution.error.value) + console.log(execution.error.traceback) + process.exit(1) + } + // Iterate over all the results and specifically check for png files that will represent the chart. + let resultIdx = 0 + for (const result of execution.results) { + if (result.png) { + // Save the png to a file + // The png is in base64 format. + fs.writeFileSync(`chart-${resultIdx}.png`, result.png, { encoding: 'base64' }) + console.log('Chart saved to chart-${resultIdx}.png') + resultIdx++ + } + } +} + +const prompt = ` +I have a CSV file about movies. It has about 10k rows. It's saved in the sandbox at ${datasetPathInSandbox.path}. +These are the columns: +- 'id': number, id of the movie +- 'original_language': string like "eng", "es", "ko", etc +- 'original_title': string that's name of the movie in the original language +- 'overview': string about the movie +- 'popularity': float, from 0 to 9137.939. It's not normalized at all and there are outliers +- 'release_date': date in the format yyyy-mm-dd +- 'title': string that's the name of the movie in english +- 'vote_average': float number between 0 and 10 that's representing viewers voting average +- 'vote_count': int for how many viewers voted + +I want to better understand how the vote average has changed over the years. Write Python code that analyzes the dataset based on my request and produces right chart accordingly` + +const anthropic = new Anthropic() +console.log('Waiting for the model response...') +const msg = await anthropic.messages.create({ + model: 'claude-3-5-sonnet-20240620', + max_tokens: 1024, + messages: [{ role: 'user', content: prompt }], + tools: [ + { + name: 'run_python_code', + description: 'Run Python code', + input_schema: { + type: 'object', + properties: { + code: { + type: 'string', + description: 'The Python code to run', + }, + }, + required: ['code'], + }, + }, + ], +}) + +interface CodeRunToolInput { + code: string +} + +for (const contentBlock of msg.content) { + if (contentBlock.type === 'tool_use') { + if (contentBlock.name === 'run_python_code') { + const code = (contentBlock.input as CodeRunToolInput).code + console.log('Will run following code in the sandbox', code) + // Execute the code in the sandbox + await runAIGeneratedCode(code) + } + } +} +``` +```python main.py +import sys +import base64 +from dotenv import load_dotenv +load_dotenv() +from e2b_code_interpreter import Sandbox +from anthropic import Anthropic + +# Create sandbox +sbx = Sandbox.create() + +# Upload the dataset to the sandbox +with open("../dataset.csv", "rb") as f: + dataset_path_in_sandbox = sbx.files.write("dataset.csv", f) + + +def run_ai_generated_code(ai_generated_code: str): + print('Running the code in the sandbox....') + execution = sbx.run_code(ai_generated_code) + print('Code execution finished!') + + # First let's check if the code ran successfully. + if execution.error: + print('AI-generated code had an error.') + print(execution.error.name) + print(execution.error.value) + print(execution.error.traceback) + sys.exit(1) + + # Iterate over all the results and specifically check for png files that will represent the chart. + result_idx = 0 + for result in execution.results: + if result.png: + # Save the png to a file + # The png is in base64 format. + with open(f'chart-{result_idx}.png', 'wb') as f: + f.write(base64.b64decode(result.png)) + print(f'Chart saved to chart-{result_idx}.png') + result_idx += 1 + +prompt = f""" +I have a CSV file about movies. It has about 10k rows. It's saved in the sandbox at {dataset_path_in_sandbox.path}. +These are the columns: +- 'id': number, id of the movie +- 'original_language': string like "eng", "es", "ko", etc +- 'original_title': string that's name of the movie in the original language +- 'overview': string about the movie +- 'popularity': float, from 0 to 9137.939. It's not normalized at all and there are outliers +- 'release_date': date in the format yyyy-mm-dd +- 'title': string that's the name of the movie in english +- 'vote_average': float number between 0 and 10 that's representing viewers voting average +- 'vote_count': int for how many viewers voted + +I want to better understand how the vote average has changed over the years. +Write Python code that analyzes the dataset based on my request and produces right chart accordingly""" + +anthropic = Anthropic() +print("Waiting for model response...") +msg = anthropic.messages.create( + model='claude-3-5-sonnet-20240620', + max_tokens=1024, + messages=[ + {"role": "user", "content": prompt} + ], + tools=[ + { + "name": "run_python_code", + "description": "Run Python code", + "input_schema": { + "type": "object", + "properties": { + "code": { "type": "string", "description": "The Python code to run" }, + }, + "required": ["code"] + } + } + ] +) + +for content_block in msg.content: + if content_block.type == "tool_use": + if content_block.name == "run_python_code": + code = content_block.input["code"] + print("Will run following code in the sandbox", code) + # Execute the code in the sandbox + run_ai_generated_code(code) + +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/analyze-data-with-ai/pre-installed-libraries/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/analyze-data-with-ai/pre-installed-libraries/index.mdx new file mode 100644 index 0000000000..2629651380 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/analyze-data-with-ai/pre-installed-libraries/index.mdx @@ -0,0 +1,36 @@ +--- +title: "Pre-installed libraries" +--- + +The sandbox comes with a [set of pre-installed Python libraries](https://github.com/e2b-dev/code-interpreter/blob/main/template/requirements.txt) for data analysis +but you can [install additional packages](/quickstart/install-custom-packages): +- `aiohttp` (v3.9.3) +- `beautifulsoup4` (v4.12.3) +- `bokeh` (v3.3.4) +- `gensim` (v4.3.2) +- `imageio` (v2.34.0) +- `joblib` (v1.3.2) +- `librosa` (v0.10.1) +- `matplotlib` (v3.8.3) +- `nltk` (v3.8.1) +- `numpy` (v1.26.4) +- `opencv-python` (v4.9.0.80) +- `openpyxl` (v3.1.2) +- `pandas` (v1.5.3) +- `plotly` (v5.19.0) +- `pytest` (v8.1.0) +- `python`-docx (v1.1.0) +- `pytz` (v2024.1) +- `requests` (v2.26.0) +- `scikit-image` (v0.22.0) +- `scikit-learn` (v1.4.1.post1) +- `scipy` (v1.12.0) +- `seaborn` (v0.13.2) +- `soundfile` (v0.12.1) +- `spacy` (v3.7.4) +- `textblob` (v0.18.0) +- `tornado` (v6.4) +- `urllib3` (v1.26.7) +- `xarray` (v2024.2.0) +- `xlrd` (v2.0.1) +- `sympy` (v1.12) diff --git a/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/create-charts-visualizations/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/create-charts-visualizations/index.mdx new file mode 100644 index 0000000000..e18f863e64 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/create-charts-visualizations/index.mdx @@ -0,0 +1,13 @@ +--- +sidebarTitle: Overview +title: "Create charts & visualizations" +--- + +E2B Sandbox allows you to create charts and visualizations by executing Python code inside the sandbox with `runCode()` method in JavaScript and `run_code()` method in Python. + +These charts and visualizations can be [static](/code-interpreting/create-charts-visualizations/static-charts) or [interactive](/code-interpreting/create-charts-visualizations/interactive-charts) plots. + +{/* +Learn more about different types of results that E2B Sandbox can return [(TODO: link)here](/code-interpreting/results). + */} + diff --git a/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/create-charts-visualizations/interactive-charts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/create-charts-visualizations/interactive-charts/index.mdx new file mode 100644 index 0000000000..32b63eadb1 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/create-charts-visualizations/interactive-charts/index.mdx @@ -0,0 +1,177 @@ +--- +title: "Interactive charts" +--- + +E2B also allows you to create interactive charts with custom styling. + +E2B automatically detects charts when executing Python code with `runCode()` in JavaScript or `run_code()` in Python. The Python code must include Matplotlib charts. + +When a chart is detected, E2B sends the data of the chart back to the client. You can access the chart in the `execution.results` array where each item is a `Result` object with the `chart` property. + + +Try out [AI Data Analyst](https://github.com/e2b-dev/ai-analyst/) - a Next.js app that uses E2B to create interactive charts. + + +Here's a simple example of bar chart: + +```js JavaScript & TypeScript +import { Sandbox, BarChart } from '@e2b/code-interpreter' + +const code = ` +import matplotlib.pyplot as plt + +# Prepare data +authors = ['Author A', 'Author B', 'Author C', 'Author D'] +sales = [100, 200, 300, 400] + +# Create and customize the bar chart +plt.figure(figsize=(10, 6)) +plt.bar(authors, sales, label='Books Sold', color='blue') +plt.xlabel('Authors') +plt.ylabel('Number of Books Sold') +plt.title('Book Sales by Authors') + +# Display the chart +plt.tight_layout() +plt.show() +` + +const sandbox = await Sandbox.create() +const result = await sandbox.runCode(code) +const chart = result.results[0].chart as BarChart + +console.log('Type:', chart.type) +console.log('Title:', chart.title) +console.log('X Label:', chart.x_label) +console.log('Y Label:', chart.y_label) +console.log('X Unit:', chart.x_unit) +console.log('Y Unit:', chart.y_unit) +console.log('Elements:', chart.elements) +``` +```python Python +from e2b_code_interpreter import Sandbox + +code = """ +import matplotlib.pyplot as plt + +# Prepare data +authors = ['Author A', 'Author B', 'Author C', 'Author D'] +sales = [100, 200, 300, 400] + +# Create and customize the bar char +plt.figure(figsize=(10, 6)) +plt.bar(authors, sales, label='Books Sold', color='blue') +plt.xlabel('Authors') +plt.ylabel('Number of Books Sold') +plt.title('Book Sales by Authors') + +# Display the chart +plt.tight_layout() +plt.show() +""" + +sandbox = Sandbox.create() +execution = sandbox.run_code(code) +chart = execution.results[0].chart + +print('Type:', chart.type) +print('Title:', chart.title) +print('X Label:', chart.x_label) +print('Y Label:', chart.y_label) +print('X Unit:', chart.x_unit) +print('Y Unit:', chart.y_unit) +print('Elements:') +for element in chart.elements: + print('\n Label:', element.label) + print(' Value:', element.value) + print(' Group:', element.group) +``` + + + +The code above will output the following: + +```bash JavaScript & TypeScript +Type: bar +Title: Book Sales by Authors +X Label: Authors +Y Label: Number of Books Sold +X Unit: null +Y Unit: null +Elements: [ + { + label: "Author A", + group: "Books Sold", + value: 100, + }, { + label: "Author B", + group: "Books Sold", + value: 200, + }, { + label: "Author C", + group: "Books Sold", + value: 300, + }, { + label: "Author D", + group: "Books Sold", + value: 400, + } +] +``` +```bash Python +Type: ChartType.BAR +Title: Book Sales by Authors +X Label: Authors +Y Label: Number of Books Sold +X Unit: None +Y Unit: None +Elements: + + Label: Author A + Value: 100.0 + Group: Books Sold + + Label: Author B + Value: 200.0 + Group: Books Sold + + Label: Author C + Value: 300.0 + Group: Books Sold + + Label: Author D + Value: 400.0 + Group: Books Sold +``` + + +You can send this data to your frontend to create an interactive chart with your favorite charting library. + +--- + +## Supported intertactive charts +The following charts are currently supported: +- Line chart +- Bar chart +- Scatter plot +- Pie chart +- Box and whisker plot + + +{/* The following charts are currently supported: +- [Line chart](#line-chart) +- [Bar chart](#bar-chart) +- [Scatter plot](#scatter-plot) +- [Pie chart](#pie-chart) +- [Box and whisker plot](#box-and-whisker-plot) + + +## Line chart + +## Bar chart + +## Scatter plot + +## Pie chart + +## Box and whisker plot */} \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/create-charts-visualizations/static-charts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/create-charts-visualizations/static-charts/index.mdx new file mode 100644 index 0000000000..2a7d33710e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/create-charts-visualizations/static-charts/index.mdx @@ -0,0 +1,68 @@ +--- +title: "Static charts" +--- + +Every time you run Python code with `runCode()` in JavaScript or `run_code()` method in Python, the code is executed in a headless Jupyter server inside the sandbox. + +E2B automatically detects any plots created with Matplotlib and sends them back to the client as images encoded in the base64 format. +These images are directly accesible on the `result` items in the `execution.results` array. + +Here's how to retrieve a static chart from the executed Python code that contains a Matplotlib plot. + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' +import fs from 'fs' + +const codeToRun = ` +import matplotlib.pyplot as plt + +plt.plot([1, 2, 3, 4]) +plt.ylabel('some numbers') +plt.show() +` +const sandbox = await Sandbox.create() + +// Run the code inside the sandbox +const execution = await sandbox.runCode(codeToRun) + + // There's only one result in this case - the plot displayed with `plt.show()` +const firstResult = execution.results[0] + +if (firstResult.png) { + // Save the png to a file. The png is in base64 format. + fs.writeFileSync('chart.png', firstResult.png, { encoding: 'base64' }) + console.log('Chart saved as chart.png') +} +``` +```python Python +import base64 +from e2b_code_interpreter import Sandbox + +code_to_run = """ +import matplotlib.pyplot as plt + +plt.plot([1, 2, 3, 4]) +plt.ylabel('some numbers') +plt.show() +""" + +sandbox = Sandbox.create() + +# Run the code inside the sandbox +execution = sandbox.run_code(code_to_run) + +# There's only one result in this case - the plot displayed with `plt.show()` +first_result = execution.results[0] + +if first_result.png: + # Save the png to a file. The png is in base64 format. + with open('chart.png', 'wb') as f: + f.write(base64.b64decode(first_result.png)) + print('Chart saved as chart.png') +``` + + +The code in the variable `codeToRun`/`code_to_run` will produce this following plot that we're saving as `chart.png` file. + + + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/streaming/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/streaming/index.mdx new file mode 100644 index 0000000000..7120f9401f --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/streaming/index.mdx @@ -0,0 +1,141 @@ +--- +title: "Streaming" +--- + +Use E2B SDK allows you to stream the output, and results when executing code in the sandbox. + + +## Stream `stdout` and `stderr` +When using the `runCode()` method in JavaScript or `run_code()` in Python you can pass `onStdout`/`on_stdout` and `onStderr`/`on_stderr` callbacks to handle the output. + + +```js JavaScript & TypeScript highlight={15-17} +import { Sandbox } from '@e2b/code-interpreter' + +const codeToRun = ` + import time + import sys + print("This goes first to stdout") + time.sleep(3) + print("This goes later to stderr", file=sys.stderr) + time.sleep(3) + print("This goes last") +` +const sandbox = await Sandbox.create() +sandbox.runCode(codeToRun, { + // Use `onError` to handle runtime code errors + onError: error => console.error('error:', error), + onStdout: data => console.log('stdout:', data), + onStderr: data => console.error('stderr:', data), +}) +``` +```python Python highlight={17-19} +from e2b_code_interpreter import Sandbox + +code_to_run = """ + import time + import sys + print("This goes first to stdout") + time.sleep(3) + print("This goes later to stderr", file=sys.stderr) + time.sleep(3) + print("This goes last") +""" + +sandbox = Sandbox.create() +sandbox.run_code( + code_to_run, + # Use `on_error` to handle runtime code errors + on_error=lambda error: print('error:', error), + on_stdout=lambda data: print('stdout:', data), + on_stderr=lambda data: print('stderr:', data), +) +``` + + +The code above will print the following: + + +```javascript JavaScript & TypeScript +stdout: { + error: false, + line: "This goes first to stdout\n", + timestamp: 1729049666861000, +} +stderr: { + error: true, + line: "This goes later to stderr\n", + timestamp: 1729049669924000, +} +stdout: { + error: false, + line: "This goes last\n", + timestamp: 1729049672664000, +} +``` +```bash Python +stdout: This goes first to stdout + +stderr: This goes later to stderr + +stdout: This goes last +``` + + +## Stream `results` + +When using the `runCode()` method in JavaScript or `run_code()` in Python you can pass `onResults`/`on_results` callback +to receive results from the sandbox like charts, tables, text, and more. + + +```js JavaScript & TypeScript highlight={20} +const codeToRun = ` +import matplotlib.pyplot as plt + +# Prepare data +categories = ['Category A', 'Category B', 'Category C', 'Category D'] +values = [10, 20, 15, 25] + +# Create and customize the bar chart +plt.figure(figsize=(10, 6)) +plt.bar(categories, values, color='green') +plt.xlabel('Categories') +plt.ylabel('Values') +plt.title('Values by Category') + +# Display the chart +plt.show() +` +const sandbox = await Sandbox.create() +await sandbox.runCode(codeToRun, { + onResult: result => console.log('result:', result), +}) +``` +```python Python highlight={24} +from e2b_code_interpreter import Sandbox + +code_to_run = """ +import matplotlib.pyplot as plt + +# Prepare data +categories = ['Category A', 'Category B', 'Category C', 'Category D'] +values = [10, 20, 15, 25] + +# Create and customize the bar chart +plt.figure(figsize=(10, 6)) +plt.bar(categories, values, color='green') +plt.xlabel('Categories') +plt.ylabel('Values') +plt.title('Values by Category') + +# Display the chart +plt.show() +""" + +sandbox = Sandbox.create() +sandbox.run_code( + code_to_run, + on_result=lambda result: print('result:', result), +) +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/bash/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/bash/index.mdx new file mode 100644 index 0000000000..323e7e4911 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/bash/index.mdx @@ -0,0 +1,23 @@ +--- +sidebarTitle: Bash +title: "Run bash code" +--- + +Use the `runCode`/`run_code` method to run bash code inside the sandbox. +You'll need to pass the `language` parameter with value `bash`. + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = await Sandbox.create() +const execution = await sbx.runCode('echo "Hello, world!"', { language: 'bash' }) +console.log(execution) +``` +```python Python +from e2b_code_interpreter import Sandbox + +sbx = Sandbox.create() +execution = sbx.run_code("echo 'Hello, world!'", language="bash") +print(execution) +``` + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/index.mdx new file mode 100644 index 0000000000..e9cfc0a690 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/index.mdx @@ -0,0 +1,17 @@ +--- +sidebarTitle: Overview +title: "Supported languages" +--- + +Typically you use Python to run AI-generated code for data analysis but you can use other languages as well. + +Out of the box E2B Sandbox supports: +- [Python](/code-interpreting/supported-languages/python) +- [JavaScript and TypeScript](/code-interpreting/supported-languages/javascript) +- [R](/code-interpreting/supported-languages/r) +- [Java](/code-interpreting/supported-languages/java) +- [Bash](/code-interpreting/supported-languages/bash) + + +You can use any custom language runtime by creating a [custom sandbox template](/sandbox-template). + diff --git a/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/java/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/java/index.mdx new file mode 100644 index 0000000000..f6cba19052 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/java/index.mdx @@ -0,0 +1,23 @@ +--- +title: "Run Java code" +sidebarTitle: Java +--- + +Use the `runCode`/`run_code` method to run Java code inside the sandbox. +You'll need to pass the `language` parameter with value `java`. + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = await Sandbox.create() +const execution = await sbx.runCode('System.out.println("Hello, world!");', { language: 'java' }) +console.log(execution) +``` +```python Python +from e2b_code_interpreter import Sandbox + +sbx = Sandbox.create() +execution = sbx.run_code('System.out.println("Hello, world!");', language="java") +print(execution) +``` + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/javascript/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/javascript/index.mdx new file mode 100644 index 0000000000..51d7cf9a86 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/javascript/index.mdx @@ -0,0 +1,78 @@ +--- +title: "Run JavaScript and TypeScript code" +sidebarTitle: "JavaScript and TypeScript" +--- + +Use the `runCode`/`run_code` method to run JavaScript and TypeScript code inside the sandbox. +You'll need to pass the `language` parameter with value `javascript` or `js` for JavaScript and `typescript` or `ts` for TypeScript. + + +The E2B Code Interpreter supports TypeScript, top-level await, ESM-style imports and automatic promises resolution. + + + +```js JavaScript & TypeScript +import { Sandbox } from "@e2b/code-interpreter"; + +// Create a new sandbox +const sbx = await Sandbox.create(); + +// Install the axios package +await sbx.commands.run("npm install axios"); + +// Run the code +const execution = await sbx.runCode(` + import axios from "axios"; + + const url: string = "https://api.github.com/status"; + const response = await axios.get(url); + response.data; +`, + { language: "ts" } +); + +console.log(execution); + +// Execution { +// results: [], +// logs: { +// stdout: [ "{ message: 'GitHub lives! (2025-05-28 10:49:55 -0700) (1)' }\n" ], +// stderr: [], +// }, +// error: undefined, +// executionCount: 1, +// text: [Getter], +// toJSON: [Function: toJSON], +// } +``` +```python Python +from e2b_code_interpreter import Sandbox + +# Create a new sandbox +sbx = Sandbox.create() + +# Install the axios package +sbx.commands.run("npm install axios") + +# Run the code +execution = sbx.run_code(""" + import axios from "axios"; + + const url: string = "https://api.github.com/status"; + const response = await axios.get(url); + response.data; +""", + language="ts", +) + +print(execution) + +# Execution( +# Results: [ +# Result({ message: 'GitHub lives! (2025-05-28 10:48:47 -0700) (1)' }) +# ], +# Logs: Logs(stdout: [], stderr: []), +# Error: None +# ) +``` + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/python/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/python/index.mdx new file mode 100644 index 0000000000..306e4692bd --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/python/index.mdx @@ -0,0 +1,22 @@ +--- +sidebarTitle: Python +title: "Run Python code" +--- + +Use the `runCode`/`run_code` method to run Python code inside the sandbox. + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = await Sandbox.create() +const execution = await sbx.runCode('print("Hello, world!")') +console.log(execution) +``` +```python Python +from e2b_code_interpreter import Sandbox + +sbx = Sandbox.create() +execution = sbx.run_code('print("Hello, world!")') +print(execution) +``` + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/r/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/r/index.mdx new file mode 100644 index 0000000000..a849eab7a7 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/code-interpreting/supported-languages/r/index.mdx @@ -0,0 +1,24 @@ +--- +title: Run R code +sidebarTitle: R +--- + + +Use the `runCode`/`run_code` method to run R code inside the sandbox. +You'll need to pass the `language` parameter with value `r`. + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = await Sandbox.create() +const execution = await sbx.runCode('print("Hello, world!")', { language: 'r' }) +console.log(execution) +``` +```python Python +from e2b_code_interpreter import Sandbox + +sbx = Sandbox.create() +execution = sbx.run_code('print("Hello, world!")', language="r") +print(execution) +``` + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/commands/background/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/commands/background/index.mdx new file mode 100644 index 0000000000..abaf810642 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/commands/background/index.mdx @@ -0,0 +1,45 @@ +--- +title: "Running commands in background" +sidebarTitle: Run commands in background +--- + +To run commands in background, pass the `background` option to the `commands.run()` method. This will return immediately and the command will continue to run in the sandbox. +You can then later kill the command using the `commands.kill()` method. + + +```js JavaScript & TypeScript highlight={7} +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() + +// Start the command in the background +const command = await sandbox.commands.run('echo hello; sleep 10; echo world', { + background: true, + onStdout: (data) => { + console.log(data) + }, +}) + +// Kill the command +await command.kill() +``` +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() + +# Start the command in the background +command = sandbox.commands.run('echo hello; sleep 10; echo world', background=True) + +# Get stdout and stderr from the command running in the background. +# You can run this code in a separate thread or use command.wait() to wait for the command to finish. +for stdout, stderr, _ in command: + if stdout: + print(stdout) + if stderr: + print(stderr) + +# Kill the command +command.kill() +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/commands/index.mdx new file mode 100644 index 0000000000..e8a43516cd --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/commands/index.mdx @@ -0,0 +1,24 @@ +--- +title: "Running commands in sandbox" +sidebarTitle: Overview +--- + +You can run terminal commands inside the sandbox using the `commands.run()` method. + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +const result = await sandbox.commands.run('ls -l') +console.log(result) +``` +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() + +result = sandbox.commands.run('ls -l') +print(result) +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/commands/streaming/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/commands/streaming/index.mdx new file mode 100644 index 0000000000..2fc08ab693 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/commands/streaming/index.mdx @@ -0,0 +1,32 @@ +--- +title: "Streaming command output" +sidebarTitle: Streaming +--- + +To stream command output as it is being executed, pass the `onStdout`, `onStderr` callbacks to the `commands.run()` method in JavaScript +or the `on_stdout`, `on_stderr` callbacks to the `commands.run()` method in Python. + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +const result = await sandbox.commands.run('echo hello; sleep 1; echo world', { + onStdout: (data) => { + console.log(data) + }, + onStderr: (data) => { + console.log(data) + }, +}) +console.log(result) +``` +```python Python +from e2b_code_interpreter import 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)/mintlify-docs/cookbook/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/cookbook/index.mdx new file mode 100644 index 0000000000..af85244002 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/cookbook/index.mdx @@ -0,0 +1,5 @@ +--- +url: https://github.com/e2b-dev/e2b-cookbook +title: Cookbook +icon: "brackets-curly" +--- \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/docs.json b/apps/web/src/app/(docs)/mintlify-docs/docs.json new file mode 100644 index 0000000000..5164b229a3 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/docs.json @@ -0,0 +1,2602 @@ +{ + "$schema": "https://mintlify.com/docs.json", + "theme": "maple", + "name": "E2B Docs", + "colors": { + "primary": "#ff8800", + "light": "#ff8800", + "dark": "#ffffff" + }, + "favicon": "/favicon.jpeg", + "navigation": { + "anchors": [ + { + "anchor": "Documentation", + "icon": "book-open-cover", + "groups": [ + { + "group": "Getting Started", + "pages": [ + "index", + { + "group": "Quickstart", + "icon": "circle-check", + "pages": [ + "quickstart/index", + "quickstart/connect-llms/index", + "quickstart/upload-download-files/index", + "quickstart/install-custom-packages/index" + ] + }, + "api-key/index", + "cookbook/index", + "support/index" + ] + }, + { + "group": "Code Interpreting", + "pages": [ + { + "group": "Analyze data with AI", + "pages": [ + "code-interpreting/analyze-data-with-ai/index", + "code-interpreting/analyze-data-with-ai/pre-installed-libraries/index" + ] + }, + { + "group": "Charts & visualizations", + "pages": [ + "code-interpreting/create-charts-visualizations/index", + "code-interpreting/create-charts-visualizations/static-charts/index", + "code-interpreting/create-charts-visualizations/interactive-charts/index" + ] + }, + "code-interpreting/streaming/index", + { + "group": "Supported languages", + "pages": [ + "code-interpreting/supported-languages/index", + "code-interpreting/supported-languages/python/index", + "code-interpreting/supported-languages/javascript/index", + "code-interpreting/supported-languages/r/index", + "code-interpreting/supported-languages/java/index", + "code-interpreting/supported-languages/bash/index" + ] + } + ] + }, + { + "group": "Sandbox", + "pages": [ + "sandbox/index", + "sandbox/lifecycle-events-api/index", + "sandbox/lifecycle-events-webhooks/index", + "sandbox/persistence/index", + "sandbox/metrics/index", + "sandbox/metadata/index", + "sandbox/environment-variables/index", + "sandbox/list/index", + "sandbox/connect/index", + "sandbox/internet-access/index", + "sandbox/connect-bucket/index", + "sandbox/rate-limits/index" + ] + }, + { + "group": "Templates", + "pages": [ + "sandbox-template/index", + "sandbox-template/start-cmd/index", + "sandbox-template/ready-cmd/index", + "sandbox-template/customize-cpu-ram/index" + ] + }, + { + "group": "Filesystem", + "pages": [ + "filesystem/index", + "filesystem/read-write/index", + "filesystem/info/index", + "filesystem/watch/index", + "filesystem/upload/index", + "filesystem/download/index" + ] + }, + { + "group": "Commands", + "pages": [ + "commands/index", + "commands/streaming/index", + "commands/background/index" + ] + }, + { + "group": "CLI", + "pages": [ + "cli/index", + "cli/auth/index", + "cli/list-sandboxes/index", + "cli/shutdown-sandboxes/index" + ] + }, + { + "group": "Deployment", + "pages": [ + "byoc/index" + ] + }, + { + "group": "Migration", + "pages": [ + "migration/v2/index" + ] + }, + { + "group": "Troubleshooting", + "pages": [ + { + "group": "SDKs", + "pages": [ + "troubleshooting/sdks/workers-edge-runtime/index" + ] + }, + { + "group": "Templates", + "pages": [ + "troubleshooting/templates/build-authentication-error/index" + ] + } + ] + } + ] + }, + { + "anchor": "SDK Reference", + "icon": "brackets-curly", + "dropdowns": [ + { + "dropdown": "SDK Reference", + "icon": "brackets-curly", + "pages": [ + "sdk-reference/index" + ] + }, + { + "dropdown": "CLI", + "icon": "terminal", + "versions": [ + { + "version": "v2.2.0@latest", + "groups": [ + { + "group": "CLI v2.2.0", + "pages": [ + "sdk-reference/cli/v2.2.0/auth/index", + "sdk-reference/cli/v2.2.0/sandbox/index", + "sdk-reference/cli/v2.2.0/template/index" + ] + } + ] + }, + { + "version": "v2.1.0", + "groups": [ + { + "group": "CLI v2.1.0", + "pages": [ + "sdk-reference/cli/v2.1.0/auth/index", + "sdk-reference/cli/v2.1.0/sandbox/index", + "sdk-reference/cli/v2.1.0/template/index" + ] + } + ] + }, + { + "version": "v2.0.3", + "groups": [ + { + "group": "CLI v2.0.3", + "pages": [ + "sdk-reference/cli/v2.0.3/auth/index", + "sdk-reference/cli/v2.0.3/sandbox/index", + "sdk-reference/cli/v2.0.3/template/index" + ] + } + ] + }, + { + "version": "v2.0.2", + "groups": [ + { + "group": "CLI v2.0.2", + "pages": [ + "sdk-reference/cli/v2.0.2/auth/index", + "sdk-reference/cli/v2.0.2/sandbox/index", + "sdk-reference/cli/v2.0.2/template/index" + ] + } + ] + }, + { + "version": "v2.0.1", + "groups": [ + { + "group": "CLI v2.0.1", + "pages": [ + "sdk-reference/cli/v2.0.1/auth/index", + "sdk-reference/cli/v2.0.1/sandbox/index", + "sdk-reference/cli/v2.0.1/template/index" + ] + } + ] + }, + { + "version": "v2.0.0", + "groups": [ + { + "group": "CLI v2.0.0", + "pages": [ + "sdk-reference/cli/v2.0.0/auth/index", + "sdk-reference/cli/v2.0.0/sandbox/index", + "sdk-reference/cli/v2.0.0/template/index" + ] + } + ] + }, + { + "version": "v1.9.2", + "groups": [ + { + "group": "CLI v1.9.2", + "pages": [ + "sdk-reference/cli/v1.9.2/auth/index", + "sdk-reference/cli/v1.9.2/sandbox/index", + "sdk-reference/cli/v1.9.2/template/index" + ] + } + ] + }, + { + "version": "v1.9.1", + "groups": [ + { + "group": "CLI v1.9.1", + "pages": [ + "sdk-reference/cli/v1.9.1/auth/index", + "sdk-reference/cli/v1.9.1/sandbox/index", + "sdk-reference/cli/v1.9.1/template/index" + ] + } + ] + }, + { + "version": "v1.9.0", + "groups": [ + { + "group": "CLI v1.9.0", + "pages": [ + "sdk-reference/cli/v1.9.0/auth/index", + "sdk-reference/cli/v1.9.0/sandbox/index", + "sdk-reference/cli/v1.9.0/template/index" + ] + } + ] + }, + { + "version": "v1.8.0", + "groups": [ + { + "group": "CLI v1.8.0", + "pages": [ + "sdk-reference/cli/v1.8.0/auth/index", + "sdk-reference/cli/v1.8.0/sandbox/index", + "sdk-reference/cli/v1.8.0/template/index" + ] + } + ] + }, + { + "version": "v1.7.0", + "groups": [ + { + "group": "CLI v1.7.0", + "pages": [ + "sdk-reference/cli/v1.7.0/auth/index", + "sdk-reference/cli/v1.7.0/sandbox/index", + "sdk-reference/cli/v1.7.0/template/index" + ] + } + ] + }, + { + "version": "v1.6.0", + "groups": [ + { + "group": "CLI v1.6.0", + "pages": [ + "sdk-reference/cli/v1.6.0/auth/index", + "sdk-reference/cli/v1.6.0/sandbox/index", + "sdk-reference/cli/v1.6.0/template/index" + ] + } + ] + }, + { + "version": "v1.5.2", + "groups": [ + { + "group": "CLI v1.5.2", + "pages": [ + "sdk-reference/cli/v1.5.2/auth/index", + "sdk-reference/cli/v1.5.2/sandbox/index", + "sdk-reference/cli/v1.5.2/template/index" + ] + } + ] + }, + { + "version": "v1.5.1", + "groups": [ + { + "group": "CLI v1.5.1", + "pages": [ + "sdk-reference/cli/v1.5.1/auth/index", + "sdk-reference/cli/v1.5.1/sandbox/index", + "sdk-reference/cli/v1.5.1/template/index" + ] + } + ] + }, + { + "version": "v1.5.0", + "groups": [ + { + "group": "CLI v1.5.0", + "pages": [ + "sdk-reference/cli/v1.5.0/auth/index", + "sdk-reference/cli/v1.5.0/sandbox/index", + "sdk-reference/cli/v1.5.0/template/index" + ] + } + ] + }, + { + "version": "v1.4.3", + "groups": [ + { + "group": "CLI v1.4.3", + "pages": [ + "sdk-reference/cli/v1.4.3/auth/index", + "sdk-reference/cli/v1.4.3/sandbox/index", + "sdk-reference/cli/v1.4.3/template/index" + ] + } + ] + }, + { + "version": "v1.4.2", + "groups": [ + { + "group": "CLI v1.4.2", + "pages": [ + "sdk-reference/cli/v1.4.2/auth/index", + "sdk-reference/cli/v1.4.2/sandbox/index", + "sdk-reference/cli/v1.4.2/template/index" + ] + } + ] + }, + { + "version": "v1.4.1", + "groups": [ + { + "group": "CLI v1.4.1", + "pages": [ + "sdk-reference/cli/v1.4.1/auth/index", + "sdk-reference/cli/v1.4.1/sandbox/index", + "sdk-reference/cli/v1.4.1/template/index" + ] + } + ] + }, + { + "version": "v1.4.0", + "groups": [ + { + "group": "CLI v1.4.0", + "pages": [ + "sdk-reference/cli/v1.4.0/auth/index", + "sdk-reference/cli/v1.4.0/sandbox/index", + "sdk-reference/cli/v1.4.0/template/index" + ] + } + ] + }, + { + "version": "v1.3.4", + "groups": [ + { + "group": "CLI v1.3.4", + "pages": [ + "sdk-reference/cli/v1.3.4/auth/index", + "sdk-reference/cli/v1.3.4/sandbox/index", + "sdk-reference/cli/v1.3.4/template/index" + ] + } + ] + }, + { + "version": "v1.3.3", + "groups": [ + { + "group": "CLI v1.3.3", + "pages": [ + "sdk-reference/cli/v1.3.3/auth/index", + "sdk-reference/cli/v1.3.3/sandbox/index", + "sdk-reference/cli/v1.3.3/template/index" + ] + } + ] + }, + { + "version": "v1.3.2", + "groups": [ + { + "group": "CLI v1.3.2", + "pages": [ + "sdk-reference/cli/v1.3.2/auth/index", + "sdk-reference/cli/v1.3.2/sandbox/index", + "sdk-reference/cli/v1.3.2/template/index" + ] + } + ] + }, + { + "version": "v1.3.1", + "groups": [ + { + "group": "CLI v1.3.1", + "pages": [ + "sdk-reference/cli/v1.3.1/auth/index", + "sdk-reference/cli/v1.3.1/sandbox/index", + "sdk-reference/cli/v1.3.1/template/index" + ] + } + ] + }, + { + "version": "v1.3.0", + "groups": [ + { + "group": "CLI v1.3.0", + "pages": [ + "sdk-reference/cli/v1.3.0/auth/index", + "sdk-reference/cli/v1.3.0/sandbox/index", + "sdk-reference/cli/v1.3.0/template/index" + ] + } + ] + }, + { + "version": "v1.2.3", + "groups": [ + { + "group": "CLI v1.2.3", + "pages": [ + "sdk-reference/cli/v1.2.3/auth/index", + "sdk-reference/cli/v1.2.3/sandbox/index", + "sdk-reference/cli/v1.2.3/template/index" + ] + } + ] + }, + { + "version": "v1.2.2", + "groups": [ + { + "group": "CLI v1.2.2", + "pages": [ + "sdk-reference/cli/v1.2.2/auth/index", + "sdk-reference/cli/v1.2.2/sandbox/index", + "sdk-reference/cli/v1.2.2/template/index" + ] + } + ] + }, + { + "version": "v1.2.1", + "groups": [ + { + "group": "CLI v1.2.1", + "pages": [ + "sdk-reference/cli/v1.2.1/auth/index", + "sdk-reference/cli/v1.2.1/sandbox/index", + "sdk-reference/cli/v1.2.1/template/index" + ] + } + ] + }, + { + "version": "v1.2.0", + "groups": [ + { + "group": "CLI v1.2.0", + "pages": [ + "sdk-reference/cli/v1.2.0/auth/index", + "sdk-reference/cli/v1.2.0/sandbox/index", + "sdk-reference/cli/v1.2.0/template/index" + ] + } + ] + }, + { + "version": "v1.0.10", + "groups": [ + { + "group": "CLI v1.0.10", + "pages": [ + "sdk-reference/cli/v1.0.10/auth/index", + "sdk-reference/cli/v1.0.10/sandbox/index", + "sdk-reference/cli/v1.0.10/template/index" + ] + } + ] + }, + { + "version": "v1.0.9", + "groups": [ + { + "group": "CLI v1.0.9", + "pages": [ + "sdk-reference/cli/v1.0.9/auth/index", + "sdk-reference/cli/v1.0.9/sandbox/index", + "sdk-reference/cli/v1.0.9/template/index" + ] + } + ] + }, + { + "version": "v1.0.8", + "groups": [ + { + "group": "CLI v1.0.8", + "pages": [ + "sdk-reference/cli/v1.0.8/auth/index", + "sdk-reference/cli/v1.0.8/sandbox/index", + "sdk-reference/cli/v1.0.8/template/index" + ] + } + ] + }, + { + "version": "v1.0.7", + "groups": [ + { + "group": "CLI v1.0.7", + "pages": [ + "sdk-reference/cli/v1.0.7/auth/index", + "sdk-reference/cli/v1.0.7/sandbox/index", + "sdk-reference/cli/v1.0.7/template/index" + ] + } + ] + }, + { + "version": "v1.0.6", + "groups": [ + { + "group": "CLI v1.0.6", + "pages": [ + "sdk-reference/cli/v1.0.6/auth/index", + "sdk-reference/cli/v1.0.6/sandbox/index", + "sdk-reference/cli/v1.0.6/template/index" + ] + } + ] + }, + { + "version": "v1.0.5", + "groups": [ + { + "group": "CLI v1.0.5", + "pages": [ + "sdk-reference/cli/v1.0.5/auth/index", + "sdk-reference/cli/v1.0.5/sandbox/index", + "sdk-reference/cli/v1.0.5/template/index" + ] + } + ] + }, + { + "version": "v1.0.4", + "groups": [ + { + "group": "CLI v1.0.4", + "pages": [ + "sdk-reference/cli/v1.0.4/auth/index", + "sdk-reference/cli/v1.0.4/sandbox/index", + "sdk-reference/cli/v1.0.4/template/index" + ] + } + ] + }, + { + "version": "v1.0.3", + "groups": [ + { + "group": "CLI v1.0.3", + "pages": [ + "sdk-reference/cli/v1.0.3/auth/index", + "sdk-reference/cli/v1.0.3/sandbox/index", + "sdk-reference/cli/v1.0.3/template/index" + ] + } + ] + }, + { + "version": "v1.0.2", + "groups": [ + { + "group": "CLI v1.0.2", + "pages": [ + "sdk-reference/cli/v1.0.2/auth/index", + "sdk-reference/cli/v1.0.2/sandbox/index", + "sdk-reference/cli/v1.0.2/template/index" + ] + } + ] + }, + { + "version": "v1.0.1", + "groups": [ + { + "group": "CLI v1.0.1", + "pages": [ + "sdk-reference/cli/v1.0.1/auth/index", + "sdk-reference/cli/v1.0.1/sandbox/index", + "sdk-reference/cli/v1.0.1/template/index" + ] + } + ] + }, + { + "version": "v1.0.0", + "groups": [ + { + "group": "CLI v1.0.0", + "pages": [ + "sdk-reference/cli/v1.0.0/auth/index", + "sdk-reference/cli/v1.0.0/sandbox/index", + "sdk-reference/cli/v1.0.0/template/index" + ] + } + ] + } + ] + }, + { + "dropdown": "JavaScript SDK", + "icon": "square-js", + "versions": [ + { + "version": "v2.1.4@latest", + "groups": [ + { + "group": "JavaScript SDK v2.1.4", + "pages": [ + "sdk-reference/js-sdk/v2.1.4/commands/index", + "sdk-reference/js-sdk/v2.1.4/errors/index", + "sdk-reference/js-sdk/v2.1.4/filesystem/index", + "sdk-reference/js-sdk/v2.1.4/sandbox/index" + ] + } + ] + }, + { + "version": "v2.1.3", + "groups": [ + { + "group": "JavaScript SDK v2.1.3", + "pages": [ + "sdk-reference/js-sdk/v2.1.3/commands/index", + "sdk-reference/js-sdk/v2.1.3/errors/index", + "sdk-reference/js-sdk/v2.1.3/filesystem/index", + "sdk-reference/js-sdk/v2.1.3/sandbox/index" + ] + } + ] + }, + { + "version": "v2.1.2", + "groups": [ + { + "group": "JavaScript SDK v2.1.2", + "pages": [ + "sdk-reference/js-sdk/v2.1.2/commands/index", + "sdk-reference/js-sdk/v2.1.2/errors/index", + "sdk-reference/js-sdk/v2.1.2/filesystem/index", + "sdk-reference/js-sdk/v2.1.2/sandbox/index" + ] + } + ] + }, + { + "version": "v2.1.1", + "groups": [ + { + "group": "JavaScript SDK v2.1.1", + "pages": [ + "sdk-reference/js-sdk/v2.1.1/commands/index", + "sdk-reference/js-sdk/v2.1.1/errors/index", + "sdk-reference/js-sdk/v2.1.1/filesystem/index", + "sdk-reference/js-sdk/v2.1.1/sandbox/index" + ] + } + ] + }, + { + "version": "v2.1.0", + "groups": [ + { + "group": "JavaScript SDK v2.1.0", + "pages": [ + "sdk-reference/js-sdk/v2.1.0/commands/index", + "sdk-reference/js-sdk/v2.1.0/errors/index", + "sdk-reference/js-sdk/v2.1.0/filesystem/index", + "sdk-reference/js-sdk/v2.1.0/sandbox/index" + ] + } + ] + }, + { + "version": "v2.0.3", + "groups": [ + { + "group": "JavaScript SDK v2.0.3", + "pages": [ + "sdk-reference/js-sdk/v2.0.3/commands/index", + "sdk-reference/js-sdk/v2.0.3/errors/index", + "sdk-reference/js-sdk/v2.0.3/filesystem/index", + "sdk-reference/js-sdk/v2.0.3/sandbox/index" + ] + } + ] + }, + { + "version": "v2.0.2", + "groups": [ + { + "group": "JavaScript SDK v2.0.2", + "pages": [ + "sdk-reference/js-sdk/v2.0.2/commands/index", + "sdk-reference/js-sdk/v2.0.2/errors/index", + "sdk-reference/js-sdk/v2.0.2/filesystem/index", + "sdk-reference/js-sdk/v2.0.2/sandbox/index" + ] + } + ] + }, + { + "version": "v2.0.1", + "groups": [ + { + "group": "JavaScript SDK v2.0.1", + "pages": [ + "sdk-reference/js-sdk/v2.0.1/commands/index", + "sdk-reference/js-sdk/v2.0.1/errors/index", + "sdk-reference/js-sdk/v2.0.1/filesystem/index", + "sdk-reference/js-sdk/v2.0.1/sandbox/index" + ] + } + ] + }, + { + "version": "v2.0.0", + "groups": [ + { + "group": "JavaScript SDK v2.0.0", + "pages": [ + "sdk-reference/js-sdk/v2.0.0/commands/index", + "sdk-reference/js-sdk/v2.0.0/errors/index", + "sdk-reference/js-sdk/v2.0.0/filesystem/index", + "sdk-reference/js-sdk/v2.0.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.13.2", + "groups": [ + { + "group": "JavaScript SDK v1.13.2", + "pages": [ + "sdk-reference/js-sdk/v1.13.2/commands/index", + "sdk-reference/js-sdk/v1.13.2/errors/index", + "sdk-reference/js-sdk/v1.13.2/filesystem/index", + "sdk-reference/js-sdk/v1.13.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.13.1", + "groups": [ + { + "group": "JavaScript SDK v1.13.1", + "pages": [ + "sdk-reference/js-sdk/v1.13.1/commands/index", + "sdk-reference/js-sdk/v1.13.1/errors/index", + "sdk-reference/js-sdk/v1.13.1/filesystem/index", + "sdk-reference/js-sdk/v1.13.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.13.0", + "groups": [ + { + "group": "JavaScript SDK v1.13.0", + "pages": [ + "sdk-reference/js-sdk/v1.13.0/commands/index", + "sdk-reference/js-sdk/v1.13.0/errors/index", + "sdk-reference/js-sdk/v1.13.0/filesystem/index", + "sdk-reference/js-sdk/v1.13.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.12.0", + "groups": [ + { + "group": "JavaScript SDK v1.12.0", + "pages": [ + "sdk-reference/js-sdk/v1.12.0/commands/index", + "sdk-reference/js-sdk/v1.12.0/errors/index", + "sdk-reference/js-sdk/v1.12.0/filesystem/index", + "sdk-reference/js-sdk/v1.12.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.11.0", + "groups": [ + { + "group": "JavaScript SDK v1.11.0", + "pages": [ + "sdk-reference/js-sdk/v1.11.0/commands/index", + "sdk-reference/js-sdk/v1.11.0/errors/index", + "sdk-reference/js-sdk/v1.11.0/filesystem/index", + "sdk-reference/js-sdk/v1.11.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.10.0", + "groups": [ + { + "group": "JavaScript SDK v1.10.0", + "pages": [ + "sdk-reference/js-sdk/v1.10.0/commands/index", + "sdk-reference/js-sdk/v1.10.0/errors/index", + "sdk-reference/js-sdk/v1.10.0/filesystem/index", + "sdk-reference/js-sdk/v1.10.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.9.1", + "groups": [ + { + "group": "JavaScript SDK v1.9.1", + "pages": [ + "sdk-reference/js-sdk/v1.9.1/commands/index", + "sdk-reference/js-sdk/v1.9.1/errors/index", + "sdk-reference/js-sdk/v1.9.1/filesystem/index", + "sdk-reference/js-sdk/v1.9.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.9.0", + "groups": [ + { + "group": "JavaScript SDK v1.9.0", + "pages": [ + "sdk-reference/js-sdk/v1.9.0/commands/index", + "sdk-reference/js-sdk/v1.9.0/errors/index", + "sdk-reference/js-sdk/v1.9.0/filesystem/index", + "sdk-reference/js-sdk/v1.9.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.8.0", + "groups": [ + { + "group": "JavaScript SDK v1.8.0", + "pages": [ + "sdk-reference/js-sdk/v1.8.0/commands/index", + "sdk-reference/js-sdk/v1.8.0/errors/index", + "sdk-reference/js-sdk/v1.8.0/filesystem/index", + "sdk-reference/js-sdk/v1.8.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.1", + "groups": [ + { + "group": "JavaScript SDK v1.7.1", + "pages": [ + "sdk-reference/js-sdk/v1.7.1/commands/index", + "sdk-reference/js-sdk/v1.7.1/errors/index", + "sdk-reference/js-sdk/v1.7.1/filesystem/index", + "sdk-reference/js-sdk/v1.7.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.0", + "groups": [ + { + "group": "JavaScript SDK v1.7.0", + "pages": [ + "sdk-reference/js-sdk/v1.7.0/commands/index", + "sdk-reference/js-sdk/v1.7.0/errors/index", + "sdk-reference/js-sdk/v1.7.0/filesystem/index", + "sdk-reference/js-sdk/v1.7.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.0", + "groups": [ + { + "group": "JavaScript SDK v1.6.0", + "pages": [ + "sdk-reference/js-sdk/v1.6.0/commands/index", + "sdk-reference/js-sdk/v1.6.0/errors/index", + "sdk-reference/js-sdk/v1.6.0/filesystem/index", + "sdk-reference/js-sdk/v1.6.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.3", + "groups": [ + { + "group": "JavaScript SDK v1.5.3", + "pages": [ + "sdk-reference/js-sdk/v1.5.3/commands/index", + "sdk-reference/js-sdk/v1.5.3/errors/index", + "sdk-reference/js-sdk/v1.5.3/filesystem/index", + "sdk-reference/js-sdk/v1.5.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.2", + "groups": [ + { + "group": "JavaScript SDK v1.5.2", + "pages": [ + "sdk-reference/js-sdk/v1.5.2/commands/index", + "sdk-reference/js-sdk/v1.5.2/errors/index", + "sdk-reference/js-sdk/v1.5.2/filesystem/index", + "sdk-reference/js-sdk/v1.5.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.1", + "groups": [ + { + "group": "JavaScript SDK v1.5.1", + "pages": [ + "sdk-reference/js-sdk/v1.5.1/commands/index", + "sdk-reference/js-sdk/v1.5.1/errors/index", + "sdk-reference/js-sdk/v1.5.1/filesystem/index", + "sdk-reference/js-sdk/v1.5.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.0", + "groups": [ + { + "group": "JavaScript SDK v1.5.0", + "pages": [ + "sdk-reference/js-sdk/v1.5.0/commands/index", + "sdk-reference/js-sdk/v1.5.0/errors/index", + "sdk-reference/js-sdk/v1.5.0/filesystem/index", + "sdk-reference/js-sdk/v1.5.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.4.0", + "groups": [ + { + "group": "JavaScript SDK v1.4.0", + "pages": [ + "sdk-reference/js-sdk/v1.4.0/commands/index", + "sdk-reference/js-sdk/v1.4.0/errors/index", + "sdk-reference/js-sdk/v1.4.0/filesystem/index", + "sdk-reference/js-sdk/v1.4.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.3.0", + "groups": [ + { + "group": "JavaScript SDK v1.3.0", + "pages": [ + "sdk-reference/js-sdk/v1.3.0/commands/index", + "sdk-reference/js-sdk/v1.3.0/errors/index", + "sdk-reference/js-sdk/v1.3.0/filesystem/index", + "sdk-reference/js-sdk/v1.3.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.5", + "groups": [ + { + "group": "JavaScript SDK v1.2.5", + "pages": [ + "sdk-reference/js-sdk/v1.2.5/commands/index", + "sdk-reference/js-sdk/v1.2.5/errors/index", + "sdk-reference/js-sdk/v1.2.5/filesystem/index", + "sdk-reference/js-sdk/v1.2.5/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.4", + "groups": [ + { + "group": "JavaScript SDK v1.2.4", + "pages": [ + "sdk-reference/js-sdk/v1.2.4/commands/index", + "sdk-reference/js-sdk/v1.2.4/errors/index", + "sdk-reference/js-sdk/v1.2.4/filesystem/index", + "sdk-reference/js-sdk/v1.2.4/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.3", + "groups": [ + { + "group": "JavaScript SDK v1.2.3", + "pages": [ + "sdk-reference/js-sdk/v1.2.3/commands/index", + "sdk-reference/js-sdk/v1.2.3/errors/index", + "sdk-reference/js-sdk/v1.2.3/filesystem/index", + "sdk-reference/js-sdk/v1.2.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.2", + "groups": [ + { + "group": "JavaScript SDK v1.2.2", + "pages": [ + "sdk-reference/js-sdk/v1.2.2/commands/index", + "sdk-reference/js-sdk/v1.2.2/errors/index", + "sdk-reference/js-sdk/v1.2.2/filesystem/index", + "sdk-reference/js-sdk/v1.2.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.1", + "groups": [ + { + "group": "JavaScript SDK v1.2.1", + "pages": [ + "sdk-reference/js-sdk/v1.2.1/commands/index", + "sdk-reference/js-sdk/v1.2.1/errors/index", + "sdk-reference/js-sdk/v1.2.1/filesystem/index", + "sdk-reference/js-sdk/v1.2.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.0", + "groups": [ + { + "group": "JavaScript SDK v1.2.0", + "pages": [ + "sdk-reference/js-sdk/v1.2.0/commands/index", + "sdk-reference/js-sdk/v1.2.0/errors/index", + "sdk-reference/js-sdk/v1.2.0/filesystem/index", + "sdk-reference/js-sdk/v1.2.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.1", + "groups": [ + { + "group": "JavaScript SDK v1.1.1", + "pages": [ + "sdk-reference/js-sdk/v1.1.1/commands/index", + "sdk-reference/js-sdk/v1.1.1/errors/index", + "sdk-reference/js-sdk/v1.1.1/filesystem/index", + "sdk-reference/js-sdk/v1.1.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.0", + "groups": [ + { + "group": "JavaScript SDK v1.1.0", + "pages": [ + "sdk-reference/js-sdk/v1.1.0/commands/index", + "sdk-reference/js-sdk/v1.1.0/errors/index", + "sdk-reference/js-sdk/v1.1.0/filesystem/index", + "sdk-reference/js-sdk/v1.1.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.7", + "groups": [ + { + "group": "JavaScript SDK v1.0.7", + "pages": [ + "sdk-reference/js-sdk/v1.0.7/commands/index", + "sdk-reference/js-sdk/v1.0.7/errors/index", + "sdk-reference/js-sdk/v1.0.7/filesystem/index", + "sdk-reference/js-sdk/v1.0.7/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.6", + "groups": [ + { + "group": "JavaScript SDK v1.0.6", + "pages": [ + "sdk-reference/js-sdk/v1.0.6/commands/index", + "sdk-reference/js-sdk/v1.0.6/errors/index", + "sdk-reference/js-sdk/v1.0.6/filesystem/index", + "sdk-reference/js-sdk/v1.0.6/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.5", + "groups": [ + { + "group": "JavaScript SDK v1.0.5", + "pages": [ + "sdk-reference/js-sdk/v1.0.5/commands/index", + "sdk-reference/js-sdk/v1.0.5/errors/index", + "sdk-reference/js-sdk/v1.0.5/filesystem/index", + "sdk-reference/js-sdk/v1.0.5/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.4", + "groups": [ + { + "group": "JavaScript SDK v1.0.4", + "pages": [ + "sdk-reference/js-sdk/v1.0.4/errors/index", + "sdk-reference/js-sdk/v1.0.4/filesystem/index", + "sdk-reference/js-sdk/v1.0.4/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.3", + "groups": [ + { + "group": "JavaScript SDK v1.0.3", + "pages": [ + "sdk-reference/js-sdk/v1.0.3/errors/index", + "sdk-reference/js-sdk/v1.0.3/filesystem/index", + "sdk-reference/js-sdk/v1.0.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.2", + "groups": [ + { + "group": "JavaScript SDK v1.0.2", + "pages": [ + "sdk-reference/js-sdk/v1.0.2/errors/index", + "sdk-reference/js-sdk/v1.0.2/filesystem/index", + "sdk-reference/js-sdk/v1.0.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.1", + "groups": [ + { + "group": "JavaScript SDK v1.0.1", + "pages": [ + "sdk-reference/js-sdk/v1.0.1/errors/index", + "sdk-reference/js-sdk/v1.0.1/filesystem/index", + "sdk-reference/js-sdk/v1.0.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.0", + "groups": [ + { + "group": "JavaScript SDK v1.0.0", + "pages": [ + "sdk-reference/js-sdk/v1.0.0/errors/index", + "sdk-reference/js-sdk/v1.0.0/filesystem/index", + "sdk-reference/js-sdk/v1.0.0/sandbox/index" + ] + } + ] + } + ] + }, + { + "dropdown": "Python SDK", + "icon": "python", + "versions": [ + { + "version": "v2.1.3@latest", + "groups": [ + { + "group": "Python SDK v2.1.3", + "pages": [ + "sdk-reference/python-sdk/v2.1.3/exceptions/index", + "sdk-reference/python-sdk/v2.1.3/sandbox_async/index", + "sdk-reference/python-sdk/v2.1.3/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v2.1.2", + "groups": [ + { + "group": "Python SDK v2.1.2", + "pages": [ + "sdk-reference/python-sdk/v2.1.2/exceptions/index", + "sdk-reference/python-sdk/v2.1.2/sandbox_async/index", + "sdk-reference/python-sdk/v2.1.2/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v2.1.1", + "groups": [ + { + "group": "Python SDK v2.1.1", + "pages": [ + "sdk-reference/python-sdk/v2.1.1/exceptions/index", + "sdk-reference/python-sdk/v2.1.1/sandbox_async/index", + "sdk-reference/python-sdk/v2.1.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v2.1.0", + "groups": [ + { + "group": "Python SDK v2.1.0", + "pages": [ + "sdk-reference/python-sdk/v2.1.0/exceptions/index", + "sdk-reference/python-sdk/v2.1.0/sandbox_async/index", + "sdk-reference/python-sdk/v2.1.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v2.0.2", + "groups": [ + { + "group": "Python SDK v2.0.2", + "pages": [ + "sdk-reference/python-sdk/v2.0.2/exceptions/index", + "sdk-reference/python-sdk/v2.0.2/sandbox_async/index", + "sdk-reference/python-sdk/v2.0.2/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v2.0.1", + "groups": [ + { + "group": "Python SDK v2.0.1", + "pages": [ + "sdk-reference/python-sdk/v2.0.1/exceptions/index", + "sdk-reference/python-sdk/v2.0.1/sandbox_async/index", + "sdk-reference/python-sdk/v2.0.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v2.0.0", + "groups": [ + { + "group": "Python SDK v2.0.0", + "pages": [ + "sdk-reference/python-sdk/v2.0.0/exceptions/index", + "sdk-reference/python-sdk/v2.0.0/sandbox_async/index", + "sdk-reference/python-sdk/v2.0.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.11.1", + "groups": [ + { + "group": "Python SDK v1.11.1", + "pages": [ + "sdk-reference/python-sdk/v1.11.1/exceptions/index", + "sdk-reference/python-sdk/v1.11.1/sandbox_async/index", + "sdk-reference/python-sdk/v1.11.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.11.0", + "groups": [ + { + "group": "Python SDK v1.11.0", + "pages": [ + "sdk-reference/python-sdk/v1.11.0/exceptions/index", + "sdk-reference/python-sdk/v1.11.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.11.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.10.0", + "groups": [ + { + "group": "Python SDK v1.10.0", + "pages": [ + "sdk-reference/python-sdk/v1.10.0/exceptions/index", + "sdk-reference/python-sdk/v1.10.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.10.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.9.0", + "groups": [ + { + "group": "Python SDK v1.9.0", + "pages": [ + "sdk-reference/python-sdk/v1.9.0/exceptions/index", + "sdk-reference/python-sdk/v1.9.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.9.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.8.0", + "groups": [ + { + "group": "Python SDK v1.8.0", + "pages": [ + "sdk-reference/python-sdk/v1.8.0/exceptions/index", + "sdk-reference/python-sdk/v1.8.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.8.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.7.1", + "groups": [ + { + "group": "Python SDK v1.7.1", + "pages": [ + "sdk-reference/python-sdk/v1.7.1/exceptions/index", + "sdk-reference/python-sdk/v1.7.1/sandbox_async/index", + "sdk-reference/python-sdk/v1.7.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.7.0", + "groups": [ + { + "group": "Python SDK v1.7.0", + "pages": [ + "sdk-reference/python-sdk/v1.7.0/exceptions/index", + "sdk-reference/python-sdk/v1.7.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.7.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.6.0", + "groups": [ + { + "group": "Python SDK v1.6.0", + "pages": [ + "sdk-reference/python-sdk/v1.6.0/exceptions/index", + "sdk-reference/python-sdk/v1.6.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.6.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.5.6", + "groups": [ + { + "group": "Python SDK v1.5.6", + "pages": [ + "sdk-reference/python-sdk/v1.5.6/exceptions/index", + "sdk-reference/python-sdk/v1.5.6/sandbox_async/index", + "sdk-reference/python-sdk/v1.5.6/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.5.5", + "groups": [ + { + "group": "Python SDK v1.5.5", + "pages": [ + "sdk-reference/python-sdk/v1.5.5/exceptions/index", + "sdk-reference/python-sdk/v1.5.5/sandbox_async/index", + "sdk-reference/python-sdk/v1.5.5/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.5.4", + "groups": [ + { + "group": "Python SDK v1.5.4", + "pages": [ + "sdk-reference/python-sdk/v1.5.4/exceptions/index", + "sdk-reference/python-sdk/v1.5.4/sandbox_async/index", + "sdk-reference/python-sdk/v1.5.4/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.5.3", + "groups": [ + { + "group": "Python SDK v1.5.3", + "pages": [ + "sdk-reference/python-sdk/v1.5.3/exceptions/index", + "sdk-reference/python-sdk/v1.5.3/sandbox_async/index", + "sdk-reference/python-sdk/v1.5.3/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.5.2", + "groups": [ + { + "group": "Python SDK v1.5.2", + "pages": [ + "sdk-reference/python-sdk/v1.5.2/exceptions/index", + "sdk-reference/python-sdk/v1.5.2/sandbox_async/index", + "sdk-reference/python-sdk/v1.5.2/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.5.1", + "groups": [ + { + "group": "Python SDK v1.5.1", + "pages": [ + "sdk-reference/python-sdk/v1.5.1/exceptions/index", + "sdk-reference/python-sdk/v1.5.1/sandbox_async/index", + "sdk-reference/python-sdk/v1.5.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.5.0", + "groups": [ + { + "group": "Python SDK v1.5.0", + "pages": [ + "sdk-reference/python-sdk/v1.5.0/exceptions/index", + "sdk-reference/python-sdk/v1.5.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.5.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.4.0", + "groups": [ + { + "group": "Python SDK v1.4.0", + "pages": [ + "sdk-reference/python-sdk/v1.4.0/exceptions/index", + "sdk-reference/python-sdk/v1.4.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.4.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.3.5", + "groups": [ + { + "group": "Python SDK v1.3.5", + "pages": [ + "sdk-reference/python-sdk/v1.3.5/exceptions/index", + "sdk-reference/python-sdk/v1.3.5/sandbox_async/index", + "sdk-reference/python-sdk/v1.3.5/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.3.4", + "groups": [ + { + "group": "Python SDK v1.3.4", + "pages": [ + "sdk-reference/python-sdk/v1.3.4/exceptions/index", + "sdk-reference/python-sdk/v1.3.4/sandbox_async/index", + "sdk-reference/python-sdk/v1.3.4/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.3.3", + "groups": [ + { + "group": "Python SDK v1.3.3", + "pages": [ + "sdk-reference/python-sdk/v1.3.3/exceptions/index", + "sdk-reference/python-sdk/v1.3.3/sandbox_async/index", + "sdk-reference/python-sdk/v1.3.3/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.3.2", + "groups": [ + { + "group": "Python SDK v1.3.2", + "pages": [ + "sdk-reference/python-sdk/v1.3.2/exceptions/index", + "sdk-reference/python-sdk/v1.3.2/sandbox_async/index", + "sdk-reference/python-sdk/v1.3.2/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.3.1", + "groups": [ + { + "group": "Python SDK v1.3.1", + "pages": [ + "sdk-reference/python-sdk/v1.3.1/exceptions/index", + "sdk-reference/python-sdk/v1.3.1/sandbox_async/index", + "sdk-reference/python-sdk/v1.3.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.3.0", + "groups": [ + { + "group": "Python SDK v1.3.0", + "pages": [ + "sdk-reference/python-sdk/v1.3.0/exceptions/index", + "sdk-reference/python-sdk/v1.3.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.3.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.2.1", + "groups": [ + { + "group": "Python SDK v1.2.1", + "pages": [ + "sdk-reference/python-sdk/v1.2.1/exceptions/index", + "sdk-reference/python-sdk/v1.2.1/sandbox_async/index", + "sdk-reference/python-sdk/v1.2.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.2.0", + "groups": [ + { + "group": "Python SDK v1.2.0", + "pages": [ + "sdk-reference/python-sdk/v1.2.0/exceptions/index", + "sdk-reference/python-sdk/v1.2.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.2.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.1.0", + "groups": [ + { + "group": "Python SDK v1.1.0", + "pages": [ + "sdk-reference/python-sdk/v1.1.0/exceptions/index", + "sdk-reference/python-sdk/v1.1.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.1.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.0.6", + "groups": [ + { + "group": "Python SDK v1.0.6", + "pages": [ + "sdk-reference/python-sdk/v1.0.6/exceptions/index", + "sdk-reference/python-sdk/v1.0.6/sandbox_async/index", + "sdk-reference/python-sdk/v1.0.6/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.0.5", + "groups": [ + { + "group": "Python SDK v1.0.5", + "pages": [ + "sdk-reference/python-sdk/v1.0.5/exceptions/index", + "sdk-reference/python-sdk/v1.0.5/sandbox_async/index", + "sdk-reference/python-sdk/v1.0.5/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.0.4", + "groups": [ + { + "group": "Python SDK v1.0.4", + "pages": [ + "sdk-reference/python-sdk/v1.0.4/exceptions/index", + "sdk-reference/python-sdk/v1.0.4/sandbox_async/index", + "sdk-reference/python-sdk/v1.0.4/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.0.3", + "groups": [ + { + "group": "Python SDK v1.0.3", + "pages": [ + "sdk-reference/python-sdk/v1.0.3/exceptions/index", + "sdk-reference/python-sdk/v1.0.3/sandbox_async/index", + "sdk-reference/python-sdk/v1.0.3/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.0.2", + "groups": [ + { + "group": "Python SDK v1.0.2", + "pages": [ + "sdk-reference/python-sdk/v1.0.2/exceptions/index", + "sdk-reference/python-sdk/v1.0.2/sandbox_async/index", + "sdk-reference/python-sdk/v1.0.2/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.0.1", + "groups": [ + { + "group": "Python SDK v1.0.1", + "pages": [ + "sdk-reference/python-sdk/v1.0.1/exceptions/index", + "sdk-reference/python-sdk/v1.0.1/sandbox_async/index", + "sdk-reference/python-sdk/v1.0.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.0.0", + "groups": [ + { + "group": "Python SDK v1.0.0", + "pages": [ + "sdk-reference/python-sdk/v1.0.0/exceptions/index", + "sdk-reference/python-sdk/v1.0.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.0.0/sandbox_sync/index" + ] + } + ] + } + ] + }, + { + "dropdown": "Code Interpreter JavaScript SDK", + "icon": "square-js", + "versions": [ + { + "version": "v2.0.0@latest", + "groups": [ + { + "group": "Code Interpreter JavaScript SDK v2.0.0", + "pages": [ + "sdk-reference/code-interpreter-js-sdk/v2.0.0/charts/index", + "sdk-reference/code-interpreter-js-sdk/v2.0.0/consts/index", + "sdk-reference/code-interpreter-js-sdk/v2.0.0/index/index", + "sdk-reference/code-interpreter-js-sdk/v2.0.0/messaging/index", + "sdk-reference/code-interpreter-js-sdk/v2.0.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.1", + "groups": [ + { + "group": "Code Interpreter JavaScript SDK v1.5.1", + "pages": [ + "sdk-reference/code-interpreter-js-sdk/v1.5.1/charts/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.1/consts/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.1/index/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.1/messaging/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.0", + "groups": [ + { + "group": "Code Interpreter JavaScript SDK v1.5.0", + "pages": [ + "sdk-reference/code-interpreter-js-sdk/v1.5.0/charts/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.0/consts/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.0/index/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.0/messaging/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.0", + "groups": [ + { + "group": "Code Interpreter JavaScript SDK v1.2.0", + "pages": [ + "sdk-reference/code-interpreter-js-sdk/v1.2.0/charts/index", + "sdk-reference/code-interpreter-js-sdk/v1.2.0/consts/index", + "sdk-reference/code-interpreter-js-sdk/v1.2.0/index/index", + "sdk-reference/code-interpreter-js-sdk/v1.2.0/messaging/index", + "sdk-reference/code-interpreter-js-sdk/v1.2.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.1", + "groups": [ + { + "group": "Code Interpreter JavaScript SDK v1.1.1", + "pages": [ + "sdk-reference/code-interpreter-js-sdk/v1.1.1/charts/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.1/consts/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.1/index/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.1/messaging/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.0", + "groups": [ + { + "group": "Code Interpreter JavaScript SDK v1.1.0", + "pages": [ + "sdk-reference/code-interpreter-js-sdk/v1.1.0/charts/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.0/consts/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.0/index/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.0/messaging/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.4", + "groups": [ + { + "group": "Code Interpreter JavaScript SDK v1.0.4", + "pages": [ + "sdk-reference/code-interpreter-js-sdk/v1.0.4/charts/index", + "sdk-reference/code-interpreter-js-sdk/v1.0.4/consts/index", + "sdk-reference/code-interpreter-js-sdk/v1.0.4/index/index", + "sdk-reference/code-interpreter-js-sdk/v1.0.4/messaging/index", + "sdk-reference/code-interpreter-js-sdk/v1.0.4/sandbox/index" + ] + } + ] + } + ] + }, + { + "dropdown": "Code Interpreter Python SDK", + "icon": "python", + "versions": [ + { + "version": "v2.0.0@latest", + "groups": [ + { + "group": "Code Interpreter Python SDK v2.0.0", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v2.0.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.2", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.5.2", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.5.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.1", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.5.1", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.5.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.0", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.5.0", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.5.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.1", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.2.1", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.2.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.0", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.2.0", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.2.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.1", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.1.1", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.1.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.0", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.1.0", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.1.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.5", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.0.5", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.0.5/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.4", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.0.4", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.0.4/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.3", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.0.3", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.0.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.2", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.0.2", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.0.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.1", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.0.1", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.0.1/sandbox/index" + ] + } + ] + } + ] + }, + { + "dropdown": "Desktop JavaScript SDK", + "icon": "square-js", + "versions": [ + { + "version": "v2.0.1@latest", + "groups": [ + { + "group": "Desktop JavaScript SDK v2.0.1", + "pages": [ + "sdk-reference/desktop-js-sdk/v2.0.1/sandbox/index" + ] + } + ] + }, + { + "version": "v2.0.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v2.0.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v2.0.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.9.2", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.9.2", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.9.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.9.1", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.9.1", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.9.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.9.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.9.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.9.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.8.1", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.8.1", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.8.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.8.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.8.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.8.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.3", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.7.3", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.7.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.2", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.7.2", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.7.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.1", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.7.1", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.7.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.7.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.7.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.2", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.6.2", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.6.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.1", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.6.1", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.6.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.6.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.6.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.5.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.5.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.4.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.4.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.4.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.3.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.3.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.3.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.2.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.2.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.1", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.1.1", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.1.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.3", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.0.3", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.0.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.2", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.0.2", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.0.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.1", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.0.1", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.0.1/sandbox/index" + ] + } + ] + } + ] + }, + { + "dropdown": "Desktop Python SDK", + "icon": "python", + "versions": [ + { + "version": "v2.0.1@latest", + "groups": [ + { + "group": "Desktop Python SDK v2.0.1", + "pages": [ + "sdk-reference/desktop-python-sdk/v2.0.1/sandbox/index" + ] + } + ] + }, + { + "version": "v2.0.0", + "groups": [ + { + "group": "Desktop Python SDK v2.0.0", + "pages": [ + "sdk-reference/desktop-python-sdk/v2.0.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.4", + "groups": [ + { + "group": "Desktop Python SDK v1.7.4", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.7.4/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.3", + "groups": [ + { + "group": "Desktop Python SDK v1.7.3", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.7.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.2", + "groups": [ + { + "group": "Desktop Python SDK v1.7.2", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.7.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.1", + "groups": [ + { + "group": "Desktop Python SDK v1.7.1", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.7.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.0", + "groups": [ + { + "group": "Desktop Python SDK v1.7.0", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.7.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.5", + "groups": [ + { + "group": "Desktop Python SDK v1.6.5", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.6.5/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.4", + "groups": [ + { + "group": "Desktop Python SDK v1.6.4", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.6.4/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.3", + "groups": [ + { + "group": "Desktop Python SDK v1.6.3", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.6.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.2", + "groups": [ + { + "group": "Desktop Python SDK v1.6.2", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.6.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.1", + "groups": [ + { + "group": "Desktop Python SDK v1.6.1", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.6.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.0", + "groups": [ + { + "group": "Desktop Python SDK v1.6.0", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.6.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.2", + "groups": [ + { + "group": "Desktop Python SDK v1.5.2", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.5.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.1", + "groups": [ + { + "group": "Desktop Python SDK v1.5.1", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.5.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.0", + "groups": [ + { + "group": "Desktop Python SDK v1.5.0", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.5.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.4.0", + "groups": [ + { + "group": "Desktop Python SDK v1.4.0", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.4.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.3.0", + "groups": [ + { + "group": "Desktop Python SDK v1.3.0", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.3.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.0", + "groups": [ + { + "group": "Desktop Python SDK v1.2.0", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.2.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.1", + "groups": [ + { + "group": "Desktop Python SDK v1.1.1", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.1.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.3", + "groups": [ + { + "group": "Desktop Python SDK v1.0.3", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.0.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.2", + "groups": [ + { + "group": "Desktop Python SDK v1.0.2", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.0.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.1", + "groups": [ + { + "group": "Desktop Python SDK v1.0.1", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.0.1/sandbox/index" + ] + } + ] + } + ] + } + ] + } + ], + "global": {} + }, + "logo": { + "light": "/logo/logo_light.svg", + "dark": "/logo/logo_dark.svg" + }, + "appearance": { + "default": "dark" + }, + "background": { + "color": { + "light": "#ffffff", + "dark": "#000000" + }, + "decoration": "windows" + }, + "navbar": { + "links": [ + { + "label": "Sign in", + "href": "https://e2b.dev/auth/sign-in?redirect_to=https%3A%2F%2Fe2b.dev%2Fdocs" + }, + { + "label": "Dashboard", + "href": "https://e2b.dev/dashboard" + } + ], + "primary": { + "type": "github", + "href": "https://github.com/e2b-dev/e2b" + } + }, + "footer": { + "socials": { + "x": "https://x.com/mintlify", + "github": "https://github.com/mintlify", + "linkedin": "https://linkedin.com/company/mintlify" + } + } +} \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/favicon.ico b/apps/web/src/app/(docs)/mintlify-docs/favicon.ico new file mode 100644 index 0000000000..0e138eb9e4 Binary files /dev/null and b/apps/web/src/app/(docs)/mintlify-docs/favicon.ico differ diff --git a/apps/web/src/app/(docs)/mintlify-docs/favicon.jpeg b/apps/web/src/app/(docs)/mintlify-docs/favicon.jpeg new file mode 100644 index 0000000000..b2a0773678 Binary files /dev/null and b/apps/web/src/app/(docs)/mintlify-docs/favicon.jpeg differ diff --git a/apps/web/src/app/(docs)/mintlify-docs/filesystem/download/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/filesystem/download/index.mdx new file mode 100644 index 0000000000..bdd178e8c3 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/filesystem/download/index.mdx @@ -0,0 +1,70 @@ +--- +sidebarTitle: Download data +title: "Download data from sandbox" +--- + +You can download data from the sandbox using the `files.read()` method. + + +```js JavaScript & TypeScript +import fs from 'fs' +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() + +// Read file from sandbox +const content = await sandbox.files.read('/path/in/sandbox') +// Write file to local filesystem +fs.writeFileSync('/local/path', content) +``` +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() + +# Read file from sandbox +content = sandbox.files.read('/path/in/sandbox') +# Write file to local filesystem +with open('/local/path', 'w') as file: + file.write(content) +``` + + + +## Download with pre-signed URL + +Sometimes, you may want to let users from unauthorized environments, like a browser, download files from the sandbox. +For this use case, you can use pre-signed URLs to let users download files securely. + +All you need to do is create a sandbox with the `secure: true` option. A download URL will then be generated with a signature that allows only authorized users to access files. +You can optionally set an expiration time for the URL so that it will be valid only for a limited time. + +```js JavaScript & TypeScript +import fs from 'fs' +import { Sandbox } from '@e2b/code-interpreter' + +// Start a secured sandbox (all operations must be authorized by default) +const sandbox = await Sandbox.create(template, { secure: true }) + +// Create a pre-signed URL for file download with a 10 second expiration +const publicUrl = await sandbox.downloadUrl( + 'demo.txt', { + useSignatureExpiration: 10_000, // optional + }, +) + +// Download a file with a pre-signed URL (this can be used in any environment, such as a browser) +const res = await fetch(publicUrl) +const content = await res.text() +``` +```python Python +from e2b import Sandbox + +# Start a secured sandbox (all operations must be authorized by default) +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. +signed_url = sbx.download_url(path="demo.txt", user="user", use_signature_expiration=10_000) +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/filesystem/index.mdx new file mode 100644 index 0000000000..24dbfefede --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/filesystem/index.mdx @@ -0,0 +1,13 @@ +--- +title: "Filesystem" +sidebarTitle: Overview +--- + +Each E2B Sandbox has its own isolated filesystem. The [Hobby tier](https://e2b.dev/pricing) sandboxes come with 1 GB of the free disk space and [Pro tier](https://e2b.dev/pricing) sandboxes come with 5 GB. + +With E2B SDK you can: +- [Read and write files to the sandbox.](/filesystem/read-write) +- [Watch directory for changes.](/filesystem/watch) +- [Upload data to the sandbox.](/filesystem/upload) +- [Download data from the sandbox.](/filesystem/download) + diff --git a/apps/web/src/app/(docs)/mintlify-docs/filesystem/info/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/filesystem/info/index.mdx new file mode 100644 index 0000000000..47d8858ea5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/filesystem/info/index.mdx @@ -0,0 +1,116 @@ +--- +title: "Get information about a file or directory" +sidebarTitle: File & directory metadata +--- + +You can get information about a file or directory using the `files.getInfo()` / `files.get_info()` methods. Information such as file name, type, and path is returned. + +### Getting information about a file + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() + +// Create a new file +await sandbox.files.write('test_file.txt', 'Hello, world!') + +// Get information about the file +const info = await sandbox.files.getInfo('test_file.txt') + +console.log(info) +// { +// name: 'test_file.txt', +// type: 'file', +// path: '/home/user/test_file.txt', +// size: 13, +// mode: 0o644, +// permissions: '-rw-r--r--', +// owner: 'user', +// group: 'user', +// modifiedTime: '2025-05-26T12:00:00.000Z', +// symlinkTarget: null +// } +``` +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() + +# Create a new file +sandbox.files.write('test_file', 'Hello, world!') + +# Get information about the file +info = sandbox.files.get_info('test_file') + +print(info) +# EntryInfo( +# name='test_file.txt', +# type=, +# path='/home/user/test_file.txt', +# size=13, +# mode=0o644, +# permissions='-rw-r--r--', +# owner='user', +# group='user', +# modified_time='2025-05-26T12:00:00.000Z', +# symlink_target=None +# ) +``` + + +### Getting information about a directory + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() + +// Create a new directory +await sandbox.files.makeDir('test_dir') + +// Get information about the directory +const info = await sandbox.files.getInfo('test_dir') + +console.log(info) +// { +// name: 'test_dir', +// type: 'dir', +// path: '/home/user/test_dir', +// size: 0, +// mode: 0o755, +// permissions: 'drwxr-xr-x', +// owner: 'user', +// group: 'user', +// modifiedTime: '2025-05-26T12:00:00.000Z', +// symlinkTarget: null +// } +``` +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() + +# Create a new directory +sandbox.files.make_dir('test_dir') + +# Get information about the directory +info = sandbox.files.get_info('test_dir') + +print(info) +# EntryInfo( +# name='test_dir', +# type=, +# path='/home/user/test_dir', +# size=0, +# mode=0o755, +# permissions='drwxr-xr-x', +# owner='user', +# group='user', +# modified_time='2025-05-26T12:00:00.000Z', +# symlink_target=None +# ) +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/filesystem/read-write/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/filesystem/read-write/index.mdx new file mode 100644 index 0000000000..53a4571aee --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/filesystem/read-write/index.mdx @@ -0,0 +1,68 @@ +--- +title: "Read & write files" +sidebarTitle: Read & write +--- + +## Reading files + +You can read files from the sandbox filesystem using the `files.read()` method. + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' +const sandbox = await Sandbox.create() +const fileContent = await sandbox.files.read('/path/to/file') +``` +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() +file_content = sandbox.files.read('/path/to/file') +``` + + +## Writing single files + +You can write single files to the sandbox filesystem using the `files.write()` method. + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' +const sandbox = await Sandbox.create() + +await sandbox.files.write('/path/to/file', 'file content') +``` +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() + +await sandbox.files.write('/path/to/file', 'file content') +``` + + +## Writing multiple files + +You can also write multiple files to the sandbox. + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' +const sandbox = await Sandbox.create() + +await sandbox.files.write([ + { path: '/path/to/a', data: 'file content' }, + { path: '/another/path/to/b', data: 'file content' } +]) +``` +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() + +await sandbox.files.write_files([ + { "path": "/path/to/a", "data": "file content" }, + { "path": "another/path/to/b", "data": "file content" } +]) +``` + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/filesystem/upload/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/filesystem/upload/index.mdx new file mode 100644 index 0000000000..45dda0bf7b --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/filesystem/upload/index.mdx @@ -0,0 +1,161 @@ +--- +title: "Upload data to sandbox" +sidebarTitle: Upload data +--- + +You can upload data to the sandbox using the `files.write()` method. + +## Upload single file + + +```js JavaScript & TypeScript +import fs from 'fs' +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() + +// Read file from local filesystem +const content = fs.readFileSync('/local/path') +// Upload file to sandbox +await sandbox.files.write('/path/in/sandbox', content) +``` +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() + +# Read file from local filesystem +with open("path/to/local/file", "rb") as file: + # Upload file to sandbox + sandbox.files.write("/path/in/sandbox", file) +``` + + +## Upload with pre-signed URL + +Sometimes, you may want to let users from unauthorized environments, like a browser, upload files to the sandbox. +For this use case, you can use pre-signed URLs to let users upload files securely. + +All you need to do is create a sandbox with the `secure: true` option. An upload URL will then be generated with a signature that allows only authorized users to upload files. +You can optionally set an expiration time for the URL so that it will be valid only for a limited time. + +```js JavaScript & TypeScript +import fs from 'fs' +import { Sandbox } from '@e2b/code-interpreter' + +// Start a secured sandbox (all operations must be authorized by default) +const sandbox = await Sandbox.create(template, { secure: true }) + +// Create a pre-signed URL for file upload with a 10 second expiration +const publicUploadUrl = await sandbox.uploadUrl( + 'demo.txt', { + useSignatureExpiration: 10_000, // optional + }, +) + +// Upload a file with a pre-signed URL (this can be used in any environment, such as a browser) +const form = new FormData() +form.append('file', 'file content') + +await fetch(publicUploadUrl, { method: 'POST', body: form }) + +// File is now available in the sandbox and you can read it +const content = fs.readFileSync('demo.txt') +``` +```python Python +from e2b import Sandbox +import requests + +# Start a secured sandbox (all operations must be authorized by default) +sandbox = Sandbox.create(timeout=12_000, secure=True) + +# Create a pre-signed URL for file upload with a 10 second expiration +signed_url = sbx.upload_url(path="demo.txt", user="user", use_signature_expiration=10_000) + +form_data = {"file":"file content"} +requests.post(signed_url, data=form_data) +``` + + +## Upload directory / multiple files + + +```js JavaScript & TypeScript +const fs = require('fs'); +const path = require('path'); + +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() + +// Read all files in the directory and store their paths and contents in an array +const readDirectoryFiles = (directoryPath) => { + // Read all files in the local directory + const files = fs.readdirSync(directoryPath); + + // Map files to objects with path and data + const filesArray = files + .filter(file => { + const fullPath = path.join(directoryPath, file); + // Skip if it's a directory + return fs.statSync(fullPath).isFile(); + }) + .map(file => { + const filePath = path.join(directoryPath, file); + + // Read the content of each file + return { + path: filePath, + data: fs.readFileSync(filePath, 'utf8') + }; + }); + + return filesArray; +}; + +// Usage example +const files = readDirectoryContents('/local/dir'); +console.log(files); +// [ +// { path: '/local/dir/file1.txt', data: 'File 1 contents...' }, +// { path: '/local/dir/file2.txt', data: 'File 2 contents...' }, +// ... +// ] + +await sandbox.files.write(files) +``` +```python Python +import os +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() + +def read_directory_files(directory_path): + files = [] + + # Iterate through all files in the directory + for filename in os.listdir(directory_path): + file_path = os.path.join(directory_path, filename) + + # Skip if it's a directory + if os.path.isfile(file_path): + # Read file contents in binary mode + with open(file_path, "rb") as file: + files.append({ + 'path': file_path, + 'data': file.read() + }) + + return files + +files = read_directory_files("/local/dir") +print(files) +# [ +# {"'path": "/local/dir/file1.txt", "data": "File 1 contents..." }, +# { "path": "/local/dir/file2.txt", "data": "File 2 contents..." }, +# ... +# ] + +sandbox.files.write(files) +``` + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/filesystem/watch/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/filesystem/watch/index.mdx new file mode 100644 index 0000000000..a20ac30b26 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/filesystem/watch/index.mdx @@ -0,0 +1,98 @@ +--- +title: "Watch sandbox directory for changes" +sidebarTitle: Watch directory for changes +--- + +You can watch a directory for changes using the `files.watchDir()` method in JavaScript and `files.watch_dir()` method in Python. + + +Since events are tracked asynchronously, their delivery may be delayed. +It's recommended not to collect or close watcher immediately after making a change. + + + +```js JavaScript & TypeScript highlight={7-12} +import { Sandbox, FilesystemEventType } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +const dirname = '/home/user' + +// Start watching directory for changes +const handle = await sandbox.files.watchDir(dirname, async (event) => { + console.log(event) + if (event.type === FilesystemEventType.WRITE) { + console.log(`wrote to file ${event.name}`) + } +}) + +// Trigger file write event +await sandbox.files.write(`${dirname}/my-file`, 'hello') +``` +```python Python highlight={7,12-16} +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() +dirname = '/home/user' + +# Watch directory for changes +handle = sandbox.files.watch_dir(dirname) +# Trigger file write event +sandbox.files.write(f"{dirname}/my-file", "hello") + +# Retrieve the latest new events since the last `get_new_events()` call +events = handle.get_new_events() +for event in events: + print(event) + if event.type == FilesystemEventType.Write: + print(f"wrote to file {event.name}") +``` + + + +## Recursive Watching + +You can enable recursive watching using the parameter `recursive`. + + +When rapidly creating new folders (e.g., deeply nested path of folders), events other than `CREATE` might not be emitted. To avoid this behavior, create the required folder structure in advance. + + + +```js JavaScript & TypeScript highlight={13,17} +import { Sandbox, FilesystemEventType } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +const dirname = '/home/user' + +// Start watching directory for changes +const handle = await sandbox.files.watchDir(dirname, async (event) => { + console.log(event) + if (event.type === FilesystemEventType.WRITE) { + console.log(`wrote to file ${event.name}`) + } +}, { + recursive: true +}) + +// Trigger file write event +await sandbox.files.write(`${dirname}/my-folder/my-file`, 'hello') +``` +```python Python highlight={7,9} +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() +dirname = '/home/user' + +# Watch directory for changes +handle = sandbox.files.watch_dir(dirname, recursive=True) +# Trigger file write event +sandbox.files.write(f"{dirname}/my-folder/my-file", "hello") + +# Retrieve the latest new events since the last `get_new_events()` call +events = handle.get_new_events() +for event in events: + print(event) + if event.type == FilesystemEventType.Write: + print(f"wrote to file {event.name}") +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/images/ai-app-e2b-sandbox-model.png b/apps/web/src/app/(docs)/mintlify-docs/images/ai-app-e2b-sandbox-model.png new file mode 100644 index 0000000000..b4ba6b7d6a Binary files /dev/null and b/apps/web/src/app/(docs)/mintlify-docs/images/ai-app-e2b-sandbox-model.png differ diff --git a/apps/web/src/app/(docs)/mintlify-docs/images/analyze-data-chart.png b/apps/web/src/app/(docs)/mintlify-docs/images/analyze-data-chart.png new file mode 100644 index 0000000000..ea9f89246e Binary files /dev/null and b/apps/web/src/app/(docs)/mintlify-docs/images/analyze-data-chart.png differ diff --git a/apps/web/src/app/(docs)/mintlify-docs/images/byoc-architecture-diagram.png b/apps/web/src/app/(docs)/mintlify-docs/images/byoc-architecture-diagram.png new file mode 100644 index 0000000000..eb8e3e0eb8 Binary files /dev/null and b/apps/web/src/app/(docs)/mintlify-docs/images/byoc-architecture-diagram.png differ diff --git a/apps/web/src/app/(docs)/mintlify-docs/images/custom-sandbox.png b/apps/web/src/app/(docs)/mintlify-docs/images/custom-sandbox.png new file mode 100644 index 0000000000..20f4f331a2 Binary files /dev/null and b/apps/web/src/app/(docs)/mintlify-docs/images/custom-sandbox.png differ diff --git a/apps/web/src/app/(docs)/mintlify-docs/images/diagram.png b/apps/web/src/app/(docs)/mintlify-docs/images/diagram.png new file mode 100644 index 0000000000..4e5cbcb4d0 Binary files /dev/null and b/apps/web/src/app/(docs)/mintlify-docs/images/diagram.png differ diff --git a/apps/web/src/app/(docs)/mintlify-docs/images/diagram.svg b/apps/web/src/app/(docs)/mintlify-docs/images/diagram.svg new file mode 100644 index 0000000000..82cc60b1f9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/images/diagram.svg @@ -0,0 +1,463 @@ + + + + + + + + + + + + + + + + + + + + + + +
+ +

+ Sandbox.create() +

+
+
+
+
+
+ + + +
+ +

+ pause() +

+
+
+
+
+
+ + + +
+ +

+ kill() +

+
+
+
+
+
+ + + +
+ +

+ connect() +

+
+
+
+
+
+ + + +
+ +

+ kill() +

+
+
+
+
+
+
+ + + + + + + + + + + +
+ Running +
+
+ +
+ • Active execution
• Consumes resources
+
+
+
+
+ + + + + + + +
+ Paused +
+
+ +
+ • Preserves memory and files
• Cannot execute code
+
+
+
+
+ + + + + + + +
+ Killed +
+
+ +
+ • Resources released
• Cannot be resumed
+
+
+
+
+
+
+
+
\ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/images/hello-world-chart.png b/apps/web/src/app/(docs)/mintlify-docs/images/hello-world-chart.png new file mode 100644 index 0000000000..fff996100c Binary files /dev/null and b/apps/web/src/app/(docs)/mintlify-docs/images/hello-world-chart.png differ diff --git a/apps/web/src/app/(docs)/mintlify-docs/images/logos/node.svg b/apps/web/src/app/(docs)/mintlify-docs/images/logos/node.svg new file mode 100644 index 0000000000..03768a8852 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/images/logos/node.svg @@ -0,0 +1,4 @@ + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/images/logos/openai.svg b/apps/web/src/app/(docs)/mintlify-docs/images/logos/openai.svg new file mode 100644 index 0000000000..1022b81433 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/images/logos/openai.svg @@ -0,0 +1,12 @@ + + + + + + + + + + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/images/logos/python.svg b/apps/web/src/app/(docs)/mintlify-docs/images/logos/python.svg new file mode 100644 index 0000000000..4248bc074f --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/images/logos/python.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/images/sandbox-build-output.png b/apps/web/src/app/(docs)/mintlify-docs/images/sandbox-build-output.png new file mode 100644 index 0000000000..514720c334 Binary files /dev/null and b/apps/web/src/app/(docs)/mintlify-docs/images/sandbox-build-output.png differ diff --git a/apps/web/src/app/(docs)/mintlify-docs/images/static-chart.png b/apps/web/src/app/(docs)/mintlify-docs/images/static-chart.png new file mode 100644 index 0000000000..2b27ad430c Binary files /dev/null and b/apps/web/src/app/(docs)/mintlify-docs/images/static-chart.png differ diff --git a/apps/web/src/app/(docs)/mintlify-docs/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/index.mdx new file mode 100644 index 0000000000..a33077521e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/index.mdx @@ -0,0 +1,40 @@ +--- +title: "E2B Documentation" +sidebarTitle: Home +icon: house +--- + +import { Concepts } from '/snippets/Concepts.jsx'; +import { CodeInterpreting } from '/snippets/CodeInterpreting.jsx'; +import { Quickstart } from '/snippets/Quickstart.jsx'; + +Here you'll find all the guides, concepts, and SDK references for developing with E2B. + + +```bash JavaScript & TypeScript +npm i @e2b/code-interpreter +``` +```bash Python +pip install e2b-code-interpreter +``` + + +## What is E2B? +E2B is an [open-source](https://github.com/e2b-dev) infrastructure that allows you to run AI-generated code in secure isolated sandboxes in the cloud. +To start and control sandboxes, use our [Python SDK](https://pypi.org/project/e2b/) or [JavaScript SDK](https://www.npmjs.com/package/e2b). + +Some of the typical use cases for E2B are AI data analysis or visualization, running AI-generated code of various languages, playground for coding agents, environment for codegen evals, or running full AI-generated apps like in [Fragments](https://github.com/e2b-dev/fragments). + +### Under the hood +The E2B Sandbox is a small isolated VM the can be started very quickly (~150ms). You can think of it as a small computer for the AI model. You can run many sandboxes at once. Typically, you run separate sandbox for each LLM, user, or AI agent session in your app. +For example, if you were building an AI data analysis chatbot, you would start the sandbox for every user session. + +## Quickstart + + +## Code interpreting with AI + + +## Learn the core concepts + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/cli/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/cli/commands/index.mdx new file mode 100644 index 0000000000..7bbcd56e3d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/cli/commands/index.mdx @@ -0,0 +1,283 @@ +--- +title: "CLI Commands" +--- + +You are reading a legacy (pre v1.0) document. + + +Build your sandbox with our CLI. + + +You can use `--help` flag for more information about commands. + + +--- + +# Auth + +
+ +## `auth login` + +Log in to the CLI. It will save your access token in `~/.e2b` file. + +```bash +e2b auth login +``` + +## `auth logout` + +Log out of the CLI. It will remove your access token from `~/.e2b` file. + +``` +e2b auth logout +``` + +## `auth configure` + +Configure the default team for the CLI. It will be used for all commands that require a team. + +```bash +e2b auth configure +``` + +## `auth info` + +Get info about your current user. + +``` +e2b auth info +``` + +--- + +# Templates + +
+ +## `template init` + +Creates a basic Dockerfile (`./e2b.Dockerfile`) in current directory. +You can then run `e2b template build` to build sandbox template from this Dockerfile. + +```bash +e2b template init +``` + +#### **Options** + + + + + + +## `template build` + +Builds a sandbox template defined by `./e2b.Dockerfile` or `./Dockerfile` from the root directory. +By default, the root directory is the current working directory. +This command also creates the `e2b.toml` config. + +```bash +e2b template build +``` + + +Running `e2b template build` without specifying a template with the `[template]` argument will rebuild template defined by the `e2b.toml` config. + +If there is no `e2b.toml` config a new template will be created. + + +#### **Arguments** + + + Specify the template you want to rebuild. You can use the template name or ID. + + + +#### **Options** + + + Specify the command that should be running when a sandbox starts. + + + Specify the path to the config file. By default, E2B tries to find `e2b.toml` in the root directory. + + + Specify the name of the sandbox template. You can use the template name to start the sandbox in the SDK. The name must be lowercase and contain only letters, numbers, dashes, and underscores. + + + Change the root directory where the command is executed to the `path` directory. + + + Specify the path to Dockerfile. By default E2B tries to find `e2b.Dockerfile` or `Dockerfile` in the root directory. + + + Specify the team that will be used for the sandbox template. You can find team ID in the team settings in the [E2B dashboard](https://e2b.dev/dashboard?tab=team). + + + Specify the number of CPUs that will be used to run the sandbox. The default value is 2. + + + Specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. + + + Specify a build argument for the Dockerfile. The format is `key=value`. You can use this option multiple times. + + +## `template delete` + +Delete the sandbox template specified by the `[template]` argument, `e2b.toml` config in the working directory, or by an interactive selection. +By default, the root directory is the current working directory. + +This command also deletes the `e2b.toml` config. + +```bash +e2b template delete +``` + + +Running `e2b template delete` without specifying a template with the `[template]` argument will delete the template defined by the `e2b.toml` config. + + +#### **Arguments** + + + Specify the template you want to delete. You can use the template name or ID. + + + +#### **Options** + + + Change the root directory where the command is executed to the `path` directory. + + + Specify the path to the config file. By default, E2B tries to find `e2b.toml` in the root directory. + + + Specify the team that will be used for the sandbox template. You can find team ID in the team settings in the [E2B dashboard](https://e2b.dev/dashboard?tab=team). + + + Interactively select sandbox templates you want to delete. + + + Don't ask for confirmation before deleting the sandbox template. + + + +## `template list` + +List your sandbox templates. + +```bash +e2b template list +``` + +#### **Options** + + + Specify the team that will be used for the sandbox template. You can find team ID in the team settings in the [E2B dashboard](https://e2b.dev/dashboard?tab=team). + + + +--- + +# Sandboxes + +
+ +## `sandbox list` + +List your created sandboxes that are running right now. + +```bash +e2b sandbox list +``` + + +## `sandbox logs` +Starts printing logs from the specified sandbox. +If the sandbox is running new logs will be streamed to the terminal. + +The timestamps are in the UTC format. + +This command is useful if you need to debug a running sandbox or check logs from a sandbox that was already closed. + +```bash +e2b sandbox logs +``` + + +You can use `e2b sandbox list` to get a list of running sandboxes and their IDs that can be used with `e2b sandbox logs ` command. + + +#### **Arguments** + + + Specify the ID of the sandbox you want to get logs from. + + +#### **Options** + + + Enable streaming logs until the sandbox is closed. + + +## `sandbox connect` + +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 bash` command in Docker. + +```bash +e2b sandbox connect +``` + + +You can use `e2b sandbox list` to get a list of running sandboxes and their IDs that can be used with `e2b sandbox connect ` command. + + +#### **Arguments** + + + Specify the ID of a running sandbox you want to connect to. + + +## `sandbox create` + +Spawns a sandbox and connects your terminal to the sandbox. +This command can be used to debug your sandbox template. + +This command works similar to the `docker run -it bash` command in Docker. + +```bash +e2b sandbox create +``` + + +Running `e2b sandbox create` without specifying a template with the `[template]` argument will create sandbox defined by the `e2b.toml` config. + + +#### **Arguments** + + + Specify the template you want to create sandbox from. You can use the template name or ID. + + + +#### **Options** + + + Specify the path to the config file. By default, E2B tries to find `e2b.toml` in the root directory. + + +## `sandbox kill` + +Immediately kill a running sandbox. + +```bash +e2b sandbox kill +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/cli/installation/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/cli/installation/index.mdx new file mode 100644 index 0000000000..02fdcf57e3 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/cli/installation/index.mdx @@ -0,0 +1,27 @@ +--- +title: "Installation" +--- + +You are reading a legacy (pre v1.0) document. + + +You build and manage sandbox templates with our CLI. + +The CLI is distributed as an [NPM package](https://www.npmjs.com/package/e2b). + +## Download CLI + +You can install the CLI with following command: + +```bash +npm install -g @e2b/cli@latest +``` + +## Login + +You'll need to login to your account to start using the CLI. +You'll be redirected to the browser after running the following command to finish the login. + +```bash +e2b auth login +``` \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/examples/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/examples/index.mdx new file mode 100644 index 0000000000..c8f751203d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/examples/index.mdx @@ -0,0 +1,149 @@ +--- +title: "Examples" +--- + +You are reading a legacy (pre v1.0) document. + + +Here are some examples of how to use the E2B Code Interpreter package. If you are missing something, please let us know. + +## Minimal example with the sharing context + +The following example demonstrates how to create a shared context between multiple code executions. This is useful when you want to share variables between different code cells. + + +```js JavaScript & TypeScript +import { CodeInterpreter } from '@e2b/code-interpreter' + +const sandbox = await CodeInterpreter.create() +await sandbox.notebook.execCell('x = 1') + +const execution = await sandbox.notebook.execCell('x+=1; x') +console.log(execution.text) // outputs 2 + +await sandbox.close() +``` +```python Python +from e2b_code_interpreter import CodeInterpreter + +with CodeInterpreter() as sandbox: + sandbox.notebook.exec_cell("x = 1") + + execution = sandbox.notebook.exec_cell("x+=1; x") + print(execution.text) # outputs 2 + +``` + + +## Get charts and any display-able data + + +```js JavaScript & TypeScript +import { CodeInterpreter } from '@e2b/code-interpreter' + +const sandbox = await CodeInterpreter.create() + +const code = ` +import matplotlib.pyplot as plt +import numpy as np + +x = np.linspace(0, 20, 100) +y = np.sin(x) + +plt.plot(x, y) +plt.show() +`; + +// you can install dependencies in "jupyter notebook style" +await sandbox.notebook.execCell("!pip install matplotlib") + +const execution = await sandbox.notebook.execCell(code) + +// this contains the image data, you can e.g. save it to file or send to frontend +execution.results[0].png + +await sandbox.close() +``` +```python Python +import base64 +import io + +from matplotlib import image as mpimg, pyplot as plt + +from e2b_code_interpreter import CodeInterpreter + +code = """ +import matplotlib.pyplot as plt +import numpy as np + +x = np.linspace(0, 20, 100) +y = np.sin(x) + +plt.plot(x, y) +plt.show() +""" + +with CodeInterpreter() as sandbox: + # you can install dependencies in "jupyter notebook style" + sandbox.notebook.exec_cell("!pip install matplotlib") + + # plot random graph + execution = sandbox.notebook.exec_cell(code) + +# there's your image +image = execution.results[0].png + +# example how to show the image / prove it works +i = base64.b64decode(image) +i = io.BytesIO(i) +i = mpimg.imread(i, format='PNG') + +plt.imshow(i, interpolation='nearest') +plt.show() +``` + + +## Streaming code output + + +```js JavaScript & TypeScript +import { CodeInterpreter } from "@e2b/code-interpreter"; + +code = ` +import time +import pandas as pd + +print("hello") +time.sleep(3) +data = pd.DataFrame(data=[[1, 2], [3, 4]], columns=["A", "B"]) +display(data.head(10)) +time.sleep(3) +print("world") +` + +const sandbox = await CodeInterpreter.create() + +await sandbox.notebook.execCell(code, { + onStdout: (out) => console.log(out), + onStderr: (outErr) => console.error(outErr), + onResult: (result) => console.log(result.text) +}) +```` +```python Python +from e2b_code_interpreter import CodeInterpreter + +code = """ +import time +import pandas as pd + +print("hello") +time.sleep(3) +data = pd.DataFrame(data=[[1, 2], [3, 4]], columns=["A", "B"]) +display(data.head(10)) +time.sleep(3) +print("world") +""" +with CodeInterpreter() as sandbox: + sandbox.notebook.exec_cell(code, on_stdout=print, on_stderr=print, on_result=(lambda result: print(result.text))) +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/execution/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/execution/index.mdx new file mode 100644 index 0000000000..0be12003ba --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/execution/index.mdx @@ -0,0 +1,198 @@ +--- +title: "Code Execution" +--- + +You are reading a legacy (pre v1.0) document. + + +You can execute code using the notebook module, using the `execCell` method. The method takes a string of code as an argument and returns an object with the results of the execution. + + +```js JavaScript & TypeScript +import { CodeInterpreter } from '@e2b/code-interpreter' + +const code = 'print("Hello, World!")' + +const sandbox = CodeInterpreter.create() +const execution = await sandbox.notebook.execCell(code) +``` + +```python Python +from e2b_code_interpreter import CodeInterpreter + +code = "print('Hello, World!')" + +sandbox = CodeInterpreter.create() +execution = sandbox.notebook.exec_cell(code) +``` + + +The `execCell` method also accepts following optional arguments: +- `kernel id`: The ID of the kernel to execute the code on. If not provided, the default kernel is used. See [here](/legacy/code-interpreter/kernels) for more info on kernels. +- `on stdout`: A callback function to handle standard output messages from the code execution. +- `on_stderr`: A callback function to handle standard error messages from the code execution. +- `on_result`: A callback function to handle the result and display calls of the code execution. + +## Streaming response + +You can use the `on_*` callbacks to handle the output of the code execution as it happens. This is useful for long-running code. You can stream the output to the user as it is generated. + +## Execution object + +The object returned by the `exec cell` method is little bit more complex, it's based on Jupyter. Here's an detailed explanation in the [Jupyter documentation](https://jupyter-client.readthedocs.io/en/stable/messaging.html). + +It contains the following fields: + +- `results`: A list containing result of the cell (interactively interpreted last line) and display calls (e.g. matplotlib plots). +- `logs`: Logs printed to stdout and stderr during execution. +- `error`: An error message, if there was an error during execution of the cell. It works only for Python code, not for system (`!` e.g `!pip install e2b`) commands. + +### Result object + +This object can be created in two different ways: +- Evaluation of the last line: If the last line of the code is an expression, the result is the value of that expression. As you would expect in REPL environments. +- Display calls: Calls to display functions, which can be used to display rich output in the notebook. E.g. [`img.show()`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.show.html), [`display(img)`](https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html), etc. + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by [ipython kernel](https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics) + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, it's always present for the actual result, +the other representations are optional. + +The result has those basic data types: + +#### Text types: +- `text`: text representation of the result +- `html`: html representation of the result +- `markdown`: markdown representation of the result +- `latex`: latex representation of the result + +#### Image types: + - `png`: "base64 encoded png image", + - `jpeg`: "base64 encoded jpeg image", + - `svg`": "svg image", + +#### Other types: + - `json`: "json representation", + - `javascript`: "javascript representation", + - `pdf`: "base64 encoded pdf" + + + If you want to integrate your own display formats or how to implement them for your classes, you can read more in [here](https://github.com/ipython/ipython/blob/main/examples/IPython%20Kernel/Custom%20Display%20Logic.ipynb) + + +### Logs object + +Logs printed to stdout and stderr during execution. Examples of logs are print statements, warnings, subprocess output, etc. + +It contains two fields: +- `stdout`: List of strings, each string is a line printed to stdout. +- `stderr`: List of strings, each string is a line printed to stderr. + +### Error object + +An error message, if there was an error during execution of the cell. + + It works only for Python code, not for system (e.g. `!pip install non_existent_package`) commands. The system commands are executed in a separate process and the output is in stdout/stderr. + + +It contains three fields: +- `name`: Name of the error, e.g. `NameError`, `ValueError`, etc. +- `value`: Value of the error, e.g. `name 'non_existent_variable' is not defined`, etc. +- `traceback`: Traceback of the error. + + +## Example how to interpret the results to LLM + +Here's an example how to return the results to LLM: + + +```js JavaScript & TypeScript +const code = '' +const execution = await sandbox.notebook.execCell(code) + +// There was an error during execution, return the error and its traceback +if (execution.error) { + return `There was an error during execution: ${execution.error.name}: ${execution.error.value}.\n + ${execution.error.traceback}` +} + +// The execution has some result, summarize to LLM, what are the results +if (execution.results.length > 0) { + let message = 'These are results of the execution:\n' + let counter = 1 + for (const result of execution.results) { + message += `Result ${counter++}:\n` + if (result.isMainResult) { + message += `[Main result]: ${result.text}\n` + } else { + message += `[Display data]: ${result.text}\n` + } + if (result.formats().length > 0) { + message += `It has following formats: ${result.formats()}\n` + } + } + + return message +} + +// There were no results, check if there was something is stdout/err +if ( + execution.logs.stdout.length > 0 || + execution.logs.stderr.length > 0 +) { + let message = 'There was no result of the execution, but here are the logs:\n' + if (execution.logs.stdout.length > 0) { + message += `Stdout: ${execution.logs.stdout.join('\n')}\n` + } + if (execution.logs.stderr.length > 0) { + message += `Stderr: ${execution.logs.stderr.join('\n')}\n` + } + + return message +} + +return 'There was no output of the execution.' +``` + +```python Python +code = "" +execution = sandbox.notebook.exec_cell(code) + +# There was an error during execution, return the error and its traceback +if execution.error: + return ( + f"There was an error during execution: {execution.error.name}: {execution.error.value}.\n" + f"{execution.error.traceback}" + ) + +# The execution has some result, summarize to LLM, what are the results +if execution.results: + message = "These are results of the execution:\n" + for i, result in enumerate(execution.results): + message += f"Result {i + 1}:\n" + if result.is_main_result: + message += f"[Main result]: {result.text}\n" + else: + message += f"[Display data]: {result.text}\n" + + if result.formats(): + message += f"It has also following formats: {result.formats()}\n" + + return message + +# There were no results, check if there was something is stdout/err +if execution.logs.stdout or execution.logs.stderr: + message = "There was no result of the execution, but here are the logs:\n" + if execution.logs.stdout: + message += "Stdout: " + "\n".join(execution.logs.stdout) + "\n" + + if execution.logs.stderr: + message += "Stderr: " + "\n".join(execution.logs.stderr) + "\n" + + return message + +return "There was no output of the execution." +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/installation/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/installation/index.mdx new file mode 100644 index 0000000000..de2f260ac0 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/installation/index.mdx @@ -0,0 +1,61 @@ +--- +title: "Code Interpreter SDK" +--- + +You are reading a legacy (pre v1.0) document. + + +E2B's [Code Interpreter SDK](https://github.com/e2b-dev/code-interpreter) allows you to add code interpreting capabilities to your AI apps. + +The code interpreter runs inside the [E2B Sandbox](https://github.com/e2b-dev/e2b) - an open-source secure sandbox made for running untrusted AI-generated code and AI agents. +- ✅ Works with any LLM and AI framework +- ✅ Supports streaming content like charts and stdout, stderr +- ✅ Python & JS SDK +- ✅ Runs on serverless and edge functions +- ✅ Runs AI-generated code in secure sandboxed environments +- ✅ 100% open source (including [infrastructure](https://github.com/e2b-dev/infra)) + +## Quickstart + +### 1. Install SDK + + +```bash JavaScript/TypeScript +npm i @e2b/code-interpreter +``` + +```bash Python +pip install e2b_code_interpreter +``` + + +### 2. Execute code with code interpreter inside sandbox + + + +```ts JavaScript +import { CodeInterpreter } from '@e2b/code-interpreter' + +const sandbox = await CodeInterpreter.create() +await sandbox.notebook.execCell('x = 1') + +const execution = await sandbox.notebook.execCell('x+=1; x') +console.log(execution.text) // outputs 2 + +await sandbox.close() +``` + +```py Python +from e2b_code_interpreter import CodeInterpreter + +with CodeInterpreter() as sandbox: + sandbox.notebook.exec_cell("x = 1") + + execution = sandbox.notebook.exec_cell("x+=1; x") + print(execution.text) # outputs 2 +``` + + +### 3. Hello World guide +Dive depeer and check out the [JavaScript](/legacy/hello-world/js) and [Python](/legacy/hello-world/py) the Hello World guides to learn how o connect code interpreter LLMs. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/kernels/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/kernels/index.mdx new file mode 100644 index 0000000000..ea36e8d5ec --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/kernels/index.mdx @@ -0,0 +1,30 @@ +--- +title: "Kernels" +--- + +You are reading a legacy (pre v1.0) document. + + +In this section you can find information about kernels and how to use them in Code Interpreter SDK. Having multiple kernels allows you to run code in separate contexts and optionally also languages. + +By default the template starts with one default kernel. This kernel is used to execute code, if you don't specify `kernelID`. You can imagine kernel as a separate environment where code is executed. You can have multiple kernels running at the same time. Each kernel has its own state, so you can have multiple kernels running different code at the same time. + +Kernel will be kept alive with the sandbox even if you disconnect. + +## Creating a new kernel + +To create a new kernel there's a `create_kernel` in Python and `createKernel()` in JavaScript/TypeScript method in the `CodeInterpreter` class. This method takes two optional arguments: +- `cwd` - working directory for the kernel, all system commands and file operations will be executed in this directory +- `kernel name` - kernel spec name (defaults to default kernel spec for server). In our case it's `python3`. If you want to use another kernel, you have to install in the template first. In that case you probably want to use [Custom Template](/legacy/code-interpreter/template). + +## Restarting a kernel + +To restart a kernel you can use `restart` method. This method takes one argument - `kernelID`, if not specifed it will restart the default kernel. This method will restart the kernel and clear its state. + +## Listing kernels + +To list all kernels you can use `list` method. This method returns an array of all running kernels with their IDs and kernel spec names. + +## Shutting down a kernel + +To shutdown a kernel you can use `shutdown` method. This method takes one argument - `kernelID`, if not specifed it will delete the default kernel. This method will delete the kernel and all its state. diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/template/index.mdx new file mode 100644 index 0000000000..d6ff68a4a5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/code-interpreter/template/index.mdx @@ -0,0 +1,61 @@ +--- +title: "Using custom sandbox template & custom compute with Code Interpreter SDK" +--- + +You are reading a legacy (pre v1.0) document. + + +# Using custom sandbox template & custom compute with Code Interpreter SDK + +If you want to customize the Code Interprerter sandbox (e.g.: add a preinstalled package) you can do that by using a [custom sandbox template](https://e2b.dev/docs/sandbox/templates/overview). + + +## Step-by-step guide +1. Create custom sandbox by following [this guide](/legacy/guide/custom-sandbox) + +2. Use prebuilt [E2B Code Interpreter image](https://hub.docker.com/r/e2bdev/code-interpreter) by replacing the `FROM` command in your `e2b.Dockerfile` with following + + ```sh + FROM e2bdev/code-interpreter:latest + ``` + +3. Run the following in the same directory where's your `e2b.toml` + ```sh + e2b template build -c "/root/.jupyter/start-up.sh" + ``` + +4. Use your custom sandbox with Code Interpreter SDK + + + ```python Python + from e2b_code_interpreter import CodeInterpreter + sandbox = CodeInterpreter(template="your-custom-sandbox-name") + execution = sandbox.notebook.exec_cell("print('hello')") + sandbox.close() + + # Or you can use `with` which handles closing the sandbox for you + with CodeInterpreter(template="your-custom-sandbox-name") as sandbox: + execution = sandbox.notebook.exec_cell("print('hello')") + ``` + + ```js JavaScript & TypeScript + import { CodeInterpreter } from '@e2b/code-interpreter' + const sandbox = await CodeInterpreter.create({ template: 'your-custom-sandbox-name' }) + const execution = await sandbox.notebook.execCell('print("hello")') + await sandbox.close() + ``` + + + +## Customize CPU & RAM of your sandbox +You can customize number of CPUs and MiB of RAM for your sandbox. To achieve that, specify the `--cpu-count` and `--memory-mb` options during the build step: +```sh +e2b template build -c "/home/user/.jupyter/start-up.sh" --cpu-count 4 --memory-mb 4096 +``` +The above will create a custom sandbox with 4 CPUs a 4 GiB of RAM. + +## How to install another Python kernels + +Jupyter has ability to work with different than Python kernel. It even supports multiple kernels in one notebook. If you want to install another kernels. + +You can find list of available kernels [here](https://github.com/jupyter/jupyter/wiki/Jupyter-kernels). Each has a little bit different installation process, but in general you need to install kernel package and register it in jupyter. diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/examples/clone-repo/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/examples/clone-repo/index.mdx new file mode 100644 index 0000000000..6b55d9cbff --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/examples/clone-repo/index.mdx @@ -0,0 +1,7 @@ +--- +title: "Clone GitHub Repository" +--- + +You are reading a legacy (pre v1.0) document. + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/getting-help/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/getting-help/index.mdx new file mode 100644 index 0000000000..31ddc50828 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/getting-help/index.mdx @@ -0,0 +1,12 @@ +--- +title: "Getting help" +--- + +You are reading a legacy (pre v1.0) document. + + +If you have any questions, issues, or feature requests, please reach out on of the following channels: +- Send us an email at [hello@e2b.dev](mailto:hello@e2b.dev) +- Talk to us on our [Discord server](https://discord.gg/U7KEcGErtQ) +- Open an issue on [our GitHub](https://github.com/e2b-dev/e2b) +- Reach out on [Twitter / X](https://x.com/e2b) \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/getting-started/api-key/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/getting-started/api-key/index.mdx new file mode 100644 index 0000000000..a43eb73fc6 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/getting-started/api-key/index.mdx @@ -0,0 +1,32 @@ +--- +title: Use API key +--- + +You are reading a legacy (pre v1.0) document. + + +To use the API key, you either: +- **Set the API key as the `E2B_API_KEY` environment variable** +- Or pass it directly to the `CodeInterpreter` constructor like this: + + +```js JavaScript & TypeScript +import { CodeInterpreter } from '@e2b/code-interpreter' + +const sandbox = await CodeInterpreter.create({ apiKey: 'YOUR_API_KEY' }) +await sandbox.notebook.execCell('x = 1') + +const execution = await sandbox.notebook.execCell('x+=1; x') +console.log(execution.text) // outputs 2 + +await sandbox.close() +``` +```python Python +from e2b_code_interpreter import CodeInterpreter + +with CodeInterpreter(api_key="YOUR_API_KEY") as code_interpreter: + sandbox.notebook.exec_cell("x = 1") + execution = sandbox.notebook.exec_cell("x+=1; x") + print(execution.text) # outputs 2 +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/getting-started/installation/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/getting-started/installation/index.mdx new file mode 100644 index 0000000000..6a9be366fd --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/getting-started/installation/index.mdx @@ -0,0 +1,46 @@ +--- +title: "Installation" +--- + +You are reading a legacy (pre v1.0) document. + + +You create and control sandboxes with our SDKs. +We offer SDKs for [JavaScript / TypeScript](https://www.npmjs.com/package/e2b), and [Python](https://pypi.org/project/e2b/). + + + + Usable both in Node.js and in the browser. Requires at least Node.js 18.0. + + + Requires at least Python 3.8. + + + +You can install them using the following commands: + + +```bash JavaScript & TypeScript +npm install e2b +``` +```bash Python +pip install e2b +``` + + + +## Next steps + +1. [Get your API key](/legacy/getting-started/api-key) +1. [Explore the Sandbox API](/legacy/sandbox/api/envs) +{/* 1. [Follow the "Hello World" example](/guides/) */} +{/* 1. [Check out the official guides](/guides/overview) */} +{/* 1. [Explore integrations with AI frameworks and LLMs](/integrations/overview) */} diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/guide/beta-code-interpreter-language-runtimes/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/guide/beta-code-interpreter-language-runtimes/index.mdx new file mode 100644 index 0000000000..5b30171525 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/guide/beta-code-interpreter-language-runtimes/index.mdx @@ -0,0 +1,59 @@ +--- +title: "Code Interpreter SDK Beta - Language Runtimes" +--- + +You are reading a legacy (pre v1.0) document. + + +This guide shows how to run AI-generated code in different language runtimes using the new Code Interpreter beta SDK. +The following language runtimes are currently supported: +- **Python** +- **JavaScript** +- **Java** +- **Bash** +- **R** + + +Want more language runtimes? Reached out to us on [Discord](https://discord.gg/U7KEcGErtQ) or over [email](emailto:contact@e2b.dev). + + +## 1. Install the Code Interpreter beta SDK +The latest beta versions you should install can be found in NPM/PyPi release history: +- **JavaScript & TypeScript** + - [Latest release](https://www.npmjs.com/package/@e2b/code-interpreter?activeTab=versions) with *rc* tag for `@e2b/code-interpreter` +- **Python** + - [Latest release](https://pypi.org/project/e2b-code-interpreter/#history) with *PRE-RELEASE* for `e2b-code-interpreter` + + +## 2. Active kernel for the desired language +Each of the supported language runtimes has its own kernel. + + +```python Python +from e2b_code_interpreter import CodeInterpreter + +sandbox = CodeInterpreter() + +# 1. Set JS kernel - available kernel names: 'r', 'javascript', 'java', 'bash' +js_id = sandbox.notebook.create_kernel(kernel_name="javascript") +# 2. Run JS code inside code interpreter! +execution = sandbox.notebook.exec_cell("console.log('Hello World!')", kernel_id=js_id) +print(execution) +# 3. Use Python again +sandbox.notebook.exec_cell("print('Hello World!')") +``` + +```js JavaScript & TypeScript +import { CodeInterpreter } from '@e2b/code-interpreter' + +const sandbox = await CodeInterpreter.create() + +// 1. Set JS kernel - available kernel names: 'r', 'javascript', 'java', 'bash' +const jsID = await sandbox.notebook.createKernel({ kernelName: 'javascript' }) +// 2. Run JS code inside code interpreter! +const execution = await sandbox.notebook.execCell("console.log('Hello World!')", { kernelID: jsID }) +console.log(execution) +// 3. Use Python again +await sandbox.notebook.execCell('print("Hello World!")') +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/guide/beta-migration/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/guide/beta-migration/index.mdx new file mode 100644 index 0000000000..9b8fc04649 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/guide/beta-migration/index.mdx @@ -0,0 +1,705 @@ +--- +title: "SDK Beta - Migration Guide" +--- + +You are reading a legacy (pre v1.0) document. + + +The following guide shows how to migrate your code from the current Core SDKs (`e2b`) and Code Interpreter SDKs (`@e2b/code-interpreter`/`e2b-code-interpreter`) to the beta versions. + +The latest beta versions you should install can be found in NPM/PyPi release history: +- **JavaScript & TypeScript** + - [Latest release](https://www.npmjs.com/package/e2b?activeTab=versions) with *rc* tag for `e2b` + - [Latest release](https://www.npmjs.com/package/@e2b/code-interpreter?activeTab=versions) with *rc* tag for `@e2b/code-interpreter` +- **Python** + - [Latest release](https://pypi.org/project/e2b/#history) with *PRE-RELEASE* for `e2b` + - [Latest release](https://pypi.org/project/e2b-code-interpreter/#history) with *PRE-RELEASE* for `e2b-code-interpreter` + +## Table of contents +- [Core Sandbox SDK changes](#core-sandbox-sdk-changes) + - [Creating sandbox](#creating-sandbox) + - [Modifying sandbox timeout](#modifying-sandbox-timeout) + - [Reconnecting](#reconnecting) + - [Writing files to sandbox](#writing-files-to-sandbox) + - [Reading files from sandbox](#reading-files-from-sandbox) + - [Uploading data to sandbox](#uploading-data-to-sandbox) + - [Downloading files from sandbox](#downloading-files-from-sandbox) + - [Running processes](#running-processes) + - [Watching for files' changes](#watching-for-files-changes) + - [Accessing sandbox ID](#accessing-sandbox-id) + - [Getting sandbox upload URL](#getting-sandbox-upload-url) + - [Configuring sandbox `cwd`](#configuring-sandbox-cwd) + - [Timeouts](#timeouts) + - [Listing sandboxes](#listing-sandboxes) + - [Getting sandbox url](#getting-sandbox-url) + - [Code Interpreter SDK changes](#code-interpreter-sdk-changes) + - [Executing code](#executing-code) + - [Custom template](#custom-template) + - [Python Async](#python-async) + - [Watching for files' changes in async Python SDK](#watching-for-files-changes-in-async-python-sdk) + - [Running background commands in async Python SDK](#running-background-commands-in-async-python-sdk) + + +##

Core Sandbox SDK changes

+These changes affect both the `e2b` Core SDKs and Code Interpreter SDKs (`@e2b/code-interpreter`/`e2b-code-interpreter`) because the Code Interpreter uses the Core SDK. + + +If you are using a custom template you need to rebuild it by calling `e2b template build` in the directory with the template. + + +## Creating sandbox + +When creating a sandbox you now **specify the sandbox timeout — how long the sandbox will exist**. If you don't specify the timeout the sandbox will be closed after 5 minutes. + +You also no longer call the `.close()` method when you are done with the sandbox. Sandbox will be automatically closed and killed after the timeout. + +You can use `.kill()` to kill the sandbox immediately if you are sure you won't need it anymore. + + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +// const sandbox = await Sandbox.create() +// await sandbox.close() + +// Now +const sandbox = await Sandbox.create({ timeoutMs: 300_000 }) +``` +```python Python +from e2b import Sandbox + +# Before +# sandbox = Sandbox.create() +# sandbox.close() + +# Now +sandbox = Sandbox.create(timeout=300) +``` + + +If you need to use a [custom sandbox template](/legacy/guide/custom-sandbox) you pass the template as the first parameter: + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +// const sandbox = await Sandbox.create({ template: 'template-name-or-id' }) +// await sandbox.close() + +// Now +const sandbox = await Sandbox.create('template-name-or-id', { + timeoutMs: 300_000, +}) +``` +```python Python +from e2b import Sandbox + +# Before +# sandbox = Sandbox.create(template='template-name-or-id') +# sandbox.close() + +# Now +sandbox = Sandbox.create(template='template-name-or-id', timeout=300) +``` + + +## Modifying sandbox timeout +If you need to change how long the sandbox should stay alive after it was created, you can use `.setTimeout()`/`.set_timeout()` method. +It will modify the timeout of the sandbox. + + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +// const sandbox = await Sandbox.create() +// await sandbox.keepAlive(600_000) + +// Now +const sandbox = await Sandbox.create({ timeoutMs: 300_000 }) +await sandbox.setTimeout(600_000) +``` +```python Python +from e2b import Sandbox + +# Before +# sandbox = Sandbox.create() +# sandbox.keep_alive(600) + +# Now +sandbox = Sandbox.create(timeout=300) +sandbox.set_timeout(600) +``` + + +## Reconnecting +When connection to an existing sandbox use `.connect()`/`.connect()` method instead of `.reconnect()`/`.reconnect()`. + +Instead of using `.keepAlive()`/`.keep_alive()` method to prevent the sandbox from closing until you reconnect use `.setTimeout()`/`.set_timeout()` method. +Because the timeout is set when the sandbox is created, you may not need to set the timeout when reconnecting at all now. + + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +// const sandbox = await Sandbox.create() +// await sandbox.keepAlive(600_000) +// await sandbox.close() + +// const existingSandbox = await Sandbox.reconnect(sandbox.id) + +// Now +const sandbox = await Sandbox.create({ timeoutMs: 600_000 }) + +const existingSandbox = await Sandbox.connect(sandbox.sandboxId) +``` +```python Python +from e2b import Sandbox + +# Before +# sandbox = Sandbox.create() +# sandbox.keep_alive(600) +# sandbox.close() + +# existing_sandbox = Sandbox.reconnect(sandbox.id) + +# Now +sandbox = Sandbox.create(timeout=600) + +existing_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + +## Writing files to sandbox +Use `.files.write()` method to write files to the sandbox. + +The method accepts `path` in the sandbox as the first argument and the `data` as the second argument. + + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +// await sandbox.filesystem.write('/hello.txt', 'Hello World!') + +// Now +await sandbox.files.write('/path/in/sandbox', 'Hello World!') +``` +```python Python +from e2b import Sandbox + +# Before +# sandbox.filesystem.write("/hello.txt", "Hello World!") + +# Now +sandbox.files.write("/path/in/sandbox", "Hello World!") +``` + + +## Reading files from sandbox +Use `.files.read()` method to read files from the sandbox. + +The method accepts `path` in the sandbox as the first argument and optional `format` as the second argument. + + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +//const content = await sandbox.downloadFile('/path/in/sandbox') + +// Now +const content = await sandbox.files.read('/path/in/sandbox') +``` +```python Python +from e2b import Sandbox + +# Before +# content = sandbox.download_file("/path/in/sandbox") + +# Now +content = sandbox.files.read("/path/in/sandbox") +``` + + +## Uploading data to sandbox +Use `.files.write()` method to upload files to the sandbox. + +The method accepts `path` in the sandbox as the first argument and the `data` as the second argument. + + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +// const content = fs.readFileSync('/local/path') +// await sandbox.uploadFile(content, '/path/in/sandbox') + +// Now +const content = fs.readFileSync('/local/path') +await sandbox.files.write('/path/in/sandbox', content) +``` +```python Python +from e2b import Sandbox + +# Before +# with open("path/to/local/file", "rb") as file: +# sandbox.upload_file(file) + +# Now +with open("path/to/local/file", "rb") as file: + sandbox.files.write("/path/in/sandbox", file) +``` + + +## Downloading files from sandbox +Use `.files.read()` method to download files from the sandbox. + +The method accepts `path` in the sandbox as the first argument and optional `format` as the second argument. + + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +//const content = await sandbox.downloadFile('/path/in/sandbox') + +// Now +const content = await sandbox.files.read('/path/in/sandbox') +``` +```python Python +from e2b import Sandbox + +# Before +# content = sandbox.download_file("/path/in/sandbox") + +# Now +content = sandbox.files.read("/path/in/sandbox") +``` + + + +## Running processes +You execute processes by calling `.commands.run()` method. By default, the method waits for the command to finish. + +You can specify the timeout for the command execution by passing `timeoutMs`/`timeout` option. The default timeout is 60 seconds. + +If the command fails with a non-zero exit it will raise `CommandExitError` in Javascript, or `CommandExitException` in Python, and you can catch and inspect the error for more info. + + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +// const sandbox = await Sandbox.create() +// const result = await sandbox.process.startAndWait({ +// cmd: 'echo "Hello, world!"', +// onStderr: (msg) => console.log(msg.line), +// onStdout: (msg) => console.log(msg.line), +// }) + +// Now +const result = await sandbox.commands.run('echo "Hello, World!"', { + onStderr(output) { console.log(output) }, + onStdout(output) { console.log(output) }, + timeoutMs: 60_000, +}) +``` +```python Python +from e2b import Sandbox + +# Before +# sandbox = Sandbox.create() +# result = sandbox.process.start_and_wait( +# cmd='echo "Hello, world!"', +# on_stderr=lambda msg: print(msg.line), +# on_stdout=lambda msg: print(msg.line), +# ) + +# Now +result = sandbox.commands.run( + cmd='echo "Hello, World!"', + timeout=60, + on_stdout=lambda output: print(output), + on_stderr=lambda output: print(output), +) +``` + +If you want to run the command in the background use `background: true`/`background=True` option. +You can then use `.wait()` method to wait for the command to finish. + + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +// const sandbox = await Sandbox.create() +// const process = await sandbox.process.start({ +// cmd: 'sleep 10; echo "Hello, world!"', +// onStderr: (msg) => console.log(msg.line), +// onStdout: (msg) => console.log(msg.line), +// }) + +// const result = await process.wait() + +// Now +const command = await sandbox.commands.run('sleep 10; echo "Hello, world!"', { + onStderr(output) { console.log(output) }, + onStdout(output) { console.log(output) }, + background: true, +}) + +const result = await command.wait() +``` +```python Python +from e2b import Sandbox + +# Before +# sandbox = Sandbox.create() +# process = sandbox.process.start( +# cmd='echo "Hello, world!"', +# on_stderr=lambda msg: print(msg.line), +# on_stdout=lambda msg: print(msg.line), +# ) + +# result = process.wait() + +# Now +command = sandbox.commands.run( + cmd='echo "Hello, World!"', + background=True, +) + +result = command.wait( + on_stderr=lambda output: print(output), + on_stdout=lambda output: print(output), +) +``` + + + +## Watching for files' changes + + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +// const sandbox = await Sandbox.create() +// const watcher = sandbox.filesystem.watchDir('/path/in/sandbox') +// watcher.addEventListener((event) => console.log(event)) +// await watcher.start() + +// Now +const sandbox = await Sandbox.create() +await sandbox.files.watchDir('/path/in/sandbox', (event) => console.log(event)) +``` +```python Python +from e2b import Sandbox + +# Before +# sandbox = Sandbox.create() + +# watcher = sandbox.filesystem.watch_dir("/path/in/sandbox") +# watcher.add_event_listener(lambda event: print(event)) +# watcher.start() + +# Now +sandbox = Sandbox.create() +watcher = sandbox.files.watch_dir("/path/in/sandbox") + +for event in watcher: + print(event) +``` + + +## Accessing sandbox ID +The `id` property on the sandbox/code interpreter instance is now named `sandboxId`/`sandbox_id`. + + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +// const sandboxId = await sandbox.id + +// Now +const sandboxId = await sandbox.sandboxId +``` +```python Python +from e2b import Sandbox + +# Before +# sandbox_id = sandbox.id + +# Now +sandbox_id = sandbox.sandbox_id +``` + + +## Getting sandbox upload URL +The `.fileURL`/`.file_url()` is now `.uploadURL`/`.upload_url()` method that takes an optional argument that specifies the path in the sandbox where the file will be uploaded. + +If the path is not specified the file will be uploaded to the home dir — `/home/user`. + + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +// const url = await sandbox.fileURL + +// Now +const url = await sandbox.uploadUrl('/path/in/sandbox') +``` +```python Python +from e2b import Sandbox + +# Before +# url = sandbox.file_url() + +# Now +url = sandbox.upload_url('/path/in/sandbox') +``` + + +## Configuring sandbox `cwd` +Previously you could set the sandbox working directory by passing `cwd` option when creating the sandbox. +Right now this is not supported because it leads to subtle bugs especially when reconnecting to an existing sandbox. + +If you need this feature please reach out to us on [Discord](https://discord.com/invite/U7KEcGErtQ) or [GitHub](https://github.com/e2b-dev/e2b) so we can prioritize it. + +## Timeouts +There are now two types of timeouts that you can pass as parameters: +1. `request_timeout`/`requestTimeoutMs` sets how long the operation should wait for connection/processing. +This is useful for ensuring that none of the sandbox operations hang indefinitely. +2. `timeout`/`timeoutMs` which is used for setting the maximum length of long-running operations like executing code, running processes, or the sandbox itself. + +## Listing sandboxes +Some properties returned from the `Sandbox.list` method have been renamed. + + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +// const sandboxes = await Sandbox.list() + +// `sandboxes` is an array of `RunningSandbox` objects: +// { +// sandboxID: string +// templateID: string +// alias?: string +// metadata?: SandboxMetadata +// startedAt: Date +// } + +// Now +const sandboxes = await Sandbox.list() + +// `sandboxes` is an array of `SandboxInfo` objects: +// { +// sandboxId: string +// templateId: string +// name?: string +// metadata: Record +// startedAt: Date +// } +``` +```python Python +from e2b import Sandbox + +# Before +# sandboxes = Sandbox.list() + +# `sandboxes` is an array of `RunningSandbox` objects: +# class RunningSandbox(BaseModel): +# sandbox_id: str +# template_id: str +# alias: Optional[str] +# metadata: Optional[Dict[str, str]] +# cpu_count: int +# memory_mb: int +# started_at: datetime + +# Now +sandboxes = Sandbox.list() + +# `sandboxes` is an array of `SandboxInfo` objects: +# @dataclass +# class SandboxInfo: +# sandbox_id: str +# template_id: str +# name: Optional[str] +# metadata: Dict[str, str] +# started_at: datetime + +``` + + + +## Getting sandbox url +The method for getting the sandbox host has changed from `sandbox.getHostname/sandbox.get_hostname` to `sandbox.getHost/sandbox.get_host`. +It now requires specifying the port. + + +```js JavaScript & TypeScript +import Sandbox from 'e2b' + +// Before +// const host = await sandbox.getHostname(80) + +// Now +const host = await sandbox.getHost(80) +``` +```python Python +from e2b import Sandbox + +# Before +# host = sandbox.get_hostname(80) + +# Now +host = sandbox.get_host(80) +``` + + + +##

Code Interpreter SDK changes

+All the previously mentioned changes to the Core SDK also apply to the Code Interpreter SDK. +Apart from them, the changes to the Code Interpreter SDK are very minimal: + +## Executing code +When executing code via JS/TS Code Interpreter SDK you now pass the `timeoutMs` option to the `execCell` method instead of `timeout`. + +The default timeout for the code execution is now 300 seconds. + + +```js JavaScript & TypeScript +import CodeInterpreter from '@e2b/code-interpreter' + +// Before +// const sandbox = await CodeInterpreter.create() +// const execution = await sandbox.notebook.execCell('print("Hello, world!")', { +// timeout: 2000, +// }) +// await sandbox.close() + +// Now +const sandbox = await CodeInterpreter.create({ timeoutMs: 300_000 }) +const execution = await sandbox.notebook.execCell('print("Hello, world!")', { + timeoutMs: 2000, +}) +``` + +```python Python +from e2b_code_interpreter import CodeInterpreter + +# Before +# sandbox = CodeInterpreter() +# execution = sandbox.notebook.exec_cell('print("Hello, world!")', timeout=2) +# sandbox.close() + +# Now +sandbox = CodeInterpreter(timeout=300) +execution = sandbox.notebook.exec_cell('print("Hello, world!")', timeout=2) +``` + + +## Custom template +If you are using a custom template for the Code Interpreter you need to rebuild it. + + +You can rebuild the template by either calling +```sh +e2b template build -c "/root/.jupyter/start-up.sh" +``` +if you use the E2B Docker image as base in your `e2b.Dockerfile` +```docker +FROM e2bdev/code-interpreter:latest + +# You custom Dockerfile content here +``` + +Or if you are using custom base you need to copy all files excluding the `e2b.toml` from [beta template](https://github.com/e2b-dev/legacy/code-interpreter/tree/beta/template) +to the directory with your template and then run `e2b template build -c "/root/.jupyter/start-up.sh"`. + + +Check of the [Code Interpreter custom template](/legacy/code-interpreter/template) page for more info. + + +##

Python Async

+Python Core SDK and Code Interpter SDK now support async. + +If you need to use async import `AsyncSandbox`/`AsyncCodeInterpreter` instead of `Sandbox`/`CodeInterpreter`. + + +```python Python +# Sync +# from e2b import Sandbox +# sandbox = Sandbox.create() + +# from e2b_code_interpreter import CodeInterpreter +# sandbox = CodeInterpreter() + +# Async +from e2b import AsyncSandbox +from e2b_code_interpreter import AsyncCodeInterpreter + +sandbox = await AsyncSandbox.create() +sandbox = await AsyncCodeInterpreter.create() +``` + + +The async versions of methods for watching for files' changes and running commands in the background are slightly different: + +## Watching for files' changes in async Python SDK + + +```python Python +from e2b import Sandbox + +# Sync +# sandbox = Sandbox.create() +# watcher = sandbox.files.watch_dir("/path/in/sandbox") + +# for event in watcher: +# print(event) + +# Async +sandbox = await AsyncSandbox.create() + +await sandbox.files.watch_dir("/path/in/sandbox", lambda event: print(event)) +``` + + +## Running background commands in async Python SDK + +```python Python +from e2b import Sandbox + +# Sync +# sandbox = Sandbox.create() +# command = sandbox.commands.run( +# cmd='echo "Hello, World!"', +# background=True, +# ) + +# result = command.wait( +# on_stderr=lambda output: print(output), +# on_stdout=lambda output: print(output), +# ) + +# Async +sandbox = await AsyncSandbox.create() +command = await sandbox.commands.run( + cmd='echo "Hello, World!"', + on_stderr=lambda output: print(output), + on_stdout=lambda output: print(output), + background=True, +) + +result = await command.wait() +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/guide/custom-sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/guide/custom-sandbox/index.mdx new file mode 100644 index 0000000000..7bec79aae8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/guide/custom-sandbox/index.mdx @@ -0,0 +1,199 @@ +--- +title: "Creating Custom Sandbox" +--- + +You are reading a legacy (pre v1.0) document. + + +In this guide, we'll create a custom E2B sandbox with preinstalled dependencies and files. +Once the sandbox is built, we'll show how to create and control it with our SDK. + +## Prerequisites +1. [Node.js](https://nodejs.org/) 18.0.0 or later +1. [E2B CLI](/legacy/cli/installation) +1. Running Docker instance + +## 1. Install E2B CLI + + +```bash Install CLI +npm install -g @e2b/cli@latest +``` + + + +You need Node.js 18.0.0 or later to install the CLI. + + +## 2. Login to CLI +Before you create your first custom sandbox, you will need to authenticate in the CLI with your E2B account. +Run the following command in your terminal. + +```bash Login to CLI +e2b auth login +``` + + + +You need to have an existing E2B account to login. Sign up [here](/legacy/getting-started/api-key). + + +## 3. Create `e2b.Dockerfile` +To describe how your custom sandbox will look like, create a new Dockerfile and name it `e2b.Dockerfile`. +We use this Dockerfile as the [template file](/legacy/sandbox/templates/template-file). + + +Run `e2b template init` to create `e2b.Dockerfile` in the current directory. + + +We want our custom sandbox to have the [ffmpeg](https://www.ffmpeg.org/) isntalled - ffmpeg is a tool for editing video and audio files. + + +We support only Debian based images at the moment. + + + +```Dockerfile e2b.Dockerfile +# You can use most of the Debian based images +FROM ubuntu:22.04 + +# Install the ffmpeg tool/ +RUN apt update \ + && apt install -y ffmpeg +``` + + +## 4. Build custom sandbox +Now it's time to create your custom sandbox based on the sandbox template file (the `e2b.Dockefile` file) you just created in the previous step. + +Run the following command inside the template file directory in your terminal. + +[Pro users](/legacy/pricing) can use the `--cpu-count=` ([docs](/legacy/cli/commands#template-build)) and `--memory-mb=` ([docs](/legacy/cli/commands#template-build)) flags to customize the sandbox compute. +Read more about the compute [here](/legacy/sandbox/compute). + + + +```bash Build sandbox template +e2b template build --name "my-agent-sandbox" +``` + + + +Use the `.dockerignore` file to exclude files from the sandbox template. + + +The final output should look similar to this. + + +```bash Build output +Preparing sandbox template building (1 files in Docker build context). +Found ./e2b.Dockerfile that will be used to build the sandbox template. +Started building the sandbox template my-agent-sandbox + +# Truncated for visibility +# ... +# ... + +Running postprocessing. It can take up to few minutes. + +Postprocessing finished. + +✅ Building sandbox template my-agent-sandbox finished. + +┌ Usage examples ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +│ │ +│ You can use E2B Python or JS SDK to spawn sandboxes now. │ +│ Find more here - https://e2b.dev/docs/legacy/guide/custom-sandbox in Spawn and control your sandbox section. │ +│ │ +│───────────────────────────────────────────────────────────────────── Python SDK ─────────────────────────────────────────────────────────────────────│ +│ │ +│ from e2b import Sandbox │ +│ │ +│ # Start sandbox │ +│ sandbox = Sandbox.create("my-agent-sandbox") │ +│ │ +│ # Interact with sandbox. Learn more here: │ +│ # https://e2b.dev/docs/sandbox/overview │ +│ │ +│ # Close sandbox once done │ +│ sandbox.close() │ +│ │ +│─────────────────────────────────────────────────────────────────────── JS SDK ───────────────────────────────────────────────────────────────────────│ +│ │ +│ import { Sandbox } from 'e2b' │ +│ │ +│ // Start sandbox │ +│ const sandbox = await Sandbox.create('my-agent-sandbox') │ +│ │ +│ // Interact with sandbox. Learn more here: │ +│ // https://e2b.dev/docs/sandbox/overview │ +│ │ +│ // Close sandbox once done │ +│ await sandbox.close() │ +│ │ +└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + +Execution time: 42.55s +``` + + + +This will create the `e2b.toml` file storing the sandbox config. + +```toml e2b.toml +# This is a config for E2B sandbox template +template_id = "1wdqsf9le9gk21ztb4mo" +dockerfile = "e2b.Dockerfile" +template_name = "my-agent-sandbox" +``` + + +| Sandbox template name | Sandbox template ID | +---|---| +|`my-agent-sandbox`|`1wdqsf9le9gk21ztb4mo`| + +### Updating your sandbox template +If you want to update your sandbox template, you run the same command you did to build it. +This will rebuild the template. + + +```bash Update sandbox template +e2b template build +``` + + +## 5. Spawn and control your sandbox + +Now you can use the [E2B SDK](/legacy/getting-started/installation) to spawn & control your new custom sandbox. + +The sandbox template name is `my-agent-sandbox`. We'll use it as an unique identifier and pass it to the SDK as the `template` parameter. +This way, we'll be able to spawn our custom sandbox and control it with the SDK. + +##### Spawn & control your custom sandbox + +```js JavaScript & TypeScript highlight={4} +import { Sandbox } from 'e2b' + +// Spawn your custom sandbox +const sandbox = await Sandbox.create({ template: 'my-agent-sandbox' }) + +// Interact with sandbox. Learn more here: +// https://e2b.dev/docs/sandbox/overview + +// Close sandbox once done +await sandbox.close() +``` + +```python Python highlight={4} +from e2b import Sandbox + +# Spawn your custom sandbox +sandbox = Sandbox.create(template="my-agent-sandbox") + +# Interact with sandbox. Learn more here: +# https://e2b.dev/docs/sandbox/overview + +# Close sandbox once done +sandbox.close() +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/hello-world/js/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/hello-world/js/index.mdx new file mode 100644 index 0000000000..5c567e9ac5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/hello-world/js/index.mdx @@ -0,0 +1,308 @@ +--- +title: "Hello World.ts" +--- + +You are reading a legacy (pre v1.0) document. + + +This JavaScript guide will show you the basics of E2B: +- Connect the code interpreter to an LLM +- Prompt the LLM to generate the Python code +- Execute the AI-generated Python code in a secure E2B sandbox + +### Get full code +Check out the [full code in our cookbook](https://github.com/e2b-dev/e2b-cookbook/tree/main/examples/hello-world-js). + +### Overview +1. [Install Code Interpreter SDK](#1-install-code-interpreter-sdk) +1. [Prepare prompt and tools for LLM](#2-prepare-prompt-and-tools-for-llm) +1. [Prepare code interpreting](#3-prepare-code-interpreting) +1. [Call LLM and parse response with tools](#4-call-llm-and-parse-response-with-tools) +1. [Create code interpreter and run everything](##5-create-code-interpreter-and-run-everything) +1. [Save generated chart](#6-save-generated-chart) + + +## 1. Install Code Interpreter SDK + +The Code Interpreter SDK allows you to run AI-generated code in a secure small VM - **E2B sandbox** - made for AI code execution. +Inside the sandbox is a Jupyter server running that you can control from our SDK through the `notebook.execCell()` method. + +Check out the [SDK's repository on GitHub](https://github.com/e2b-dev/code-interpreter). + + +```bash JavaScript & TypeScript +npm init -y \ +&& npm i --save-dev typescript tsx @types/node \ +&& npm i @e2b/code-interpreter +``` + + +Get your E2B API key [here](/legacy/getting-started/api-key) and save it to `.env` in your root directory. + +```bash .env +E2B_API_KEY="e2b-api-key" +``` + + +## 2. Prepare prompt and tools for LLM +We'll be using Anthropic's [Claude 3 Opus](https://www.anthropic.com/news/claude-3-family) model but E2B works with any LLM so feel free to pick any you want! + + +Usually, all you need from the model is just support for tool use. If the LLM doesn't support tool use, you can ask the LLM to respond with Markdown or XML and parse the LLM's output on your own. Then just pass the parsed code from code blocks to the code interpreter. + + +Create the `model.ts` file and paste the following code. + +```ts model.ts +import { Anthropic } from '@anthropic-ai/sdk' + +export const MODEL_NAME = 'claude-3-opus-20240229' + +export const SYSTEM_PROMPT = ` +## your job & context +you are a python data scientist. you are given tasks to complete and you run python code to solve them. +- the python code runs in jupyter notebook. +- every time you call \`execute_python\` tool, the python code is executed in a separate cell. it's okay to multiple calls to \`execute_python\`. +- display visualizations using matplotlib or any other visualization library directly in the notebook. don't worry about saving the visualizations to a file. +- you have access to the internet and can make api requests. +- you also have access to the filesystem and can read/write files. +- you can install any pip package (if it exists) if you need to but the usual packages for data analysis are already preinstalled. +- you can run any python code you want, everything is running in a secure sandbox environment. +` + +export const tools: Anthropic.Tool[] = [ + { + name: 'execute_python', + description: 'Execute python code in a Jupyter notebook cell and returns any result, stdout, stderr, display_data, and error.', + input_schema: { + type: 'object', + properties: { + code: { + type: 'string', + description: 'The python code to execute in a single cell.' + } + }, + required: ['code'] + } + } +] + +``` + + +This defines our system prompt and the `tools` dictionary with available tools for the LLM - namely the `"execute_python"` tool. +A little bit later, we'll connect `"execute_python"` to the E2B's code interpretrer. + + +## 3. Prepare code interpreting +We'll create a new function called `codeInterpret()` in a separate file `codeInterpreter.ts`. + + +```ts codeInterpreter.ts +import { CodeInterpreter } from '@e2b/code-interpreter' + +export async function codeInterpret(codeInterpreter: CodeInterpreter, code: string) { + console.log(`\n${'='.repeat(50)}\n> Running following AI-generated code:\n${code}\n${'='.repeat(50)}`); + + const exec = await codeInterpreter.notebook.execCell( + code, + { + // You can stream logs from the code interpreter + // onStderr: (stderr: string) => console.log("\n[Code Interpreter stdout]", stderr), + // onStdout: (stdout: string) => console.log("\n[Code Interpreter stderr]", stdout), + // + // You can also stream additional results like charts, images, etc. + // onResult: ... + } + ) + + if (exec.error) { + console.log('[Code Interpreter error]', exec.error) // Runtime error + return undefined + } + + return exec +} +``` + + +This function takes the `CodeInterpreter` object from our SDK, and `code` as paramaters. +The `code` parameter is the code generated by the LLM. + +Inside the function, we call the `codeInterpreter.notebook.execCell()` method. The `execCell()` takes `code` argument, and executes this `code` inside E2B sandbox. + +## 4. Call LLM and parse response with tools +We're using Claude 3 Opus. Get your [Anthropic API key](https://console.anthropic.com/), save it to `.env` file, and install the [Anthropic SDK](https://docs.anthropic.com/claude/reference/client-sdks). + + +```bash .env +ANTHROPIC_API_KEY="anthropic-api-key" +``` + + + +```bash npm +npm i @anthropic-ai/sdk@0.28.0 +``` + + +Now we'll put everything together. +Create the `index.ts` file, import dependencies, and create the `chat()` function that will do the LLM calling and tool parsing. + + +```ts index.ts +import * as fs from 'fs' + +import 'dotenv/config' +import { CodeInterpreter, Execution } from '@e2b/code-interpreter' +import Anthropic from '@anthropic-ai/sdk' + +import { + MODEL_NAME, + SYSTEM_PROMPT, + tools, +} from './model' +import { codeInterpret } from './codeInterpreter' + +const anthropic = new Anthropic() + +async function chat(codeInterpreter: CodeInterpreter, userMessage: string): Promise { + console.log('Waiting for Claude...') + + const msg = await anthropic.messages.create({ + model: MODEL_NAME, + system: SYSTEM_PROMPT, + max_tokens: 4096, + messages: [{role: 'user', content: userMessage}], + tools, + }) + + console.log(`\n${'='.repeat(50)}\nModel response: ${msg.content}\n${'='.repeat(50)}`) + console.log(msg) + + if (msg.stop_reason === 'tool_use') { + const toolBlock = msg.content.find((block) => block.type === 'tool_use'); + const toolName = toolBlock.name + const toolInput = toolBlock.input + + console.log(`\n${'='.repeat(50)}\nUsing tool: ${toolName}\n${'='.repeat(50)}`); + + if (toolName === 'execute_python') { + const code = toolInput.code + return codeInterpret(codeInterpreter, code) + } + return undefined + } +} +``` + + +## 5. Create code interpreter and run everything +Now we put all together, and run our program. In the end of `index.ts` add following code prompting the LLM to visualize a distribution of height of men and print the median. + + +```ts index.ts +async function run() { + const userMessage = 'Visualize a distribution of height of men based on the latest data you know. Also print the median value.' + + const codeInterpreter = await CodeInterpreter.create() + + const codeOutput = await chat(codeInterpreter, userMessage) + if (!codeOutput) { + console.log('No code output') + return + } + + const logs = codeOutput.logs + console.log(logs) + + if (codeOutput.results.length == 0) { + console.log('No results') + return + } + + const firstResult = codeOutput.results[0] + // Print description of the first rich result + console.log(firstResult.text) + + await codeInterpreter.close() +} + +run() +``` + + +After running your code with the following command + +```bash bash +$ tsx index.ts +``` + + +you should see similar results to this: + +```sh +stdout=['The median male height is 175.5 cm\n'] stderr=[] +
+``` + +We got our median in the logs (`stdout`, and `stderr`) but we also something intering in `firstResult`. +```sh +
+``` + +## 6. Save generated chart + +This looks like a plot. Let's save it to a file. Update the `run()` function like this, +and run the code again with `tsx index.ts` in your terminal. + +```ts index.ts +async function run() { + const userMessage = 'Visualize a distribution of height of men based on the latest data you know. Also print the median value.' + + const codeInterpreter = await CodeInterpreter.create() + + const codeOutput = await chat(codeInterpreter, userMessage) + if (!codeOutput) { + console.log('No code output') + return + } + + const logs = codeOutput.logs + console.log(logs) + + if (codeOutput.results.length == 0) { + console.log('No results') + return + } + + const firstResult = codeOutput.results[0] + // Print description of the first rich result + console.log(firstResult.text) + + // If we received a chart in PNG form, we can visualize it + if (firstResult.png) { + // Decode the base64 encoded PNG data + const pngData = Buffer.from(firstResult.png, 'base64'); + + // Generate a unique filename for the PNG + const filename = 'chart.png'; + + // Save the decoded PNG data to a file + fs.writeFileSync(filename, pngData); + + console.log(`Saved chart to ${filename}`); + } + + await codeInterpreter.close() +} + +run() +``` + + +The chart got saved in the `chart.png` file and it should look similar to this: + + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/hello-world/py/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/hello-world/py/index.mdx new file mode 100644 index 0000000000..146c7c2e4e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/hello-world/py/index.mdx @@ -0,0 +1,256 @@ +--- +title: "Hello World.py" +--- + +You are reading a legacy (pre v1.0) document. + + +This Python guide will show you the basics of E2B: +- Connect the code interpreter to an LLM +- Prompt the LLM to generate the Python code +- Execute the AI-generated Python code in a secure E2B sandbox + +### Get full code +Check out the [full code in our cookbook](https://github.com/e2b-dev/e2b-cookbook/tree/main/examples/hello-world-python). + +### Overview +1. [Install Code Interpreter SDK](#1-install-code-interpreter-sdk) +1. [Prepare prompt and tools for LLM](#2-prepare-prompt-and-tools-for-llm) +1. [Prepare code interpreting](#3-prepare-code-interpreting) +1. [Call LLM and parse response with tools](#4-call-llm-and-parse-response-with-tools) +1. [Create code interpreter and run everything](##5-create-code-interpreter-and-run-everything) +1. [Save generated chart](#6-save-generated-chart) + + +## 1. Install Code Interpreter SDK + +The Code Interpreter SDK allows you to run AI-generated code in a secure small VM - **E2B sandbox** - made for AI code execution. +Inside the sandbox is a Jupyter server running that you can control from our SDK through the `notebook.execCell()` method. + +Check out the [SDK's repository on GitHub](https://github.com/e2b-dev/code-interpreter). + + +```bash Python +pip install e2b_code_interpreter python-dotenv +``` + + +Get your E2B API key [here](/legacy/getting-started/api-key) and save it to `.env` in your root directory. + +```bash .env +E2B_API_KEY="e2b-api-key" +``` + + + +## 2. Prepare prompt and tools for LLM +We'll be using Anthropic's [Claude 3 Opus](https://www.anthropic.com/news/claude-3-family) model but E2B works with any LLM so feel free to pick any you want! + + +Usually, all you need from the model is just support for tool use. If the LLM doesn't support tool use, you can ask the LLM to respond with Markdown or XML and parse the LLM's output on your own. Then just pass the parsed code from code blocks to the code interpreter. + + +Create the `model.py` file and paste the following code. + +```python Python +# model.py +MODEL_NAME = "claude-3-opus-20240229" + +SYSTEM_PROMPT = """ +## your job & context +you are a python data scientist. you are given tasks to complete and you run python code to solve them. +- the python code runs in jupyter notebook. +- every time you call `execute_python` tool, the python code is executed in a separate cell. it's okay to multiple calls to `execute_python`. +- display visualizations using matplotlib or any other visualization library directly in the notebook. don't worry about saving the visualizations to a file. +- you have access to the internet and can make api requests. +- you also have access to the filesystem and can read/write files. +- you can install any pip package (if it exists) if you need to but the usual packages for data analysis are already preinstalled. +- you can run any python code you want, everything is running in a secure sandbox environment. +""" + +tools = [ + { + "name": "execute_python", + "description": "Execute python code in a Jupyter notebook cell and returns any result, stdout, stderr, display_data, and error.", + "input_schema": { + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "The python code to execute in a single cell." + } + }, + "required": ["code"] + } + } +] +``` + + +This defines our system prompt and the `tools` dictionary with available tools for the LLM - namely the `"execute_python"` tool. +A little bit later, we'll connect `"execute_python"` to the E2B's code interpreter. + + +## 3. Prepare code interpreting +We'll create a new function called `code_interpret()` in a separate file `code_interpreter.py`. + + +```python Python +# code_interpreter.py +from e2b_code_interpreter import CodeInterpreter + +def code_interpret(code_interpreter: CodeInterpreter, code: str): + print(f"\n{'='*50}\n> Running following AI-generated code:\n{code}\n{'='*50}") + exec = code_interpreter.notebook.exec_cell( + code, + # You can stream logs from the code interpreter + # on_stderr=lambda stderr: print("\n[Code Interpreter stdout]", stderr), + # on_stdout=lambda stdout: print("\n[Code Interpreter stderr]", stdout), + # + # You can also stream additional results like charts, images, etc. + # on_result=... + ) + + if exec.error: + print("[Code Interpreter error]", exec.error) # Runtime error + else: + return exec.results, exec.logs +``` + + +This function takes the `CodeInterpreter` object from our SDK and `code` as paramaters. +The `code` parameter is the code generated by the LLM. + +Inside the function, we call the `code_interpreter.notebook.exec_cell()` method. The `exec_cell()` takes the `code` argument and executes this `code` inside E2B sandbox. + +## 4. Call LLM and parse response with tools +We're using Claude 3 Opus. Get your [Anthropic API key](https://console.anthropic.com/), save it to `.env` file, and install the [Anthropic SDK](https://docs.anthropic.com/claude/reference/client-sdks). + + +```bash .env +ANTHROPIC_API_KEY="anthropic-api-key" +``` + + + +```bash bash +pip install anthropic==0.35.0 +``` + + +Now we'll put everything together. +Create the `main.py` file, import dependencies, and create the `chat()` function that will do the LLM calling and tool parsing. + + +```python Python +import base64 +from dotenv import load_dotenv +from anthropic import Anthropic +from typing import List, Tuple +from e2b_code_interpreter import CodeInterpreter, Result +from e2b_code_interpreter.models import Logs + +from e2b_hello_world.model import MODEL_NAME, SYSTEM_PROMPT, tools +from e2b_hello_world.code_interpreter import code_interpret + +# Load the .env file +load_dotenv() + +client = Anthropic() + +def chat(code_interpreter: CodeInterpreter, user_message: str) -> Tuple[List[Result], Logs]: + print(f"\n{'='*50}\nUser Message: {user_message}\n{'='*50}") + + message = client.messages.create( + model=MODEL_NAME, + system=SYSTEM_PROMPT, + max_tokens=4096, + messages=[{"role": "user", "content": user_message}], + tools=tools, + ) + + print(f"\n{'='*50}\nModel response: {message.content}\n{'='*50}") + + if message.stop_reason == "tool_use": + tool_use = next(block for block in message.content if block.type == "tool_use") + tool_name = tool_use.name + tool_input = tool_use.input + + print(f"\n{'='*50}\nUsing tool: {tool_name}\n{'='*50}") + + if tool_name == "execute_python": + return code_interpret(code_interpreter, tool_input["code"]) + return [] +``` + + + +## 5. Create code interpreter and run everything +Now we are ready to run our program. At the end of `main.py` add the following code prompting the LLM to visualize a distribution of the height of men and print the median. + + +```python Python +# main.py +def main(): + user_message = "Visualize a distribution of height of men based on the latest data you know. Also, print the median value." + + # Create the CodeInterpreter object and save it as code_interpreter + with CodeInterpreter() as code_interpreter: + code_interpreter_results, code_interpreter_logs = chat( + code_interpreter, + user_message, + ) + + print(code_interpreter_logs) + + first_result= code_interpreter_results[0] + print(first_result) +``` + + +After running your code with the following command + +```bash bash +$ python main.py +``` + + +you should see results similar to this: + +```sh +stdout=['The median male height is 175.5 cm\n'] stderr=[] +
+``` + +We got our median in the logs (`stdout`, and `stderr`) but we also something intering in `first_result`. +```sh +
+``` + +## 6. Save generated chart + +This looks like a plot. Let's save it to a file. Add the following to the end of `main.py` and run the code again with `python main.py` in your terminal. + +```python Python +# main.py + # If we received a chart in PNG form, we can visualize it + if first_result.png: + # Decode the base64 encoded PNG data + png_data = base64.b64decode(first_result.png) + + # Generate a unique filename for the PNG + filename = f"chart.png" + + # Save the decoded PNG data to a file + with open(filename, "wb") as f: + f.write(png_data) + + print(f"Saved chart to {filename}") +``` + + +The chart was saved in the `chart.png` file and it should look similar to this: + + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/index.mdx new file mode 100644 index 0000000000..9b1f174f18 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/index.mdx @@ -0,0 +1,53 @@ +--- +title: "Code interpreting for your AI app" +--- + +You are reading a legacy (pre v1.0) document. + +E2B's [Code Interpreter SDK](https://github.com/e2b-dev/code-interpreter) allows you to add code interpreting capabilities to your AI apps. + +With code interpreting, you can build apps like: +- AI code execution +- Data analysis with AI +- AI tutors +- Reasoning modules for LLM + +## Quickstart + +### 1. Install SDK + +```bash JavaScript & TypeScript +npm i @e2b/code-interpreter +``` +```bash Python +pip install e2b_code_interpreter +``` + + +### 2. Execute code with code interpreter inside sandbox + +```ts JavaScript & TypeScript +import { CodeInterpreter } from '@e2b/code-interpreter' + +const sandbox = await CodeInterpreter.create() +await sandbox.notebook.execCell('x = 1') + +const execution = await sandbox.notebook.execCell('x+=1; x') +console.log(execution.text) // outputs 2 + +await sandbox.close() +``` + +```py Python +from e2b_code_interpreter import CodeInterpreter + +with CodeInterpreter() as sandbox: + sandbox.notebook.exec_cell("x = 1") + + execution = sandbox.notebook.exec_cell("x+=1; x") + print(execution.text) # outputs 2 +``` + + +### 3. Hello World guide +Dive depeer and check out the [JavaScript](/legacy/hello-world/js) and [Python](/legacy/hello-world/py) Hello World guides to learn how to connect the code interpreter to LLMs. diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/open-source/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/open-source/index.mdx new file mode 100644 index 0000000000..1b13cf322f --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/open-source/index.mdx @@ -0,0 +1,15 @@ +--- +title: "Open source" +--- + +You are reading a legacy (pre v1.0) document. + + +E2B is fully open source including the infrastructure layer. + +- [E2B monorepo containing the SDKs, CLI, and docs](https://github.com/e2b-dev/e2b) +- [E2B infrastructure](https://github.com/e2b-dev/infra) +- [Example code interpreter ChatGPT plugin](https://github.com/e2b-dev/llm-code-interpreter) +- [List of awesome SDKs for AI agents](https://github.com/e2b-dev/awesome-sdks-for-ai-agents) +- [List of awesome AI agents](https://github.com/e2b-dev/awesome-ai-agents) +{/* - [E2B cookbook](https://github.com/e2b-dev/e2b-cookbook) */} diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/pricing/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/pricing/index.mdx new file mode 100644 index 0000000000..011e50d43d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/pricing/index.mdx @@ -0,0 +1,70 @@ +--- +title: "Pricing" +--- + +You are reading a legacy (pre v1.0) document. + + +import SandboxSpec from "/snippets/SandboxSpec.mdx"; + +[Manage Billing](https://e2b.dev/dashboard?tab=billing) + +We charge you based on your real sandbox usage. All new users get one-time free $100 worth of usage in credits. + +--- + +# Plans pricing +Additionally to the usage costs, you can also select a tier that includes dedicated support, prioritized features, and higher sandbox limits. + +## Hobby tier +**$0/month + usage costs** + +- One-time $100 of usage in credits +- Community support +- Up to 1 hour sandbox session length +- Up to 20 concurrently running sandboxes + +## Pro tier +**$150/month + usage costs** + +- One-time $100 of usage in credits +- Dedicated Slack channel with live Pro support from our team +- Prioritized features +- Customize your [sandbox compute](/legacy/sandbox/compute) +- Up to 24 hours sandbox session length +- Up to 100 concurrently running sandboxes + + +If you need any additional features or resources, please [reach out to us](/legacy/getting-help) with your use case. + +--- + +# Compute pricing +We charge per second of a running sandbox. +- vCPU: $0.000014 per second (~$0.05 per hour) +- GiB RAM: $0.0000045 per second (~$0.018 per hour) +- GiB storage: Free + + +1 GiB is equal to 1,024 MiB + + +## Sandbox compute +Pro customers can customize the sandbox with **any combination** of the CPU and RAM based on the following tables. + + +By default your sandbox has 2 vCPU and 512 MiB RAM. + +To customize your sandbox compute, you need to build your custom sandbox template using the [E2B CLI](/legacy/cli/installation). +Run [`e2b template build`](/legacy/cli/commands#template-build) and specify the `--cpu-count` and `--memory-mb` options. + +For example this custom build gives your sandbox 8 vCPU and 4GiB of RAM +```sh +e2b template build --cpu-count 8 --memory-mb 4096 +``` + + + + +
+[Let us know](/legacy/getting-help) if you need more powerful compute. diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/cwd/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/cwd/index.mdx new file mode 100644 index 0000000000..b7bbdb1d33 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/cwd/index.mdx @@ -0,0 +1,136 @@ +--- +title: "Current Working Directory" +--- + +You are reading a legacy (pre v1.0) document. + + +You can set a working directory either for the whole sandbox, a filesystem operation, or a new process. + +## Sandbox + +If the current working directory for the sandbox is not set, it will default to the home directory - `/home/user`. + + +```js JavaScript & TypeScript highlight={5-9} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ + template: 'base', + cwd: '/code', +}) + +// You can also change the cwd of an existing sandbox +sandbox.cwd = '/home' + +await sandbox.close() +``` +```python Python highlight={5-9} +from e2b import Sandbox + +sandbox = Sandbox( + template="base", + cwd="/code", +) + +# You can also change the cwd of an existing sandbox +sandbox.cwd = "/home" + +sandbox.close() +``` + + +## Filesystem + +All filesystem operations with relative paths are relative to the current working directory. + + +```js JavaScript & TypeScript highlight={5,8,16} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ + template: 'base', + cwd: '/home/user/code', +}) + +await sandbox.filesystem.write('hello.txt', 'Welcome to E2B!') +const proc = await sandbox.process.start({ + cmd: 'cat /home/user/code/hello.txt', +}) +await proc.wait() +console.log(proc.output.stdout) +// output: "Welcome to E2B!" + +await sandbox.filesystem.write('../hello.txt', 'We hope you have a great day!') +const proc2 = await sandbox.process.start({cmd: 'cat /home/user/hello.txt'}) +await proc2.wait() +console.log(proc2.output.stdout) +// output: "We hope you have a great day!" + +await sandbox.close() +``` +```python Python highlight={5,7,13} +from e2b import Sandbox + +sandbox = Sandbox( + template="base", + cwd="/home/user/code" +) +sandbox.filesystem.write("hello.txt", "Welcome to E2B!") +proc = sandbox.process.start("cat /home/user/code/hello.txt") +proc.wait() +print(proc.output.stdout) +# output: "Welcome to E2B!" + +sandbox.filesystem.write("../hello.txt", "We hope you have a great day!") +proc2 = sandbox.process.start("cat /home/user/hello.txt") +proc2.wait() +print(proc2.output.stdout) +# output: "We hope you have a great day!" + +sandbox.close() +``` + + +## Process + +If you set a working directory for the sandbox, all processes will inherit it. You can override it for each process. + + +```js JavaScript & TypeScript highlight={5,8,13} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ + template: 'base', + cwd: '/code', +}) + +const sandboxCwd = await sandbox.process.start({cmd: 'pwd'}) +await sandboxCwd.wait() +console.log(sandboxCwd.output.stdout) +// output: /code + +const processCwd = await sandbox.process.start({cmd: 'pwd', cwd: '/home'}) +await processCwd.wait() +console.log(processCwd.output.stdout) +// output: /home + +await sandbox.close() +``` +```python Python highlight={3,4,9} +from e2b import Sandbox + +sandbox = Sandbox(template="base", cwd="/code") +sandbox_cwd = sandbox.process.start("pwd") +sandbox_cwd.wait() +print(sandbox_cwd.output.stdout) +# output: "/code" + +process_cwd = sandbox.process.start("pwd", cwd="/home") +process_cwd.wait() +print(process_cwd.output.stdout) +# output: "/home" + +sandbox.close() +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/debugging/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/debugging/index.mdx new file mode 100644 index 0000000000..d11a3212bd --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/debugging/index.mdx @@ -0,0 +1,79 @@ +--- +title: "Logging" +--- + +You are reading a legacy (pre v1.0) document. + + +export const sections = [ + { title: 'Logging', id: 'logging' }, +] + + + ```text JavaScript & TypeScript + E2B package logs only warnings & errors to the console by default. Below is an example of how to fully customize the logging levels.\n\nFeel free to override the logger with your own implementation with debug, info, warn, and error methods. + ``` + ```text Python + E2B package uses the standard Python logging module You can configure the logging level, handlers and format as you would with any other Python application. \n\nBelow is an example of how to configure the logging module to log to the console. + ``` + + + +```js JavaScript & TypeScript highlight={14} +import { Sandbox } from 'e2b' + +const logger = { + debug: console.debug, // log debug messages, in default logger this is noop + info: console.info, // log info messages, in default logger this is noop + // don't forget to also specify warn & error handlers, otherwise they won't be logged when overriding the logger + warn: console.warn, + error: console.error, +} + +const sandbox = await Sandbox.create({ + template: 'base', + apiKey: process.env.E2B_API_KEY, + logger, +}) +``` +```python Python highlight={10,15,18,29} +import logging +from os import getenv + +from e2b import Sandbox + +E2B_API_KEY = getenv("E2B_API_KEY") + +# Global logging configuration +logging.basicConfig(level=logging.INFO, format="GLOBAL - [%(asctime)s] - %(name)-32s - %(levelname)7s: %(message)s", + datefmt="%Y-%m-%d %H:%M:%S") + +# Or configure only e2b logger + +# Get e2b logger +e2b_logger = logging.getLogger("e2b") + +# Set e2b logger level to INFO +e2b_logger.setLevel(logging.INFO) + +# Setup formatter +formatter = logging.Formatter("E2B - [%(asctime)s] - %(name)-32s - %(levelname)7s: %(message)s", + datefmt="%Y-%m-%d %H:%M:%S") + +# Setup handler +handler = logging.StreamHandler() +handler.setFormatter(formatter) + +# Add handler to e2b logger +e2b_logger.addHandler(handler) + + +def main(): + sandbox = Sandbox(template="base", api_key=E2B_API_KEY) + sandbox.filesystem.write("test.txt", "Hello World") + sandbox.close() + + +main() +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/download/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/download/index.mdx new file mode 100644 index 0000000000..2855834030 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/download/index.mdx @@ -0,0 +1,40 @@ +--- +title: "Download files from the sandbox" +--- + +You are reading a legacy (pre v1.0) document. + + +Any file inside the sandbox can be downloaded using the `downloadFile`/`download_file` method. + +## Use case for downloading files +For example, the download file method is useful for downloading any files produced by LLM. You can let LLM generate and execute code inside the sandbox. +This LLM-generated code might produce some files like charts, CSV files, or PDF files that you want to download to your machine. + + +```js JavaScript & TypeScript highlight={6} +import { Sandbox } from 'e2b' +import fs from 'node:fs' + +const sandbox = await Sandbox.create({ template: 'base' }) + +const buffer = await sandbox.downloadFile('path/to/remote/file/inside/sandbox', 'buffer') +// Save file to local filesystem +fs.writeFileSync('path/to/local/file', buffer) + +await sandbox.close() +``` +```python Python highlight={5,7,8} +from e2b import Sandbox + +sandbox = Sandbox(template="base") + +file_in_bytes = sandbox.download_file("path/to/remote/file/inside/sandbox") +# Save file to local filesystem +with open("path/to/local/file", "wb") as f: + f.write(file_in_bytes) + +sandbox.close() +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/envs/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/envs/index.mdx new file mode 100644 index 0000000000..f3b7fdf0b9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/envs/index.mdx @@ -0,0 +1,79 @@ +--- +title: "Setting environment variables" +--- + +You are reading a legacy (pre v1.0) document. + + +## Global environment variables +You can set the sandbox's global environment variables when initializing a new sandbox. + +```js JavaScript & TypeScript highlight={5} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ + template: 'base', + envVars: {FOO: 'Hello'}, +}) + +await sandbox.close() +``` +```python Python highlight={5} +from e2b import Sandbox + +sandbox = Sandbox( + template="base", + env_vars={"FOO": "Hello"}, +) + +sandbox.close() +``` + + + +## Environment variables per process +Alternatively, you can set environment variables when starting a new process. These environment variables are accessible only for this process. + + +Environment variables set when starting a new process have precedence over the environment variables set when initializing the sandbox. + + + +```js JavaScript & TypeScript highlight={10} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ + template: 'base', + envVars: {FOO: 'Hello'}, +}) + +const proc = await sandbox.process.start({ + cmd: 'echo $FOO $BAR!', + envVars: {BAR: 'World'}, +}) +await proc.wait() +console.log(proc.output.stdout) +// output: Hello World! + +await sandbox.close() +``` +```python Python highlight={10} +from e2b import Sandbox + +sandbox = Sandbox( + template="base", + env_vars={"FOO": "Hello"} +) + +proc = sandbox.process.start( + "echo $FOO $BAR!", + env_vars={"BAR": "World"}, +) +proc.wait() + +print(proc.output.stdout) +# output: Hello World! + +sandbox.close() +``` + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/filesystem/index.mdx new file mode 100644 index 0000000000..a972478a45 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/filesystem/index.mdx @@ -0,0 +1,275 @@ +--- +title: List directory +--- + +You are reading a legacy (pre v1.0) document. + + + +```js JavaScript & TypeScript highlight={7} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ + template: 'base', +}) + +const dirContent = await sandbox.filesystem.list('/') +dirContent.forEach((item) => { + console.log(item.name) +}) + +await sandbox.close() +``` +```python Python highlight={6} +from e2b import Sandbox + +sandbox = Sandbox(template="base") + +# List the root directory +content = sandbox.filesystem.list("/") +for item in content: + print(f"Is '{item.name}' directory?", item.is_dir) + +sandbox.close() +``` + + +## Create directory + +Create directory and all parent directories. + + +```js JavaScript & TypeScript highlight={6} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ template: 'base' }) + +// Create a new directory '/dir' +await sandbox.filesystem.makeDir('/dir') + +await sandbox.close() +``` +```python Python highlight={6} +from e2b import Sandbox + +sandbox = Sandbox(template="base") + +# Create a new directory '/dir' +sandbox.filesystem.make_dir("/dir") + +sandbox.close() +``` + + +## Write to file + +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. + + +```js JavaScript & TypeScript highlight={11} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ template: 'base' }) + +// `filesystem.write()` will: +// - create the file if it doesn't exist +// - fail if any directory in the path doesn't exist +// - overwrite the file if it exists + +// Write the content of the file '/hello.txt' +await sandbox.filesystem.write('/hello.txt', 'Hello World!') + +// The following would fail because '/dir' doesn't exist +// await sandbox.filesystem.write("/dir/hello.txt", "Hello World!") + +await sandbox.close() +``` +```python Python highlight={11} +from e2b import Sandbox + +sandbox = Sandbox(template="base") + +# `filesystem.write()` will: +# - create the file if it doesn't exist +# - fail if any directory in the path doesn't exist +# - overwrite the file if it exists + +# Write the content of the file '/hello.txt' +sandbox.filesystem.write("/hello.txt", "Hello World!") + +# The following would fail because '/dir' doesn't exist +# sandbox.filesystem.write("/dir/hello.txt", "Hello World!") + +sandbox.close() +``` + + +## Read from file + + +```js JavaScript & TypeScript highlight={5} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ template: 'base' }) + +const fileContent = await sandbox.filesystem.read('/etc/hosts') +console.log(fileContent) + +await sandbox.close() +``` +```python Python highlight={6} +from e2b import Sandbox + +sandbox = Sandbox(template="base") + +# Read the '/etc/hosts' file +file_content = sandbox.filesystem.read("/etc/hosts") + +# Prints something like: +# 127.0.0.1 localhost +print(file_content) + +sandbox.close() +``` + + +## Write bytes + + +```js JavaScript & TypeScript highlight={10} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ template: 'base' }) + +// Let's convert string to bytes for testing purposes +const encoder = new TextEncoder('utf-8') +const contentInBytes = encoder.encode('Hello World!') + +// `writeBytes` accepts a Uint8Array and saves it to a file inside the playground +await sandbox.filesystem.writeBytes('/file', contentInBytes) + +// We can read the file back to verify the content +const fileContent = await sandbox.filesystem.read('/file') + +// This will print 'Hello World!' +console.log(fileContent) + +await sandbox.close() +``` +```python Python highlight={8} +from e2b import Sandbox + +sandbox = Sandbox(template="base") + +content_in_bytes = bytearray(b"Hello world") + +# `write_bytes` will write bytearray to a file inside the playground. +sandbox.filesystem.write_bytes("/file", content_in_bytes) + +# We can read the file back to verify the content +file_content = sandbox.filesystem.read("/file") +print(file_content) + +sandbox.close() +``` + + +## Read bytes + + +```js JavaScript & TypeScript highlight={8} +import fs from 'fs' +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ template: 'base' }) + +// File bytes will read file's content as bytes +// `fileBytes` as a Uint8Array +const fileBytes = await sandbox.filesystem.readBytes('/etc/hosts') + +// The output will look similar to this: +// + +## Watch directory for changes + + +```js JavaScript & TypeScript highlight={6-10} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ template: 'base' }) + +// Start filesystem watcher for the /home directory +const watcher = sandbox.filesystem.watchDir('/home') +watcher.addEventListener((event) => { + console.log('Filesystem event', event) +}) +await watcher.start() + +// Create files in the /home directory inside the playground +// We'll receive notifications for these events through the watcher we created above. +for (let i = 0; i < 10; i++) { + console.log('Creating file', i) + // `filesystem.write()` will trigger two events: + // 1. 'Create' when the file is created + // 2. 'Write' when the file is written to + await sandbox.filesystem.write(`/home/${i}.txt`, `Hello World ${i}!`) +} + +await sandbox.close() +``` +```python Python highlight={7,19} +import time + +from e2b import Sandbox + +sandbox = Sandbox.create() + +watcher = sandbox.files.watch_dir("/home") + +# Create files in the /home directory inside the playground +# We'll receive notifications for these events through the watcher we created above. +for i in range(10): + # `filesystem.write()` will trigger two events: + # 1. 'Create' when the file is created + # 2. 'Write' when the file is written to + sandbox.files.write(f"/home/file{i}.txt", f"Hello World {i}!") + time.sleep(1) + +for event in watcher.get(): + print(f"Event: {event.type} {event.name}") + +watcher.stop() +sandbox.kill() +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/metadata/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/metadata/index.mdx new file mode 100644 index 0000000000..96233b4433 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/metadata/index.mdx @@ -0,0 +1,66 @@ +--- +title: Sandbox metadata +--- + +You are reading a legacy (pre v1.0) document. + + +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. + + +```js JavaScript & TypeScript highlight={5} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ + template: 'base', + metadata: { userID: 'uniqueID' } +}) +// Keep the sandbox alive for 60 seconds +await sandbox.keepAlive(60_000) +// You can even close the script + +// Later, can be even from another process +// List all running sandboxes +const paginator = Sandbox.list({ query: {state: ['running']}}) +const runningSandboxes = await paginator.nextItems() +// Find the sandbox by metadata +const found = runningSandboxes.find(s => s.metadata?.userID === 'uniqueID') +if (found) { + // Sandbox found, we can reconnect to it + const sandbox = await Sandbox.reconnect(found.sandboxID) +} else { + // Sandbox not found +} + +await sandbox.close() +``` +```python Python highlight={6} +from e2b import Sandbox, SandboxState +from e2b.sandbox.sandbox_api import SandboxQuery + +sandbox = Sandbox( + template="base", + metadata={"user_id": "uniqueID"}, +) + +# Keep the sandbox alive for 60 seconds +sandbox.set_timeout(60) +# You can even close the script + +# Later, can be even from another process +# List all running sandboxes +paginator = Sandbox.list(query=SandboxQuery(state=[SandboxState.RUNNING])) +running_sandboxes = paginator.next_items() + +# Find the sandbox by metadata +for running_sandbox in running_sandboxes: + if running_sandbox.metadata.get("user_id", "") == "uniqueID": + sandbox = Sandbox.connect(running_sandbox.sandbox_id) + break +else: + # Sandbox not found + pass + +sandbox.close() +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/process/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/process/index.mdx new file mode 100644 index 0000000000..ce3c6bfe94 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/process/index.mdx @@ -0,0 +1,269 @@ +--- +title: "Starting process inside a sandbox" +--- + +You are reading a legacy (pre v1.0) document. + + +Here are the basic operations you can do with the process inside the sandbox: + +- [Start process](#start-process) +- [Stop process](#stop-process) +- [Stdout](#stream-stdout) +- [Stdin](#send-stdin) +- [Stderr](#stream-stderr) +- [On exit](#on-process-exit) + +## Start process + + +```js JavaScript & TypeScript highlight={6} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ template: 'base' }) + +const npmInit = await sandbox.process.start({ + cmd: 'npm init -y', +}) +await npmInit.wait() + +console.log(npmInit.output.stdout) + +await sandbox.close() +``` +```python Python highlight={5} +from e2b import Sandbox + +sandbox = Sandbox(template="base") + +npm_init = sandbox.process.start("npm init -y") +npm_init.wait() +print(npm_init.stdout) + +sandbox.close() +``` + + +## Stop process + + +```js JavaScript & TypeScript highlight={10} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ + template: 'base', +}) + +const npmInit = await sandbox.process.start({ + cmd: 'npm init -y', +}) +await npmInit.kill() +// There will be no output because we immediately kill the `npm_init` process +console.log(npmInit.output.stdout) + +await sandbox.close() +``` +```python Python highlight={6} +from e2b import Sandbox + +sandbox = Sandbox(template="base") + +npm_init = sandbox.process.start("npm init -y") +npm_init.kill() + +# There will be no output because we immediately kill the `npm_init` process +print(npm_init.stdout) + +sandbox.close() +``` + + +## Stream stdout + +Set either stdout handler for the whole sandbox level or per process. + + +```js JavaScript & TypeScript highlight={5,16} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ + template: 'base', + onStdout: (output) => console.log('sandbox', output.line), +}) + +const proc = await sandbox.process.start({ + cmd: 'echo "Hello World!"', +}) +await proc.wait() +// output: sandbox Hello World! + +const procWithCustomHandler = await sandbox.process.start({ + cmd: 'echo "Hello World!"', + onStdout: (data) => console.log('process', data.line), +}) +await procWithCustomHandler.wait() +// output: process Hello World! + +await sandbox.close() +``` +```python Python highlight={5,14} +from e2b import Sandbox + +sandbox = Sandbox( + template="base", + on_stdout=lambda output: print("sandbox", output.line), +) + +proc = sandbox.process.start('echo "Hello World!"') +proc.wait() +# output: sandbox Hello World! + +proc_with_custom_handler = sandbox.process.start( + 'echo "Hello World!"', + on_stdout=lambda output: print("process", output.line), +) +proc_with_custom_handler.wait() +# output: process Hello World! + +sandbox.close() +``` + + +## Stream stderr + +Set either stderr handler for the whole sandbox level or per process. + + +```js JavaScript & TypeScript highlight={10,17} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ + template: 'base', +}) + +// This command will fail and output to stderr because Golang isn't installed in the cloud playground +const golangVersion = await sandbox.process.start({ + cmd: 'go version', + onStderr: (output) => console.log('sandbox', output.line), +}) +await golangVersion.wait() +// output: [sandbox] /bin/bash: line 1: go: command not found + +const procWithCustomHandler = await sandbox.process.start({ + cmd: 'go version', + onStderr: (data) => console.log('process', data.line), +}) +await procWithCustomHandler.wait() +// output: process /bin/bash: line 1: go: command not found + +await sandbox.close() +``` +```python Python highlight={5,15} +from e2b import Sandbox + +sandbox = Sandbox( + template="base", + on_stderr=lambda output: print("[sandbox]", output.line), +) + +# This command will fail and output to stderr because Golang isn't installed in the cloud playground +proc = sandbox.process.start("go version") +proc.wait() +# output: [sandbox] /bin/bash: line 1: go: command not found + +proc_with_custom_handler = sandbox.process.start( + "go version", + on_stderr=lambda output: print("[process]", output.line), +) +proc_with_custom_handler.wait() +# output: [process] /bin/bash: line 1: go: command not found + +sandbox.close() +``` + + +## On process exit + +Set either on exit handler for the whole sandbox level or per process. + + +```js JavaScript & TypeScript highlight={5,14} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ + template: 'base', + onExit: () => console.log('[sandbox]', 'process ended'), +}) + +const proc = await sandbox.process.start({cmd: 'echo "Hello World!"'}) +await proc.wait() +// output: [sandbox] process ended + +const procWithCustomHandler = await sandbox.process.start({ + cmd: 'echo "Hello World!"', + onExit: () => console.log('[process]', 'process ended'), +}) +await procWithCustomHandler.wait() +// output: [process] process ended + +await sandbox.close() +``` +```python Python highlight={5,14} +from e2b import Sandbox + +sandbox = Sandbox( + template="base", + on_exit=lambda: print("[sandbox]", "process ended"), +) + +proc = sandbox.process.start('echo "Hello World!"') +proc.wait() +# output: [sandbox] process ended + +proc_with_custom_handler = sandbox.process.start( + 'echo "Hello World!"', + on_exit=lambda: print("[process]", "process ended"), +) +proc_with_custom_handler.wait() +# output: [process] process ended + +sandbox.close() +``` + + +## Send stdin + + +```js JavaScript & TypeScript highlight={11} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ template: 'base' }) + +// This example will print back the string we send to the process using `sendStdin()` + +const proc = await sandbox.process.start({ + cmd: 'while IFS= read -r line; do echo "$line"; sleep 1; done', + onStdout: (output) => console.log(output), +}) +await proc.sendStdin('AI Playground\n') +await proc.kill() + +await sandbox.close() +``` +```python Python highlight={11} +from e2b import Sandbox + +sandbox = Sandbox(template="base") + +# This example will print back the string we send to the process using `send_stdin()` + +proc = sandbox.process.start( + 'while IFS= read -r line; do echo "$line"; sleep 1; done', + on_stdout=print, +) +proc.send_stdin("AI Playground\n") +proc.kill() + +sandbox.close() +``` + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/reconnect/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/reconnect/index.mdx new file mode 100644 index 0000000000..aab0ea6658 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/reconnect/index.mdx @@ -0,0 +1,110 @@ +--- +title: "Connect to running sandbox" +--- + +You are reading a legacy (pre v1.0) document. + + +Disconnect and reconnect later to the same sandbox while keeping it alive + +## Description + +The sandboxes are by default kept alive only when connected to them. When you disconnect from a sandbox, it will be destroyed. + +If you want to keep the sandbox alive even after disconnecting from it, you can explicitly say for how long you want to keep it alive. You can then disconnect from the sandbox and reconnect to it later. This can be useful for example in a **serverless environment** or **chatbot application**. + +The duration limit to keep the sandbox alive is 1 hour. If you need more, feel free to [reach out to us](/legacy/getting-help) with your use. + +## Keep sandbox alive + +The example below shows how to disconnect from a running sandbox and reconnect to it again while keeping the sandbox alive. + + +```js JavaScript & TypeScript +import { Sandbox } from 'e2b' + +async function wait(ms) { + return new Promise(resolve => setTimeout(resolve, ms)) +} + +const sandbox = await Sandbox.create({ template: 'base' }) +``` +```python Python +import time +from e2b import Sandbox + + +sandbox = Sandbox('base') +``` + + +Call the `keep_alive`/`keepAlive` method on the sandbox instance to keep it alive. You can specify the preferred duration, as a multiple of a default time unit, which is +- 1ms in JS +- 1s in Python. + +You then disconnect from the sandbox. + + +```js JavaScript & TypeScript highlight={8} +// Do something in the sandbox +await sandbox.filesystem.write('hello.txt', 'Hello World!') + +// Get the sandbox ID, we'll need it later +const sandboxID = sandbox.id + +// Keep alive the sandbox for 2 minutes +await sandbox.keepAlive(2 * 60 * 1000) // 2 minutes + +// Close the sandbox. Even if we close the sandbox, it will stay alive, because we explicitly called keepAlive(). +await sandbox.close() + +// Do something else... +await wait(60 * 1000) +``` +```python Python highlight={8} +# Do something in the sandbox +sandbox.filesystem.write('hello.txt', 'Hello World!') + +# Get the sandbox ID, we'll need it later +sandboxID = sandbox.id + +# Keep the sandbox alive for 2 minutes +sandbox.keep_alive(60 * 2) + +# Close the sandbox. Even if we close the sandbox, it will stay alive, because we explicitly called keep_alive(). +sandbox.close() + +# Do something else... +time.sleep(60) +``` + + +You can then reconnect to the sandbox from anywhere. + + +```js JavaScript & TypeScript highlight={2} +// Reconnect to the sandbox +const sandbox2 = await Sandbox.reconnect(sandboxID) + +// Continue in using the sandbox +const content = await sandbox2.filesystem.read('hello.txt') +console.log(content) + +// Close the sandbox +await sandbox2.close() +``` +```python Python highlight={2} +# Reconnect to the sandbox +sandbox2 = Sandbox.reconnect(sandboxID) + +# Continue in using the sandbox +content = sandbox2.filesystem.read('hello.txt') +print(content) + +# Close the sandbox +sandbox2.close() +``` + + +## Use sandbox metadata +Sandbox metadata can be very useful to store information about the sandbox. You can use it to store the user ID or any other information you need to keep track of and then use this info for reconnecting to the sandbox. You can read more about sandbox metadata [here](/legacy/sandbox/api/metadata). \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/timeouts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/timeouts/index.mdx new file mode 100644 index 0000000000..40e08d7a3c --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/timeouts/index.mdx @@ -0,0 +1,100 @@ +--- +title: "Timeouts" +--- + +You are reading a legacy (pre v1.0) document. + + +The SDK has a number of timeouts that can be configured to control how long the SDK will wait for a response from the E2B servers. **The default is 60 seconds.** + +## Timeout creating sandbox + +```js JavaScript & TypeScript highlight={6} +import { Sandbox } from 'e2b' + +// Timeout 3s for the sandbox to open +const sandbox = await Sandbox.create({ + template: 'base', + timeout: 3000, +}) + +await sandbox.close() +``` +```python Python highlight={4} +from e2b import Sandbox + +# Timeout 3s for the sandbox to open +sandbox = Sandbox(template="base", timeout=3) + +sandbox.close() +``` + + +## Timeout process + +```js JavaScript & TypeScript highlight={8} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ template: 'base' }) + +// Timeout 3s for the process to start +const npmInit = await sandbox.process.start({ + cmd: 'npm init -y', + timeout: 3000, +}) +await npmInit.wait() + +await sandbox.close() +``` +```python Python highlight={6} +from e2b import Sandbox + +sandbox = Sandbox(template="base") + +# Timeout 3s for the process to start +npm_init = sandbox.process.start("npm init -y", timeout=3) +npm_init.wait() + +sandbox.close() +``` + + +## Timeout filesystem operations + +```js JavaScript & TypeScript highlight={6,9,13} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ template: 'base' }) + +// Timeout 3s for the write operation +await sandbox.filesystem.write('hello.txt', 'Hello World!', {timeout: 3000}) + +// Timeout 3s for the list operation +const files = await sandbox.filesystem.list('.', {timeout: 3000}) +console.log(files) + +// Timeout 3s for the read operation +const content = await sandbox.filesystem.read('hello.txt', {timeout: 3000}) +console.log(content) + +await sandbox.close() +``` +```python Python highlight={6,9,13} +from e2b import Sandbox + +sandbox = Sandbox(template="base") + +# Timeout 3s for the write operation +sandbox.filesystem.write("test.txt", "Hello World", timeout=3) + +# Timeout 3s for the list operation +dir_content = sandbox.filesystem.list(".", timeout=3) +print(dir_content) + +# Timeout 3s for the read operation +file_content = sandbox.filesystem.read("test.txt", timeout=3) +print(file_content) + +sandbox.close() +``` + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/upload/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/upload/index.mdx new file mode 100644 index 0000000000..517417c175 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/upload/index.mdx @@ -0,0 +1,56 @@ +--- +title: "Upload files to sandbox" +--- + +You are reading a legacy (pre v1.0) document. + + +You can upload any file to the sandbox. This is useful if you want to let the LLM work with your files or files of your users. The file will be uploaded to the user's home directory with the same name. If a file with the same name already exists, it will be overwritten. + +## Use case for uploading files +A popular workflow is for example to upload a CSV data file and then let the LLM generate and execute Python code that operates with the uploaded CSV file inside the sandbox. This way, you can essentially create your own AI data analyst or code interpreter. + + +We support uploading files up to 100MB at the moment. If you need to upload larger files, please [reach out to us](/legacy/getting-help). + + + +```js JavaScript & TypeScript highlight={7-9} +import { Sandbox } from 'e2b' +import fs from 'node:fs' + +const sandbox = await Sandbox.create({ template: 'base' }) + +// If you're in the server environment +const filename = 'data.csv' +const fileBuffer = fs.readFileSync('path/to/local/file') +const remotePath = await sandbox.uploadFile(fileBuffer, filename) + +// If you're in the browser environment, you can use the Blob API +// const filename = 'data.csv' +// const CSV = [ +// '"1","val1","val2","val3","val4"', +// '"2","val1","val2","val3","val4"', +// '"3","val1","val2","val3","val4"' +// ].join('\n'); +// const fileBlob = new Blob([csv], { type: 'text/csv' }) +// const remotePath = await sandbox.uploadFile(fileBlob, 'data.csv') + +console.log( + `The file was uploaded to '${remotePath}' path inside the sandbox `, +) + +await sandbox.close() +``` +```python Python highlight={6} +from e2b import Sandbox + +sandbox = Sandbox(template="base") + +with open("path/to/local/file", "rb") as f: + remote_path = sandbox.upload_file(f) + +sandbox.close() +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/url/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/url/index.mdx new file mode 100644 index 0000000000..423d3005b1 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/api/url/index.mdx @@ -0,0 +1,60 @@ +--- +title: "Sandbox URL" +--- + +You are reading a legacy (pre v1.0) document. + + +Each sandbox has its own URL that you can use to connect to any service running inside the sandbox. + +For example, you can start a server inside the sandbox and connect to it from your browser. + + +```js JavaScript & TypeScript highlight={5} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ template: 'base' }) + +const url = sandbox.getHostname() +console.log('https://' + url) + +await sandbox.close() +``` +```python Python highlight={5} +from e2b import Sandbox + +sandbox = Sandbox(template="base") + +url = sandbox.get_host() +print("https://" + url) + +sandbox.close() +``` + + + +If you want to get an URL for a specific port inside the sandbox, pass the port number to the `getHostname()`/`get_hostname()` method. + +```js JavaScript & TypeScript highlight={6} +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ template: 'base' }) + +const openPort = 3000 +const url = sandbox.getHostname(openPort) +console.log('https://' + url) + +await sandbox.close() +``` +```python Python highlight={6} +from e2b import Sandbox + +sandbox = Sandbox(template="base") + +open_port = 3000 +url = sandbox.get_host(open_port) +print("https://" + url) + +sandbox.close() +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/compute/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/compute/index.mdx new file mode 100644 index 0000000000..eec0fb8652 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/compute/index.mdx @@ -0,0 +1,31 @@ +--- +title: "Sandbox compute" +--- + +You are reading a legacy (pre v1.0) document. + + +import SandboxSpec from "/snippets/SandboxSpec.mdx"; + +# Sandbox compute +Pro customers can customize the sandbox with **any combination** of the CPU and RAM based on the following tables. + +Read a dedicated page to [learn more about pricing](/legacy/pricing). + + +**By default your sandbox has 2 vCPU and 512 MiB RAM.** + +To customize your sandbox compute, you need to build your custom sandbox template using the [E2B CLI](/legacy/cli/installation). +Run [`e2b template build`](/legacy/cli/commands#template-build) and specify the `--cpu-count` and `--memory-mb` options. + +For example, this custom build command gives your sandbox 8 vCPU and 4GiB of RAM +```sh +e2b template build --cpu-count 8 --memory-mb 4096 +``` + + + + +
+ +[Let us know](/legacy/getting-help) if you need more powerful compute. \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/custom/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/custom/index.mdx new file mode 100644 index 0000000000..c728220f97 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/custom/index.mdx @@ -0,0 +1,55 @@ +--- +title: "Customizing Sandbox" +--- + +You are reading a legacy (pre v1.0) document. + + +Custom sandboxes allows you to spawn a sandbox with a pre-defined environment by you and then control it with our SDK. + +You can build a custom sandbox by creating the [Sandbox Template](/legacy/sandbox/templates/overview). Sandbox template is a Dockerfile that describes the environment of your sandbox. + +Once you build your custom sandbox template, you can spawn multiple isolated sandboxes from it. + +## How it works +1. [Provide the sandbox template file](/legacy/sandbox/templates/template-file) +1. [Build a sandbox template from it using our CLI](/legacy/guide/custom-sandbox#4-build-custom-sandbox) +1. Get a template ID from the CLI: + ```sh + # ... truncated CLI output + ✅ Building sandbox template 3y5bvra6kgq0kaumgztu finished. + ``` +1. Pass the template ID to our SDK like this: + + ```js JavaScript & TypeScript + import { Sandbox } from 'e2b' + + // Create new sandbox + const sandbox = await Sandbox.create({ + template: '', // You get sandbox template ID from the CLI after you run `$ e2b template build` + }) + + // Close sandbox once done + await sandbox.close() + ``` + + ```python Python + from e2b import Sandbox + + # Create new sandbox + sandbox = Sandbox.create( + template="", # You get sandbox template from the CLI after you run `$ e2b template build` + ) + + # Close sandbox once done + sandbox.close() + ``` + +1. Run the code and we spawn a sandbox based on the template you built in step 2 + +Now you can do step 4/5 multiple times using the same ID, always creating a separate sandbox instance. + + + +Read more on [Sandbox Templates](/legacy/sandbox/templates/overview) if you want to create your own custom sandbox. + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/overview/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/overview/index.mdx new file mode 100644 index 0000000000..3521393bd3 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/overview/index.mdx @@ -0,0 +1,81 @@ +--- +title: "Overview" +--- + +You are reading a legacy (pre v1.0) document. + + +**The E2B's sandboxes are isolated cloud environments made specifcially for AI code interpreting or code execution.** + +The E2B sandboxes are an ideal fit as a playground for AI assistants like coding copilots, code interpreters, AI data analysts, AI browser assistants, and other AI-powered apps. + +## Features + + [Open-source](https://github.com/e2b-dev/e2b) sandbox for LLMA full VM environmentNo need for orchestration or infrastructure managementAbility to give each user of your AI app their own isolated environment + + [Python & Node.js SDK](/legacy/getting-started/installation) for controling the sandbox's + + [filesystem](/legacy/sandbox/api/filesystem), + + [processes](/legacy/sandbox/api/process), and more.Support for up to 24h long-running sandbox sessionsAbility to + + [upload files](/legacy/sandbox/api/upload) to the sandbox and + + [download files](/legacy/sandbox/api/download) from the sandbox, + + +With more features coming in the future: +- Out-of-the box working monitoring of what's happening inside the sandbox +- LLM Access control to data, tools, and any internet requests +- Statefull sandboxes +- Resumable workflows (pause sandbox and load it later) +- Unlimited long-running sandboxed + +## Comparison to other services +With LLMs, it's not safe to let the LLM run code and use tools in the same environment where your application is running. + +You need to isolate the LLM from the rest of your app and make sure that the LLM can't access your data, tools, and the internet without you knowing about it or giving it explicit access. You need to make sure that the LLM can run untrusted code safely and install libraries on fly. +The AI apps also often need to run for a long time, and need to be resumable - for example, when waiting for user's consent to make an internet purchase, you need to be able to pause the AI app and resume it later without losing the whole state. + +Additionally, the AI apps present need for a new model: +- How can every user of your AI app have the environment described above for themselves? +- How can developers easily manage and orchestrate these environments? +- How can developers easily debug these environments? +- How to let LLMs use the same tools as humans do on their computers (for example browser, code linters, autocomplete, etc)? +- How can developers easily monitor what's happening inside these environments? +- How to scale these environments to billions of instances? + + + + + +E2B Sandboxes are made exactly to solve these challenges. The sandbox is like an isolated runtime or playground for the LLM. **We give you our SDK to spawn and control these sandboxes.** + + +## How sandboxes work under the hood +When you create a new sandbox session, we start a small VM in our cloud. This VM is running a Ubuntu OS and it takes about 400-600ms to start it. + +Inside this sandbox, your AI app can [run code and start any programs](/legacy/sandbox/api/process), access the internet to download or upload data, use the [filesystem](/legacy/sandbox/api/filesystem), start long running processes such as web servers, and more. +You can also [upload](/legacy/sandbox/api/upload) to sandbox and [download](/legacy/sandbox/api/upload) from sandbox any file you want. + +To start and control the sandbox, use the [E2B SDK](/legacy/getting-started/installation) for Python or JavaScript. + + +```js JavaScript & TypeScript +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() + +await sandbox.close() +``` +```python Python +from e2b import Sandbox + +sandbox = Sandbox.create() +sandbox.close() +``` + + + +Make sure you have the `E2B_API_KEY` environment variable set with your [API key](/legacy/getting-started/api-key). + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/templates/overview/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/templates/overview/index.mdx new file mode 100644 index 0000000000..d850f027ba --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/templates/overview/index.mdx @@ -0,0 +1,68 @@ +--- +title: "Custom Sandbox" +--- + +You are reading a legacy (pre v1.0) document. + + +Custom sandboxes allow you to spawn a sandbox with an environment predefined by you and then control it with our SDK. + + +The E2B Sandbox is a secure way to run your AI app. It is a long-running cloud environment where you can let any LLM (GPTs, Claude, local LLMs, etc) use tools exactly like you would do locally. + +Read more about E2B Sandboxes [here](/legacy/sandbox/overview). + + + +## How Custom Sandboxes Work + + +Follow our [guide](/legacy/guide/custom-sandbox) on how to create a custom sandbox. + + +1. You build a custom sandbox by creating the [Sandbox Template](/legacy/sandbox/templates/template-file) which is a Dockerfile describing the environment of your sandbox. +1. Build a sandbox template from it using our CLI +1. Get a template ID from the CLI: + ```sh + # ... truncated CLI output + ✅ Building sandbox template 3y5bvra6kgq0kaumgztu finished. + ``` +1. Pass the template ID to our SDK like this: + + ```js JavaScript & TypeScript highlight={6} + import { Sandbox } from 'e2b' + + // Create new sandbox + const sandbox = await Sandbox.create({ + // You get sandbox template from the CLI after you run `$ e2b template build` + template: '', + }) + + // Close sandbox once done + await sandbox.close() + ``` + + ```python Python highlight={6} + from e2b import Sandbox + + # Create new sandbox + sandbox = Sandbox.create( + # You get sandbox template from the CLI after you run `$ e2b template build` + template="", + ) + + # Close sandbox once done + sandbox.close() + ``` + +1. Run the code and we spawn a sandbox based on the template you built in step 2 + +Once you build your custom sandbox template, you can spawn multiple isolated sandboxes from it. You can repeat the steps 4, 5 multiple times using the same ID, always creating a separate sandbox instance. + + + + + + +Follow [our guide](/legacy/guide/custom-sandbox) on how to create a custom sandbox. + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/templates/template-file/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/templates/template-file/index.mdx new file mode 100644 index 0000000000..c7e9555815 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/sandbox/templates/template-file/index.mdx @@ -0,0 +1,49 @@ +--- +title: "Template File" +--- + +You are reading a legacy (pre v1.0) document. + + +The template file is a Dockerfile named `e2b.Dockerfile`. The template file is used to define an environment for your custom sandbox. + + +Follow our [guide](/legacy/guide/custom-sandbox) on how to create a custom sandbox. + + + + + + +## `e2b.Dockerfile` +The Dockerfile must be Debian based (e.g. Ubuntu). Only the following [Dockerfile commands](https://docs.docker.com/engine/reference/builder/) are supported: + - `FROM` + - `ADD` + - `COPY` + - `RUN` + - `WORKDIR` + - `ARG` + +## Example + +The following example template file defines a Ubuntu-based sandbox with installed GitHub CLI. + + + +```sh +# You can use most of the Debian-based base images +FROM ubuntu:22.04 + +# Install dependencies and customize sandbox +RUN apt update \ + && apt install sudo + +# Install GitHub CLI +RUN type -p curl >/dev/null || (sudo apt update && sudo apt install curl -y) +RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \ + && sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \ + && echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \ + && sudo apt update \ + && sudo apt install gh -y +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/legacy/supported/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/legacy/supported/index.mdx new file mode 100644 index 0000000000..645360a999 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/legacy/supported/index.mdx @@ -0,0 +1,15 @@ +--- +title: "Supported LLMs and AI frameworks" +--- + +You are reading a legacy (pre v1.0) document. + + +E2B is LLM agnostic - it supports any LLM models and any AI frameworks. + +Usually, all you need from the model is just support for tool use. You then use the E2B code interpreter as a tool. +If the LLM doesn't support tool use, you can ask the LLM to respond with Markdown or XML and parse the LLM's output on your own. Then just pass the parsed code from code blocks to the code interpreter. + + +Check out our [cookbook](https://github.com/e2b-dev/e2b-cookbook) for examples. + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/logo/logo_dark.svg b/apps/web/src/app/(docs)/mintlify-docs/logo/logo_dark.svg new file mode 100644 index 0000000000..51c7a9247e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/logo/logo_dark.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/logo/logo_light.svg b/apps/web/src/app/(docs)/mintlify-docs/logo/logo_light.svg new file mode 100644 index 0000000000..bde45a2f40 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/logo/logo_light.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/logo/white.svg b/apps/web/src/app/(docs)/mintlify-docs/logo/white.svg new file mode 100644 index 0000000000..b8fb4e8928 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/logo/white.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/migration/v2/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/migration/v2/index.mdx new file mode 100644 index 0000000000..b478426e2e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/migration/v2/index.mdx @@ -0,0 +1,146 @@ +--- +title: "SDK v2 Migration Guide" +--- + +This guide helps you migrate from E2B SDK v1 to v2, covering all breaking changes and new patterns. + +## Table of contents + +SDK v2 introduces several important changes: +- [**New creation pattern in Python Synchronous SDK**](#1-sandbox-creation-in-synchronous-python-sdk) +- [**Secure by default**](#2-secure-communication-by-default) +- [**Updated file operations in Python SDK**](#3-file-writing-in-python-sdk) +- [**Updated list method**](#4-listing-sandboxes) + +## Breaking changes + +### 1. Sandbox creation in synchronous Python SDK + +In v2, the synchronous Python SDK uses a class method `create()` instead of the constructor `Sandbox()`. + + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() +sandbox = Sandbox.create(template="base") +``` + + +In the v1, you would instantiate directly: + + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +sandbox = Sandbox(template="base") +``` + + +### 2. Secure communication by default + +Sandboxes are now **secure by default**. That means you cannot access the sandbox directly via its URL; there's authentication required. If you use the SDK, this is handled for you automatically. + +This shouldn't affect you, but if you need to access sandbox directly without SDK and you are now getting 401, you may need to set `secure` to `false`. + + + If you are using custom code interpreter templates, it may be necessary to rebuild the template to ensure compatibility with secure sandboxes. + + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create({ secure: false }) // Explicitly disable +``` + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create(secure=False) # Explicitly disable +``` + + +### 3. File writing in Python SDK + +The file writing API in Python has been made more consistent. + +In v2, use `sandbox.files.write()` for single files and `sandbox.files.write_files()` for multiple files: + +```python v2 +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() + +# Write single file +info = sandbox.files.write("/tmp/file.txt", "content") + +# Write multiple files +infos = sandbox.files.write_files([ + {"path": "/tmp/file1.txt", "data": "content1"}, + {"path": "/tmp/file2.txt", "data": "content2"} +]) +``` + + +In v1, the same `write()` method was overloaded for both single and multiple files: + + +```python v1 +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() + +# Write single file +info = sandbox.write(path="/tmp/file.txt", data="content") + +# Write multiple files +infos = sandbox.write([ + {"path": "/tmp/file1.txt", "data": "content1"}, + {"path": "/tmp/file2.txt", "data": "content2"} +]) +``` + + +### 4. Listing sandboxes + +The method for listing sandboxes has been updated to use pagination. + + +```js JavaScript & TypeScript +import { Sandbox, SandboxInfo } from '@e2b/code-interpreter' + +// Get paginator +const paginator = Sandbox.list() + +// Iterate through all sandboxes +for (const sandbox of await paginator.nextItems()) { + console.log(sandbox.sandboxId) +} + +// Iterate through all sandboxes +const allSandboxes: SandboxInfo[] = [] +while (paginator.hasNext) { + const items = await paginator.nextItems() + allSandboxes.push(...items) +} + +// With query +const queryPaginator = Sandbox.list({query: {metadata: {key: "value"}}}) +``` +```python Python +from e2b_code_interpreter import Sandbox, SandboxQuery + +# Get paginator +paginator = Sandbox.list() + +# Iterate through all sandboxes +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) + +# With query +paginator = Sandbox.list(query=SandboxQuery(metadata={"key": "value"})) +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/quickstart/connect-llms/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/quickstart/connect-llms/index.mdx new file mode 100644 index 0000000000..adfbc664d1 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/quickstart/connect-llms/index.mdx @@ -0,0 +1,807 @@ +--- +title: "Connect LLMs to E2B" +--- + +E2B can work with any LLM and AI framework. The easiest way to connect an LLM to E2B is to use the tool use capabilities of the LLM (sometimes known as function calling). + +If the LLM doesn't support tool use, you can, for example, prompt the LLM to output code snippets and then manually extract the code snippets with [RegEx](https://en.wikipedia.org/wiki/Regular_expression). + +## Contents +- [OpenAI](#openai) +- [Anthropic](#anthropic) +- [Mistral](#mistral) +- [Groq](#groq) +- [Vercel AI SDK](#vercel-ai-sdk) +- [CrewAI](#crewai) +- [LangChain](#langchain) +- [LlamaIndex](#llamaindex) +- [Ollama](#ollama) +- [Hugging Face](#hugging-face) + +--- + +## OpenAI + +### Simple + + +```python Python +# pip install openai e2b-code-interpreter +from openai import OpenAI +from e2b_code_interpreter import Sandbox + +# Create OpenAI client +client = OpenAI() +system = "You are a helpful assistant that can execute python code in a Jupyter notebook. Only respond with the code to be executed and nothing else. Strip backticks in code blocks." +prompt = "Calculate how many r's are in the word 'strawberry'" + +# Send messages to OpenAI API +response = client.chat.completions.create( + model="gpt-4o", + messages=[ + {"role": "system", "content": system}, + {"role": "user", "content": prompt} + ] +) + +# Extract the code from the response +code = response.choices[0].message.content + +# Execute code in E2B Sandbox +if code: + with Sandbox.create() as sandbox: + execution = sandbox.run_code(code) + result = execution.text + + print(result) +``` + + +### Function calling + + +```python Python +# pip install openai e2b-code-interpreter +import json +from openai import OpenAI +from e2b_code_interpreter import Sandbox + +# Create OpenAI client +client = OpenAI() +model = "gpt-4o" + +# Define the messages +messages = [ + { + "role": "user", + "content": "Calculate how many r's are in the word 'strawberry'" + } +] + +# Define the tools +tools = [{ + "type": "function", + "function": { + "name": "execute_python", + "description": "Execute python code in a Jupyter notebook cell and return result", + "parameters": { + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "The python code to execute in a single cell" + } + }, + "required": ["code"] + } + } +}] + +# Generate text with OpenAI +response = client.chat.completions.create( + model=model, + messages=messages, + tools=tools, +) + +# Append the response message to the messages list +response_message = response.choices[0].message +messages.append(response_message) + +# Execute the tool if it's called by the model +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.create() as sandbox: + code = json.loads(tool_call.function.arguments)['code'] + execution = sandbox.run_code(code) + result = execution.text + + # Send the result back to the model + messages.append({ + "role": "tool", + "name": "execute_python", + "content": result, + "tool_call_id": tool_call.id, + }) + +# Generate the final response +final_response = client.chat.completions.create( + model=model, + messages=messages +) + +print(final_response.choices[0].message.content) +``` + + +--- + +## Anthropic + +### Simple + + +```python Python +# pip install anthropic e2b-code-interpreter +from anthropic import Anthropic +from e2b_code_interpreter import Sandbox + +# Create Anthropic client +anthropic = Anthropic() +system_prompt = "You are a helpful assistant that can execute python code in a Jupyter notebook. Only respond with the code to be executed and nothing else. Strip backticks in code blocks." +prompt = "Calculate how many r's are in the word 'strawberry'" + +# Send messages to Anthropic API +response = anthropic.messages.create( + model="claude-3-5-sonnet-20240620", + max_tokens=1024, + messages=[ + {"role": "assistant", "content": system_prompt}, + {"role": "user", "content": prompt} + ] +) + +# Extract code from response +code = response.content[0].text + +# Execute code in E2B Sandbox +with Sandbox.create() as sandbox: + execution = sandbox.run_code(code) + result = execution.logs.stdout + +print(result) +``` + + +### Function calling + + +```python Python +# pip install anthropic e2b-code-interpreter +from anthropic import Anthropic +from e2b_code_interpreter import Sandbox + +# Create Anthropic client +client = Anthropic() +model = "claude-3-5-sonnet-20240620" + +# Define the messages +messages = [ + { + "role": "user", + "content": "Calculate how many r's are in the word 'strawberry'" + } +] + +# Define the tools +tools = [{ + "name": "execute_python", + "description": "Execute python code in a Jupyter notebook cell and return (not print) the result", + "input_schema": { + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "The python code to execute in a single cell" + } + }, + "required": ["code"] + } +}] + +# Generate text with Anthropic +message = client.messages.create( + model=model, + max_tokens=1024, + messages=messages, + tools=tools +) + +# Append the response message to the messages list +messages.append({ + "role": "assistant", + "content": message.content +}) + +# Execute the tool if it's called by the model +if message.stop_reason == "tool_use": + tool_use = next(block for block in message.content if block.type == "tool_use") + tool_name = tool_use.name + tool_input = tool_use.input + + if tool_name == "execute_python": + with Sandbox.create() as sandbox: + code = tool_input['code'] + execution = sandbox.run_code(code) + result = execution.text + + # Append the tool result to the messages list + messages.append({ + "role": "user", + "content": [ + { + "type": "tool_result", + "tool_use_id": tool_use.id, + "content": result, + } + ], + }) + +# Generate the final response +final_response = client.messages.create( + model=model, + max_tokens=1024, + messages=messages, + tools=tools +) + +print(final_response.content[0].text) +``` + + +--- + +## Mistral + +### Simple + + +```python Python +# pip install mistralai e2b-code-interpreter +import os +from mistralai import Mistral +from e2b_code_interpreter import Sandbox + +# Create Mistral client +client = Mistral(api_key=os.environ["MISTRAL_API_KEY"]) +system_prompt = "You are a helpful assistant that can execute python code in a Jupyter notebook. Only respond with the code to be executed and nothing else. Strip backticks in code blocks." +prompt = "Calculate how many r's are in the word 'strawberry'" + +# Send the prompt to the model +response = client.chat.complete( + model="codestral-latest", + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": prompt} + ] +) + +# Extract the code from the response +code = response.choices[0].message.content + +# Execute code in E2B Sandbox +with Sandbox.create() as sandbox: + execution = sandbox.run_code(code) + result = execution.text + +print(result) +``` + + +### Function calling + + +```python Python +# pip install mistralai e2b-code-interpreter +import os +import json +from mistralai import Mistral +from e2b_code_interpreter import Sandbox + +# Create Mistral client +client = Mistral(api_key=os.environ["MISTRAL_API_KEY"]) +model = "mistral-large-latest" +messages = [ + { + "role": "user", + "content": "Calculate how many r's are in the word 'strawberry'" + } +] + +# Define the tools +tools = [{ + "type": "function", + "function": { + "name": "execute_python", + "description": "Execute python code in a Jupyter notebook cell and return result", + "parameters": { + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "The python code to execute in a single cell" + } + }, + "required": ["code"] + } + } +}] + +# Send the prompt to the model +response = client.chat.complete( + model=model, + messages=messages, + tools=tools +) + +# Append the response message to the messages list +response_message = response.choices[0].message +messages.append(response_message) + +# Execute the tool if it's called by the model +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.create() as sandbox: + code = json.loads(tool_call.function.arguments)['code'] + execution = sandbox.run_code(code) + result = execution.text + + # Send the result back to the model + messages.append({ + "role": "tool", + "name": "execute_python", + "content": result, + "tool_call_id": tool_call.id, + }) + +# Generate the final response +final_response = client.chat.complete( + model=model, + messages=messages, +) + +print(final_response.choices[0].message.content) +``` + + +--- + +## Groq + +```python Python + +# pip install groq e2b-code-interpreter +import os +from groq import Groq +from e2b_code_interpreter import Sandbox + +api_key = os.environ["GROQ_API_KEY"] + +# Create Groq client +client = Groq(api_key=api_key) +system_prompt = "You are a helpful assistant that can execute python code in a Jupyter notebook. Only respond with the code to be executed and nothing else. Strip backticks in code blocks." +prompt = "Calculate how many r's are in the word 'strawberry.'" + +# Send the prompt to the model +response = client.chat.completions.create( + model="llama3-70b-8192", + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": prompt}, + ] +) + +# Extract the code from the response +code = response.choices[0].message.content + +# Execute code in E2B Sandbox +with Sandbox.create() as sandbox: + execution = sandbox.run_code(code) + result = execution.text + +print(result) + +``` + + +--- + +## Vercel AI SDK +Vercel's [AI SDK](https://sdk.vercel.ai) offers support for multiple different LLM providers through a unified JavaScript interface that's easy to use. + +### Simple + + +```js JavaScript & TypeScript +// npm install ai @ai-sdk/openai @e2b/code-interpreter +import { openai } from '@ai-sdk/openai' +import { generateText } from 'ai' +import { Sandbox } from '@e2b/code-interpreter' + +// Create OpenAI client +const model = openai('gpt-4o') +const system = "You are a helpful assistant that can execute python code in a Jupyter notebook. Only respond with the code to be executed and nothing else. Strip backticks in code blocks." +const prompt = "Calculate how many r's are in the word 'strawberry'" + +// Generate code with OpenAI +const { text: code } = await generateText({ + model, + system, + prompt +}) + +// Run the code in E2B Sandbox +const sandbox = await Sandbox.create() +const { text, results, logs, error } = await sandbox.runCode(code) + +console.log(text) +``` + + +### Function calling + + +```js JavaScript & TypeScript +// npm install ai @ai-sdk/openai zod @e2b/code-interpreter +import { openai } from '@ai-sdk/openai' +import { generateText } from 'ai' +import z from 'zod' +import { Sandbox } from '@e2b/code-interpreter' + +// Create OpenAI client +const model = openai('gpt-4o') + +const prompt = "Calculate how many r's are in the word 'strawberry'" + +// Generate text with OpenAI +const { text } = await generateText({ + model, + prompt, + tools: { + // Define a tool that runs code in a sandbox + execute_python: { + description: 'Execute python code in a Jupyter notebook cell and return result', + parameters: z.object({ + code: z.string().describe('The python code to execute in a single cell'), + }), + execute: async ({ code }) => { + // Create a sandbox, execute LLM-generated code, and return the result + const sandbox = await Sandbox.create() + const { text, results, logs, error } = await sandbox.runCode(code) + return results + }, + }, + }, + // This is required to feed the tool call result back to the LLM + maxSteps: 2 +}) + +console.log(text) +``` + + +--- + +## CrewAI +[CrewAI](https://crewai.com/) is a platform for building AI agents. + + +```python Python +# pip install crewai e2b-code-interpreter +from crewai.tools import tool +from crewai import Agent, Task, Crew, LLM +from e2b_code_interpreter import Sandbox + +# Update tool definition using the decorator +@tool("Python Interpreter") +def execute_python(code: str) -> str: + """ + Execute Python code and return the results. + """ + with Sandbox.create() as sandbox: + execution = sandbox.run_code(code) + return execution.text + +# Define the agent +python_executor = Agent( + role='Python Executor', + goal='Execute Python code and return the results', + backstory='You are an expert Python programmer capable of executing code and returning results.', + tools=[execute_python], + llm=LLM(model="gpt-4o") +) + +# Define the task +execute_task = Task( + description="Calculate how many r's are in the word 'strawberry'", + agent=python_executor, + expected_output="The number of r's in the word 'strawberry'" +) + +# Create the crew +code_execution_crew = Crew( + agents=[python_executor], + tasks=[execute_task], + verbose=True, +) + +# Run the crew +result = code_execution_crew.kickoff() +print(result) +``` + + +--- + +## LangChain +[LangChain](https://langchain.com/) offers support multiple different LLM providers. + +### Simple + + +```python Python +# pip install langchain langchain-openai e2b-code-interpreter +from langchain_openai import ChatOpenAI +from langchain_core.prompts import ChatPromptTemplate +from langchain_core.output_parsers import StrOutputParser +from e2b_code_interpreter import Sandbox + +system_prompt = "You are a helpful assistant that can execute python code in a Jupyter notebook. Only respond with the code to be executed and nothing else. Strip backticks in code blocks." +prompt = "Calculate how many r's are in the word 'strawberry'" + +# Create LangChain components +llm = ChatOpenAI(model="gpt-4o") +prompt_template = ChatPromptTemplate.from_messages([ + ("system", system_prompt), + ("human", "{input}") +]) + +output_parser = StrOutputParser() + +# Create the chain +chain = prompt_template | llm | output_parser + +# Run the chain +code = chain.invoke({"input": prompt}) + +# Execute code in E2B Sandbox +with Sandbox.create() as sandbox: + execution = sandbox.run_code(code) + result = execution.text + +print(result) +``` + + +### Agent + + +```python Python +# pip install langchain langchain-openai e2b-code-interpreter +from langchain_core.prompts import ChatPromptTemplate +from langchain_core.tools import tool +from langchain.agents import create_tool_calling_agent, AgentExecutor +from langchain_openai import ChatOpenAI +from e2b_code_interpreter import Sandbox + +system_prompt = "You are a helpful assistant that can execute python code in a Jupyter notebook. Only respond with the code to be executed and nothing else. Strip backticks in code blocks." +prompt = "Calculate how many r's are in the word 'strawberry'" + +# Define the tool +@tool +def execute_python(code: str): + """ + Execute python code in a Jupyter notebook. + """ + with Sandbox.create() as sandbox: + execution = sandbox.run_code(code) + return execution.text + +# Define LangChain components +prompt_template = ChatPromptTemplate.from_messages([ + ("system", system_prompt), + ("human", "{input}"), + ("placeholder", "{agent_scratchpad}"), +]) + +tools = [execute_python] +llm = ChatOpenAI(model="gpt-4o", temperature=0) + +agent = create_tool_calling_agent(llm, tools, prompt_template) +agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) + +# Run the agent +agent_executor.invoke({"input": prompt}) +``` + + +### Function calling + + +```python Python +# pip install langchain langchain-openai e2b-code-interpreter +from langchain_openai import ChatOpenAI +from langchain.tools import Tool +from langchain.schema import HumanMessage, AIMessage, FunctionMessage +from e2b_code_interpreter import Sandbox + +def execute_python(code: str): + with Sandbox.create() as sandbox: + execution = sandbox.run_code(code) + return execution.text + +# Define a tool that uses the E2B Sandbox +e2b_sandbox_tool = Tool( + name="execute_python", + func=execute_python, + description="Execute python code in a Jupyter notebook cell and return result" +) + +# Initialize the language model and bind the tool +llm = ChatOpenAI(model="gpt-4o").bind_tools([e2b_sandbox_tool]) + +# Define the messages +messages = [ + HumanMessage(content="Calculate how many 'r's are in the word 'strawberry'.") +] + +# Run the model with a prompt +result = llm.invoke(messages) +messages.append(AIMessage(content=result.content)) + +# Check if the model called the tool +if result.additional_kwargs.get('tool_calls'): + tool_call = result.additional_kwargs['tool_calls'][0] + if tool_call['function']['name'] == "execute_python": + code = tool_call['function']['arguments'] + execution_result = execute_python(code) + + # Send the result back to the model + messages.append( + FunctionMessage(name="execute_python", content=execution_result) + ) + +final_result = llm.invoke(messages) +print(final_result.content) +``` + + +--- + +## LlamaIndex +[LlamaIndex](https://www.llamaindex.ai/) offers support multiple different LLM providers. + +```python Python +# pip install llama-index e2b-code-interpreter +from llama_index.core.tools import FunctionTool +from llama_index.llms.openai import OpenAI +from llama_index.core.agent import ReActAgent +from e2b_code_interpreter import Sandbox + +# Define the tool +def execute_python(code: str): + with Sandbox.create() as sandbox: + execution = sandbox.run_code(code) + return execution.text + +e2b_sandbox_tool = FunctionTool.from_defaults( + name="execute_python", + description="Execute python code in a Jupyter notebook cell and return result", + fn=execute_python +) + +# Initialize LLM +llm = OpenAI(model="gpt-4o") + +# Initialize ReAct agent +agent = ReActAgent.from_tools([e2b_sandbox_tool], llm=llm, verbose=True) +agent.chat("Calculate how many r's are in the word 'strawberry'") +``` + + +## Ollama + + +```python Python +# pip install ollama +import ollama +from e2b_code_interpreter import Sandbox + +# Send the prompt to the model +response = ollama.chat( + model="llama3.2", + messages=[{ + "role": "system", + "content": "You are a helpful assistant that can execute python code in a Jupyter notebook. Only respond with the code to be executed and nothing else. Strip backticks in code blocks." + }, + { + "role": "user", + "content": "Calculate how many r's are in the word 'strawberry'" + } +]) + +# Extract the code from the response +code = response['message']['content'] + +# Execute code in E2B Sandbox +with Sandbox.create() as sandbox: + execution = sandbox.run_code(code) + result = execution.logs.stdout + +print(result) +``` + + +--- + +## Hugging Face + +Hugging Face offers support for serverless inference for models on their model hub with [Hugging Face's Inference API](https://huggingface.co/docs/inference-providers/en/index). + + +Note that not every model on Hugging Face has native support for tool use and function calling. + + + +```python Python +from huggingface_hub import InferenceClient +from e2b_code_interpreter import Sandbox +import re + +# Not all models are capable of direct tools use - we need to extract the code block manually and prompting the LLM to generate the code. +def match_code_block(llm_response): + pattern = re.compile(r'```python Python\n(.*?)\n```', re.DOTALL) # Match everything in between ```python and ``` + match = pattern.search(llm_response) + if match: + code = match.group(1) + print(code) + return code + return "" + + +system_prompt = """You are a helpful coding assistant that can execute python code in a Jupyter notebook. You are given tasks to complete and you run Python code to solve them. +Generally, you follow these rules: +- ALWAYS FORMAT YOUR RESPONSE IN MARKDOWN +- ALWAYS RESPOND ONLY WITH CODE IN CODE BLOCK LIKE THIS: +\`\`\`python +{code} +\`\`\` +""" +prompt = "Calculate how many r's are in the word 'strawberry.'" + +# Initialize the client +client = InferenceClient( + provider="hf-inference", + api_key="HF_INFERENCE_API_KEY" +) + +completion = client.chat.completions.create( + model="Qwen/Qwen3-235B-A22B", # Or use any other model from Hugging Face + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": prompt}, + ] +) + +content = completion.choices[0].message.content +code = match_code_block(content) + +with Sandbox.create() as sandbox: + execution = sandbox.run_code(code) + print(execution) +``` + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/quickstart/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/quickstart/index.mdx new file mode 100644 index 0000000000..9890edc285 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/quickstart/index.mdx @@ -0,0 +1,71 @@ +--- +title: Running your first Sandbox +description: This guide will show you how to start your first E2B Sandbox. +--- + + + +Every new E2B account get $100 in credits. You can sign up [here](https://e2b.dev/auth/sign-up). + + +1. Navigate to the E2B Dashboard. +2. Copy your API key. +3. Paste your E2B API key into your .env file. + +```bash .env +E2B_API_KEY=e2b_*** +``` + + +Install the E2B SDK to your project by running the following command in your terminal. + +```javascript JavaScript & TypeScript +npm i @e2b/code-interpreter dotenv +``` +```python Python +pip install e2b-code-interpreter python-dotenv +``` + + + +We'll write the minimal code for starting Sandbox, executing Python inside it and listing all files inside the root directory. + +```javascript JavaScript & TypeScript +// index.ts +import 'dotenv/config' +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = await Sandbox.create() // By default the sandbox is alive for 5 minutes +const execution = await sbx.runCode('print("hello world")') // Execute Python inside the sandbox +console.log(execution.logs) + +const files = await sbx.files.list('/') +console.log(files) +``` +```python Python +# main.py +from dotenv import load_dotenv +load_dotenv() +from e2b_code_interpreter import Sandbox + +sbx = Sandbox() # By default the sandbox is alive for 5 minutes +execution = sbx.run_code("print('hello world')") # Execute Python inside the sandbox +print(execution.logs) + +files = sbx.files.list("/") +print(files) +``` + + + +Run the code with the following command: + +```bash JavaScript & TypeScript +npx tsx ./index.ts +``` +```bash Python +python main.py +``` + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/quickstart/install-custom-packages/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/quickstart/install-custom-packages/index.mdx new file mode 100644 index 0000000000..26b63225e8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/quickstart/install-custom-packages/index.mdx @@ -0,0 +1,189 @@ +--- +title: "Install custom packages" +--- + +There are two ways to install custom packages in the E2B Sandbox. + +1. [Create custom sandbox with preinstalled packages](#create-a-custom-sandbox). +2. [Install packages during the sandbox runtime](#install-packages-during-the-sandbox-runtime). + +--- + +## Create a custom sandbox + +Use this option if you know beforehand what packages you need in the sandbox. + +Prerequisites: +- E2B CLI +- Docker running + + +Custom sandbox template is a Docker image that we automatically convert to a sandbox that you can then start with our SDK. + + + +### 1. Install E2B CLI + +**Using Homebrew (on macOS)** + + +```bash Terminal +brew install e2b +``` + + +**Using NPM** + + +```bash Terminal +npm i -g @e2b/cli +``` + + +### 2. Login to E2B CLI +Before you can create a custom sandbox, you need to login to E2B CLI. + +```bash Terminal +e2b auth login +``` + + +### 2. Initialize a sandbox template + +```bash Terminal +e2b template init +``` + + +### 3. Specify the packages you need in `e2b.Dockerfile` +Edit the E2B Dockerfile to install the packages you need. + + +You need to use the `e2bdev/code-interpreter:latest` base image. + + + +```bash e2b.Dockerfile +FROM e2bdev/code-interpreter:latest + +RUN pip install cowsay +RUN npm install cowsay +``` + + +### 4. Build the sandbox template +Run the following command to build the sandbox template. + +```bash Terminal +e2b template build -c "/root/.jupyter/start-up.sh" +``` + + +This will take a while, as it convert the Docker image to a sandbox which is a small VM. +At the end of the process you will see the sandbox ID like this: +``` +Running postprocessing. It can take up to few minutes. + +Postprocessing finished. + +✅ Building sandbox template YOUR_TEMPLATE_ID finished. +``` + +### 5. Start your custom sandbox +Now you can pass the template ID to the SDK to start your custom sandbox. + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = Sandbox.create({ + template: 'YOUR_TEMPLATE_ID', +}) +``` +```python Python +from e2b_code_interpreter import Sandbox + +sbx = Sandbox.create(template='YOUR_TEMPLATE_ID') +``` + + +--- + + +## Install packages during the sandbox runtime +Use this option if don't know beforehand what packages you need in the sandbox. You can install packages with the package manager of your choice. + + +The packages installed during the runtime are available only in the running sandbox instance. +When you start a new sandbox instance, the packages are not be available. + + +### 1. Install Python packages with PIP + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = Sandbox.create() +sbx.commands.run('pip install cowsay') // This will install the cowsay package +sbx.runCode(` + import cowsay + cowsay.cow("Hello, world!") +`) +``` +```python Python +from e2b_code_interpreter import Sandbox + +sbx = Sandbox.create() +sbx.commands.run("pip install cowsay") # This will install the cowsay package +sbx.run_code(""" + import cowsay + cowsay.cow("Hello, world!") +""") +``` + + + +### 2. Install Node.js packages with NPM + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = Sandbox.create() +sbx.commands.run('npm install cowsay') // This will install the cowsay package +sbx.runCode(` + const cowsay = require('cowsay') + console.log(cowsay.say({ text: 'Hello, world!' })) +`, { language: 'javascript' }) +``` +```python Python +from e2b_code_interpreter import Sandbox + +sbx = Sandbox.create() +sbx.commands.run("npm install cowsay") # This will install the cowsay package +sbx.run_code(""" + import { say } from 'cowsay' + console.log(say('Hello, world!')) +""", language="javascript") +``` + + + +### 3. Install packages with package manager of your choice +Since E2B Sandboxes are Debian based machines, you can use any package manager supported by Debian. +You just need to make sure that the package manager is already installed in the sandbox. + +For example, to install `curl` and `git`, you can use the following commands: + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = Sandbox.create() +await sbx.commands.run('apt-get update && apt-get install -y curl git') +``` +```python Python +from e2b_code_interpreter import Sandbox + +sbx = Sandbox.create() +sbx.commands.run("apt-get update && apt-get install -y curl git") +``` + \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/quickstart/upload-download-files/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/quickstart/upload-download-files/index.mdx new file mode 100644 index 0000000000..5c4345858c --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/quickstart/upload-download-files/index.mdx @@ -0,0 +1,150 @@ +--- +title: "Upload & downloads files" +--- + +E2B Sandbox allows you to upload and downloads file to and from the Sandbox. + +An alternative way to get your data to the sandbox is to create a [custom sandbox template](/sandbox-template). + + +## Upload file + +```ts JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +// Read local file relative to the current working directory +const content = fs.readFileSync('local/file') + +const sbx = await Sandbox.create() +// Upload file to the sandbox to absolute path '/home/user/my-file' +await sbx.files.write('/home/user/my-file', content) +``` + +```python Python +from e2b_code_interpreter import Sandbox + +sbx = Sandbox.create() + +# Read local file relative to the current working directory +with open("local/file", "rb") as file: + # Upload file to the sandbox to absolute path '/home/user/my-file' + sbx.files.write("/home/user/my-file", file) +``` + + + +## Upload multiple files +Currently, if you want to upload multiple files, you need to upload each one of the separately. +We're working on a better solution. + + +```ts JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +// Read local file relative to the current working directory +const fileA = fs.readFileSync('local/file/a') +const fileB = fs.readFileSync('local/file/b') + +const sbx = await Sandbox.create() +// Upload file A to the sandbox to absolute path '/home/user/my-file-a' +await sbx.files.write('/home/user/my-file-a', fileA) +// Upload file B to the sandbox to absolute path '/home/user/my-file-b' +await sbx.files.write('/home/user/my-file-b', fileB) +``` + +```python Python +from e2b_code_interpreter import Sandbox + +sbx = Sandbox.create() + +# Read local file relative to the current working directory +with open("local/file/a", "rb") as file: + # Upload file to the sandbox to absolute path '/home/user/my-file-a' + sbx.files.write("/home/user/my-file-a", file) + +with open("local/file/b", "rb") as file: + # Upload file to the sandbox to absolute path '/home/user/my-file-b' + sbx.files.write("/home/user/my-file-b", file) +``` + + + +## Upload directory +We currently don't support an easy way to upload a whole directory. +You need to upload each file separately. + +We're working on a better solution. + +--- + +## Download file +To download a file, you need to first get the file's content and then write it to a local file. + + +```ts JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = await Sandbox.create() +// Download file from the sandbox to absolute path '/home/user/my-file' +const content = await sbx.files.read('/home/user/my-file') +// Write file to local path relative to the current working directory +fs.writeFileSync('local/file', content) +``` + +```python Python +from e2b_code_interpreter import 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 +with open('local/file', 'w') as file: + file.write(content) +``` + + +## Download multiple files +To download multiple files, you need to download each one of them separately from the sandbox. + +We're working on a better solution. + + + +```ts JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = await Sandbox.create() +// Download file A from the sandbox by absolute path '/home/user/my-file-a' +const contentA = await sbx.files.read('/home/user/my-file-a') +// Write file A to local path relative to the current working directory +fs.writeFileSync('local/file/a', contentA) + +// Download file B from the sandbox by absolute path '/home/user/my-file-b' +const contentB = await sbx.files.read('/home/user/my-file-b') +// Write file B to local path relative to the current working directory +fs.writeFileSync('local/file/b', contentB) +``` + +```python Python +from e2b_code_interpreter import 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 directory +with open('local/file/a', 'w') as file: + file.write(contentA) + +# Download file B from the sandbox by absolute path '/home/user/my-file-b' +contentB = sbx.files.read('/home/user/my-file-b') +# Write file B to local path relative to the current working directory +with open('local/file/b', 'w') as file: + file.write(contentB) +``` + + +## Download directory +We currently don't support an easy way to download a whole directory. +You need to download each file separately. + +We're working on a better solution. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox-template/customize-cpu-ram/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox-template/customize-cpu-ram/index.mdx new file mode 100644 index 0000000000..dc669f6a05 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox-template/customize-cpu-ram/index.mdx @@ -0,0 +1,18 @@ +--- +title: "Customize sandbox CPU & RAM" +sidebarTitle: Customize CPU & RAM +--- + +You can customize the CPU and RAM of your sandbox template via E2B CLI. + +You'll need to create a sandbox [template first](/sandbox-template). + +During the build step, you can specify the CPU and RAM of your sandbox template. + +The following command will create a sandbox template with 2 CPUs and 2GB of RAM. + + +```bash Terminal +e2b template build -c "/root/.jupyter/start-up.sh" --cpu-count 2 --memory-mb 2048 +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox-template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox-template/index.mdx new file mode 100644 index 0000000000..5ceff2375b --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox-template/index.mdx @@ -0,0 +1,138 @@ +--- +title: "Sandbox templates" +sidebarTitle: Sandbox customization +--- + +Sandbox templates allow you to customize the sandbox environment to your needs. + +To create a sandbox template, you specify the `e2b.Dockerfile`. We then take this Dockerfile and create a new sandbox template from it and give you back a template ID. + +You can then use this template ID to create a new sandbox with the SDK based on the template you created. + +## How to create custom sandbox + +**Steps** +1. [Install E2B CLI](#1-install-e2b-cli) +1. [Initialize sandbox template](#2-initialize-sandbox-template) +1. [Customize `e2b.Dockerfile`](#3-customize-e2b-dockerfile) +1. [Build your sandbox template](#4-build-your-sandbox-template) +1. [Start your custom sandbox](#5-start-your-custom-sandbox) + + +### 1. Install E2B CLI + +**Using Homebrew (on macOS)** + + + ```bash Homebrew + brew install e2b + ``` + + +**Using NPM** + + + ```bash NPM + npm i -g @e2b/cli + ``` + + +### 2. Initialize sandbox template +The following command will create a basic `e2b.Dockerfile` in the current directory. + + + ```bash bash + e2b template init + ``` + + +### 3. Customize `e2b.Dockerfile` +Now you can customize your sandbox template by editing the `e2b.Dockerfile` file. + + ```bash e2b.Dockerfile highlight={2,5} + # Make sure to use this base image + FROM e2bdev/code-interpreter:latest + + # Install some Python packages + RUN pip install cowsay + ``` + + + + Only [Debian-based](https://en.wikipedia.org/wiki/List_of_Linux_distributions#Debian-based) images + (e.g., Debian, Ubuntu, or [E2B images](https://hub.docker.com/u/e2bdev)) are supported. + + +### 4. Build your sandbox template +Now you can build your sandbox template. We'll use Docker and the E2B CLI. +What is going to happen is that E2B CLI will call Docker to build the image and then push it to the E2B cloud. +Then we convert the Docker image to a micro VM that can be then launched as a sandbox with our SDK. + + + ```bash bash + e2b template build -c "/root/.jupyter/start-up.sh" + ``` + + +This process will take a moment. In the end, you'll see your template ID that you'll need to use to create a sandbox with the SDK. + +### 5. Start your custom sandbox +Now you can use the template ID to create a sandbox with the SDK. + + + ```javascript JavaScript & TypeScript highlight={4,6} + import { Sandbox } from '@e2b/code-interpreter' + + // Your template ID from the previous step + const templateID = 'id-of-your-template' + // Pass the template ID to the `Sandbox.create` method + const sandbox = await Sandbox.create(templateID) + + // The template installed cowsay, so we can use it + const execution = await sandbox.runCode(` + import cowsay + cowsay.say('Hello from E2B!') + `) + + console.log(execution.stdout) + ``` + ```python Python highlight={4,6} + from e2b_code_interpreter import Sandbox + + # Your template ID from the previous step + template_id = 'id-of-your-template' + # Pass the template ID to the `Sandbox.create` method + sandbox = Sandbox.create(template_id) + + # The template installed cowsay, so we can use it + execution = sandbox.run_code(""" + import cowsay + cowsay.say('Hello from E2B!') + """) + + print(execution.stdout) + ``` + + +## How it works +Every time you are building a sandbox template, we create a container based on the [`e2b.Dockerfile`](/sandbox-template#3-customize-e2b-dockerfile) file you create in the process. +We extract the container's filesystem, do provisioning and configuration (e.g. installing required dependencies), and start a sandbox. + +Then, these steps happen: + + 1. We take the running sandbox. + 2. (Only if you specified the [start command](/sandbox-template/start-cmd), otherwise this step is skipped) Execute the start command. + 3. Wait for readiness (by default 20 seconds if start command is specified, otherwise immediately ready). Readiness check can be configured using [ready command](/sandbox-template/ready-cmd). + 4. Snapshot the sandbox and make it ready for you to spawn it with the SDK. + +We call this sandbox snapshot a _sandbox template_. + + + **Sandbox Snapshot** + + Snapshots are saved running sandboxes. We serialize and save the whole sandbox's filesystem together with all the + running processes in a way that can be loaded later. + + This allows us to load the sandbox in a few hundred milliseconds any time later with all the processes already running + and the filesystem exactly as it was. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox-template/ready-cmd/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox-template/ready-cmd/index.mdx new file mode 100644 index 0000000000..4d5b4c54ae --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox-template/ready-cmd/index.mdx @@ -0,0 +1,51 @@ +--- +title: "Ready Command" +sidebarTitle: Ready command +--- + +The ready command allows you to specify a command that will determine **template sandbox** readiness before a [snapshot](/sandbox-template#how-it-works) is created. +It is executed in an infinite loop until it returns a successful **exit code 0**. +This way you can control how long should we wait for the [start command](/sandbox-template/start-cmd) or any system state. + + +## How to add ready command + +When you are building a sandbox template you can specify the ready command by using the [`--ready-cmd`](/sdk-reference/cli/v1.5.0/template#e2b-template-build) option: + +```bash +e2b template build --ready-cmd "" +``` + +### Sandbox template config +You can specify the ready command inside the `e2b.toml` in the same directory where you run `e2b template build`. + + ```toml e2b.toml highlight={5} + # This is a config for E2B sandbox template + template_id = "1wdqsf9le9gk21ztb4mo" + dockerfile = "e2b.Dockerfile" + template_name = "my-agent-sandbox" + ready_cmd = "" + ``` + + +## Default values +By default, the ready command is set to `sleep 0`, which means the sandbox template will be ready immediatelly. +If the [start command](/sandbox-template/start-cmd) is defined, the default is set to `sleep 20`, which means that the template sandbox will wait for 20 seconds before taking the snapshot. + +## Examples +Here are some examples of the ready command you can use. + +### Wait for URL to return 200 status code +```bash +ready_cmd = 'curl -s -o /dev/null -w "%{http_code}" http://localhost:3000 | grep -q "200"' +``` + +### Wait for a specific process to start +```bash +ready_cmd = 'pgrep my-process-name > /dev/null' +``` + +### Wait for a file to exist +```bash +ready_cmd = '[ -f /tmp/ready.flag ]' +``` \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox-template/start-cmd/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox-template/start-cmd/index.mdx new file mode 100644 index 0000000000..ea85d5faf9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox-template/start-cmd/index.mdx @@ -0,0 +1,47 @@ +--- +title: "Start Command" +sidebarTitle: Start command +--- + +The start command allows you to specify a command that will be **already running** when you spawn your custom sandbox. +This way, you can for example have running servers or seeded databases inside the sandbox that are already fully ready when you spawn the sandbox using the SDK and with zero waiting time for your users during the runtime. + +The idea behind the start command feature is to lower the wait times for your users and have everything ready for your users when you spawn your sandbox. + +You can see how it works [here](/sandbox-template#how-it-works). + +## How to add start command + +When you are building a sandbox template you can specify the start command by using the [`-c`](/sdk-reference/cli/v1.0.9/template#e2b-template-build) option: + +```bash +e2b template build -c "" +``` + +When you spawn the custom sandbox you built, the start command will be already running if there was no error when we tried to execute it. + +### Sandbox template config +You can specify the start command also inside the `e2b.toml` in the same directory where you run `e2b template build`. + + ```toml e2b.toml highlight={5} + # This is a config for E2B sandbox template + template_id = "1wdqsf9le9gk21ztb4mo" + dockerfile = "e2b.Dockerfile" + template_name = "my-agent-sandbox" + start_cmd = "" + ``` + + + +## Logs +You can retrieve the start command's logs using the CLI: + + +```bash bash +e2b sandbox logs +``` + + + +These logs include logs from the start command during the build phase. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox/connect-bucket/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox/connect-bucket/index.mdx new file mode 100644 index 0000000000..b162c7b90d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox/connect-bucket/index.mdx @@ -0,0 +1,166 @@ +--- +title: "Connecting storage bucket to the sandbox" +sidebarTitle: Connecting storage bucket +--- + +To connect a bucket for storing data from the sandbox, we will use the FUSE file system to mount the bucket to the sandbox. + +You will need to create a custom sandbox template with the FUSE file system installed. The guide for building a custom sandbox template can be found [here](/sandbox-template). + +## Google Cloud Storage +### Prerequisites + +To use Google Cloud Storage, you'll need a bucket and a service account. You can create a service account [here](https://console.cloud.google.com/iam-admin/serviceaccounts) and a bucket [here](https://console.cloud.google.com/storage). + +If you want to write to the bucket, make sure the service account has the `Storage Object User` role for this bucket. + +You can find a guide on creating a service account key [here](https://cloud.google.com/iam/docs/keys-create-delete#iam-service-account-keys-create-console). + +### Mounting the bucket + +To use the Google Cloud Storage we need to install the `gcsfuse` package. There's simple `Dockerfile` that can be used to create a container with the `gcsfuse` installed. + +```docker +FROM e2bdev/code-interpreter:latest + +RUN apt-get update && apt-get install -y gnupg lsb-release wget + +RUN lsb_release -c -s > /tmp/lsb_release +RUN GCSFUSE_REPO=$(cat /tmp/lsb_release) && echo "deb https://packages.cloud.google.com/apt gcsfuse-$GCSFUSE_REPO main" | tee /etc/apt/sources.list.d/gcsfuse.list +RUN wget -O - https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add - + +RUN apt-get update && apt-get install -y gcsfuse + +``` + +The bucket is mounted during the sandbox runtime using the `gcsfuse` command. + + +```js JavaScript & TypeScript +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create('') +await sandbox.files.makeDir('/home/user/bucket') +await sandbox.files.write('key.json', '') + +await sandbox.commands.run('sudo gcsfuse --key-file /home/user/key.json /home/user/bucket') +``` + +```python Python +from e2b import Sandbox + +sandbox = Sandbox.create("") +sandbox.files.make_dir("/home/user/bucket") +sandbox.files.write("key.json", "") + +output = sandbox.commands.run( + "sudo gcsfuse --key-file /home/user/key.json /home/user/bucket" +) +``` + + +### Flags + +The complete list of flags is available [here](https://cloud.google.com/storage/docs/gcsfuse-cli#options). + +### Allow the default user to access the files + +To allow the default user to access the files, we can use the following flags: + +``` +-o allow_other -file-mode=777 -dir-mode=777 +``` + +## Amazon S3 + +To use Amazon S3, we can use the `s3fs` package. The `Dockerfile` setup is similar to that of Google Cloud Storage. + +```docker +FROM ubuntu:latest + +RUN apt-get update && apt-get install s3fs +``` + +Similar to Google Cloud Storage, the bucket is mounted during the runtime of the sandbox. The `s3fs` command is used to mount the bucket to the sandbox. + + +```js JavaScript & TypeScript +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create('') +await sandbox.files.makeDir('/home/user/bucket') + +// Create a file with the credentials +// If you use another path for the credentials you need to add the path in the command s3fs command +await sandbox.files.write('/root/.passwd-s3fs', ':') +await sandbox.commands.run('sudo chmod 600 /root/.passwd-s3fs') + +await sandbox.commands.run('sudo s3fs /home/user/bucket') +``` + +```python Python +from e2b import Sandbox + +sandbox = Sandbox.create("") +sandbox.files.make_dir("/home/user/bucket") + +# Create a file with the credentials +# If you use another path for the credentials you need to add the path in the command s3fs command +sandbox.files.write("/root/.passwd-s3fs", ":") +sandbox.commands.run("sudo chmod 600 /root/.passwd-s3fs") + +sandbox.commands.run("sudo s3fs /home/user/bucket") +``` + + +### Flags + +The complete list of flags is available [here](https://manpages.ubuntu.com/manpages/xenial/man1/s3fs.1.html). + +### Allow the default user to access the files + +To allow the default user to access the files, add the following flag: + +``` +-o allow_other +``` + +## Cloudflare R2 + +For Cloudflare R2, we can use a setup very similar to S3. The `Dockerfile` remains the same as for S3. However, the mounting differs slightly; we need to specify the endpoint for R2. + + +```js JavaScript & TypeScript +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create({ template: '' }) +await sandbox.files.makeDir('/home/user/bucket') + +// Create a file with the R2 credentials +// If you use another path for the credentials you need to add the path in the command s3fs command +await sandbox.files.write('/root/.passwd-s3fs', ':') +await sandbox.commands.run('sudo chmod 600 /root/.passwd-s3fs') + +await sandbox.commands.run('sudo s3fs -o url=https://.r2.cloudflarestorage.com /home/user/bucket') +``` + +```python Python +from e2b import Sandbox + +sandbox = Sandbox.create("") +sandbox.files.make_dir("/home/user/bucket") + +# Create a file with the R2 credentials +# If you use another path for the credentials you need to add the path in the command s3fs command +sandbox.files.write("/root/.passwd-s3fs", ":") +sandbox.commands.run("sudo chmod 600 /root/.passwd-s3fs") + +sandbox.commands.run( + "sudo s3fs -o url=https://.r2.cloudflarestorage.com /home/user/bucket" +) +``` + + +### Flags + +It's the same as for S3. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox/connect/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox/connect/index.mdx new file mode 100644 index 0000000000..d2bd054294 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox/connect/index.mdx @@ -0,0 +1,88 @@ +--- +title: "Connect to running sandbox" +--- + +If you have a running sandbox, you can connect to it using the `Sandbox.connect()` method and then start controlling it with our SDK. + +This is useful if you want to, for example, reuse the same sandbox instance for the same user after a short period of inactivity. + +## 1. Get the sandbox ID +To connect to a running sandbox, you first need to retrieve its ID. You can do this by calling the `Sandbox.list()` method. + + +```js JavaScript & TypeScript highlight={6} +import { Sandbox } from '@e2b/code-interpreter' +const sbx = await Sandbox.create() + +// Get all running sandboxes +const paginator = await Sandbox.list({ + query: { state: ['running'] }, +}) + +const runningSandboxes = await paginator.nextItems() +if (runningSandboxes.length === 0) { + throw new Error('No running sandboxes found') +} + +// Get the ID of the sandbox you want to connect to +const sandboxId = runningSandboxes[0].sandboxId +``` + +```python Python highlight={4} +from e2b_code_interpreter import Sandbox + +# Get all running sandboxes +paginator = Sandbox.list() + +# 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") + +# Get the ID of the sandbox you want to connect to +sandbox_id = running_sandboxes[0].sandbox_id + +``` + + +## 2. Connect to the sandbox + +Now that you have the sandbox ID, you can connect to the sandbox using the `Sandbox.connect()` method. + + +```js JavaScript & TypeScript highlight={14} +import { Sandbox } from "@e2b/code-interpreter" + +// Get all running sandboxes +const runningSandboxes = await Sandbox.list() + +if (runningSandboxes.length === 0) { + throw new Error("No running sandboxes found") +} + +// Get the ID of the sandbox you want to connect to +const sandboxId = runningSandboxes[0].sandboxId + +// Connect to the sandbox +const sandbox = await Sandbox.connect(sandboxId) +// Now you can use the sandbox as usual +// ... +``` +```python Python highlight={13} +from e2b_code_interpreter import Sandbox + +# Get all running sandboxes +running_sandboxes = Sandbox.list() + +# Get the ID of the sandbox you want to connect to +if len(running_sandboxes) == 0: + raise Exception("No running sandboxes found") + +sandbox_id = running_sandboxes[0].sandbox_id + +# Connect to the sandbox +sandbox = Sandbox.connect(sandbox_id) +# Now you can use the sandbox as usual +# ... +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox/environment-variables/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox/environment-variables/index.mdx new file mode 100644 index 0000000000..3f91b1a5d3 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox/environment-variables/index.mdx @@ -0,0 +1,123 @@ +--- +title: "Environment variables" +--- + +This page covers how to set and use environment variables in a sandbox, and default environment variables inside the sandbox. + +## Default environment variables +### Knowing if you are inside a sandbox + +Sometimes it's useful to know if the code is running inside a sandbox. Upon creating a sandbox, useful sandbox metadata is set as environment variables for commands: +- `E2B_SANDBOX` is set to `true` for processes to know if they are inside our VM. +- `E2B_SANDBOX_ID` to know the ID of the sandbox. +- `E2B_TEAM_ID` to know the team ID that created the sandbox. +- `E2B_TEMPLATE_ID` to know what template was used for the current sandbox. + +You can try it out by running the following code in the sandbox: + + +```js JavaScript & TypeScript +const sandbox = await Sandbox.create() +const result = await sandbox.commands.run('echo $E2B_SANDBOX_ID') +``` +```python Python +sandbox = Sandbox.create() +result = sandbox.commands.run("echo $E2B_SANDBOX_ID") +``` + + + +These default environment variables are only accessible via the SDK, when using the CLI you can find them in the form of dot files in the `/run/e2b/` dir: +```sh +user@e2b:~$ ls -a /run/e2b/ +.E2B_SANDBOX .E2B_SANDBOX_ID .E2B_TEAM_ID .E2B_TEMPLATE_ID +``` + + +--- + +## Setting environment variables +There are 3 ways to set environment variables in a sandbox: +1. [Global environment variables when creating the sandbox](/sandbox/environment-variables#1-global-environment-variables-when-creating-the-sandbox). +2. [When running code in the sandbox](/sandbox/environment-variables#2-setting-environment-variables-when-running-code). +3. [When running commands in the sandbox](/sandbox/environment-variables#3-setting-environment-variables-when-running-commands). + +### 1. Global environment variables +You can set global environment variables when creating a sandbox. + + +```js JavaScript & TypeScript highlight={4-6} +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create({ + envs: { + MY_VAR: 'my_value', + }, +}) +``` +```python Python highlight={4-6} +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create( + envs={ + 'MY_VAR': 'my_value', + }, +) +``` + + +### 2. Setting environment variables when running code +You can set environment variables for specific code execution call in the sandbox. + + +- These environment variables are scoped to the command but are not private in the OS. +- If you had a global environment variable with the same name, it will be overridden only for the command. + + + +```js JavaScript & TypeScript highlight={3-5} +const sandbox = await Sandbox.create() +const result = await sandbox.runCode('import os; print(os.environ.get("MY_VAR"))', { + envs: { + MY_VAR: 'my_value', + }, +}) +``` +```python Python highlight={4-6} +sandbox = Sandbox.create() +result = sandbox.run_code( + 'import os; print(os.environ.get("MY_VAR"))', + envs={ + 'MY_VAR': 'my_value' + } +) +``` + + +### 3. Setting environment variables when running commands +You can set environment variables for specific command execution in the sandbox. + + +- These environment variables are scoped to the command but are not private in the OS. +- If you had a global environment variable with the same name, it will be overridden only for the command. + + + +```js JavaScript & TypeScript highlight={3-5} +const sandbox = await Sandbox.create() +sandbox.commands.run('echo $MY_VAR', { + envs: { + MY_VAR: '123', + }, +}) +``` +```python Python highlight={4-6} +sandbox = Sandbox.create() +sandbox.commands.run( + 'echo $MY_VAR', + envs={ + 'MY_VAR': '123' + } +) +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox/index.mdx new file mode 100644 index 0000000000..5b25f8a3ac --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox/index.mdx @@ -0,0 +1,132 @@ +--- +title: "Sandbox lifecycle" +sidebarTitle: Lifecycle +--- + +When you start the sandbox, it stays alive for 5 minutes by default but you can change it by passing the `timeout` parameter. +After the time passes, the sandbox will be automatically shutdown. + +```js JavaScript & TypeScript highlight={6} +import { Sandbox } from '@e2b/code-interpreter' + +// Create sandbox with and keep it running for 60 seconds. +// 🚨 Note: The units are milliseconds. +const sandbox = await Sandbox.create({ + timeoutMs: 60_000, +}) +``` +```python Python highlight={6} +from e2b_code_interpreter import Sandbox + +# Create sandbox with and keep it running for 60 seconds. +# 🚨 Note: The units are seconds. +sandbox = Sandbox.create( + timeout=60, +) +``` + + + +## Change sandbox timeout during runtime + +You can change the sandbox timeout when it's running by calling the the `setTimeout` method in JavaScript or `set_timeout` method in Python. + +When you call the set timeout method, the sandbox timeout will be reset to the new value that you specified. + +This can be useful if you want to extend the sandbox lifetime when it's already running. +You can for example start with a sandbox with 1 minute timeout and then periodically call set timout every time user interacts with it in your app. + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +// Create sandbox with and keep it running for 60 seconds. +const sandbox = await Sandbox.create({ timeoutMs: 60_000 }) + +// Change the sandbox timeout to 30 seconds. +// 🚨 The new timeout will be 30 seconds from now. +await sandbox.setTimeout(30_000) +``` +```python Python +from e2b_code_interpreter import Sandbox + +# Create sandbox with and keep it running for 60 seconds. +sandbox = Sandbox.create(timeout=60) + +# Change the sandbox timeout to 30 seconds. +# 🚨 The new timeout will be 30 seconds from now. +sandbox.set_timeout(30) +``` + + +## Retrieve sandbox information + +You can retrieve sandbox information like sandbox ID, template, metadata, started at/end at date by calling the `getInfo` method in JavaScript or `get_info` method in Python. + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +// Create sandbox with and keep it running for 60 seconds. +const sandbox = await Sandbox.create({ timeoutMs: 60_000 }) + +// Retrieve sandbox information. +const info = await sandbox.getInfo() + +console.log(info) + +// { +// "sandboxId": "iiny0783cype8gmoawzmx-ce30bc46", +// "templateId": "rki5dems9wqfm4r03t7g", +// "name": "base", +// "metadata": {}, +// "startedAt": "2025-03-24T15:37:58.076Z", +// "endAt": "2025-03-24T15:42:58.076Z" +// } +``` + +```python Python +from e2b_code_interpreter import Sandbox + +# Create sandbox with and keep it running for 60 seconds. +sandbox = Sandbox.create(timeout=60) + +# Retrieve sandbox information. +info = sandbox.get_info() + +print(info) + +# SandboxInfo(sandbox_id='ig6f1yt6idvxkxl562scj-419ff533', +# template_id='u7nqkmpn3jjf1tvftlsu', +# name='base', +# metadata={}, +# started_at=datetime.datetime(2025, 3, 24, 15, 42, 59, 255612, tzinfo=tzutc()), +# end_at=datetime.datetime(2025, 3, 24, 15, 47, 59, 255612, tzinfo=tzutc()) +# ) +``` + + +## Shutdown sandbox + +You can shutdown the sandbox any time even before the timeout is up by calling the `kill` method. + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +// Create sandbox with and keep it running for 60 seconds. +const sandbox = await Sandbox.create({ timeoutMs: 60_000 }) + +// Shutdown the sandbox immediately. +await sandbox.kill() +``` +```python Python +from e2b_code_interpreter import Sandbox + +# Create sandbox with and keep it running for 60 seconds. +sandbox = Sandbox.create(timeout=60) + +# Shutdown the sandbox immediately. +sandbox.kill() +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox/internet-access/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox/internet-access/index.mdx new file mode 100644 index 0000000000..d9ebaddd10 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox/internet-access/index.mdx @@ -0,0 +1,160 @@ +--- +title: "Internet access" +--- + +Every sandbox has access to the internet and can be reached by a public URL. + +## Controlling internet access + +You can control whether a sandbox has access to the internet by using the `allowInternetAccess` parameter when creating a sandbox. By default, internet access is enabled (`true`), but you can disable it for security-sensitive workloads. + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +// Create sandbox with internet access enabled (default) +const sandbox = await Sandbox.create({ allowInternetAccess: true }) + +// Create sandbox without internet access +const isolatedSandbox = await Sandbox.create({ allowInternetAccess: false }) +``` +```python Python +from e2b_code_interpreter import Sandbox + +# Create sandbox with internet access enabled (default) +sandbox = Sandbox.create(allow_internet_access=True) + +# Create sandbox without internet access +isolated_sandbox = Sandbox.create(allow_internet_access=False) +``` + + +When internet access is disabled, the sandbox cannot make outbound network connections, which provides an additional layer of security for sensitive code execution. + +## Sandbox public URL +Every sandbox has a public URL that can be used to access running services inside the sandbox. + + +```js JavaScript & TypeScript highlight={6} +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() + +// You need to always pass a port number to get the host +const host = sandbox.getHost(3000) +console.log(`https://${host}`) +``` +```python Python highlight={6} +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() + +# You need to always pass a port number to get the host +host = sandbox.get_host(3000) +print(f'https://{host}') +``` + + +The code above will print something like this: + + +```bash JavaScript & TypeScript +https://3000-i62mff4ahtrdfdkyn2esc-b0b684e9.e2b.dev +``` +```bash Python +https://3000-i62mff4ahtrdfdkyn2esc-b0b684e9.e2b.dev +``` + + +The first leftmost part of the host is the port number we passed to the method. + +## Connecting to a server running inside the sandbox +You can start a server inside the sandbox and connect to it using the approach above. + +In this example we will start a simple HTTP server that listens on port 3000 and responds with the content of the directory where the server is started. + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() + +// Start a simple HTTP server inside the sandbox. +const process = await sandbox.commands.run('python -m http.server 3000', { background: true }) +const host = sandbox.getHost(3000) +const url = `https://${host}` +console.log('Server started at:', url) + +// Fetch data from the server inside the sandbox. +const response = await fetch(url); +const data = await response.text(); +console.log('Response from server inside sandbox:', data); + +// Kill the server process inside the sandbox. +await process.kill() +``` +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() + +# Start a simple HTTP server inside the sandbox. +process = sandbox.commands.run("python -m http.server 3000", background=True) +host = sandbox.get_host(3000) +url = f"https://{host}" +print('Server started at:', url) + +# Fetch data from the server inside the sandbox. +response = sandbox.commands.run(f"curl {url}") +data = response.stdout +print("Response from server inside sandbox:", data) + +# Kill the server process inside the sandbox. +process.kill() +``` + + + +This output will look like this: + +```bash JavaScript & TypeScript +Server started at: https://3000-ip3nfrvajtqu5ktoxugc7-b0b684e9.e2b.dev +Response from server inside sandbox: + + + +Directory listing for / + + +

Directory listing for /

+
+ +
+ + +``` +```bash Python +Server started at: https://3000-ip3nfrvajtqu5ktoxugc7-b0b684e9.e2b.dev +Response from server inside sandbox: + + + +Directory listing for / + + +

Directory listing for /

+
+ +
+ + +``` +
diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox/lifecycle-events-api/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox/lifecycle-events-api/index.mdx new file mode 100644 index 0000000000..d9166e7518 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox/lifecycle-events-api/index.mdx @@ -0,0 +1,151 @@ +--- +title: "Monitor sandbox lifecycle Events" +sidebarTitle: Lifecycle events API +--- + +The lifecycle API provides RESTful endpoints to request the latest sandbox lifecycle events. This allows you to track when sandboxes are created, paused, resumed, updated, or killed, along with metadata. +All requests require authentication using your team [API key](/api-key#where-to-find-api-key). + +Query Parameters: +- `offset` (optional): Number of events to skip (default: 0, min: 0) +- `limit` (optional): Number of events to return (default: 10, min: 1, max: 100) +- `orderAsc` (optional): Sort order - true for ascending, false for descending (default: false) + + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = await Sandbox.create() + +// Get the latest events for a specific sandbox +const resp1 = await fetch( + `https://api.e2b.app/events/sandboxes/${sbx.id}`, + { + method: 'GET', + headers: { + 'X-API-Key': E2B_API_KEY, + }, + } +) +const sandboxEvents = await resp1.json() + +// Get the latest 10 events for all sandboxes associated with the team +const resp2 = await fetch( + 'https://api.e2b.app/events/sandboxes?limit=10', + { + method: 'GET', + headers: { + 'X-API-Key': E2B_API_KEY, + }, + } +) +const teamSandboxEvents = await resp2.json() + +console.log(teamSandboxEvents) + +// [ +// { +// "eventCategory": "lifecycle", +// "eventData": null, +// "eventLabel": "kill", +// "sandboxBuildId": "a979a14b-bdcc-49e6-bc04-1189fc9fe7c2", +// "sandboxExecutionId": "1dae9e1c-9957-4ce7-a236-a99d5779aadf", +// "sandboxId": "${SANDBOX_ID}", +// "sandboxTeamId": "460355b3-4f64-48f9-9a16-4442817f79f5", +// "sandboxTemplateId": "rki5dems9wqfm4r03t7g", +// "timestamp": "2025-08-06T20:59:36Z" +// }, +// { +// "eventCategory": "lifecycle", +// "eventData": { +// "set_timeout": "2025-08-06T20:59:59Z" +// }, +// "eventLabel": "update", +// "sandboxBuildId": "a979a14b-bdcc-49e6-bc04-1189fc9fe7c2", +// "sandboxExecutionId": "1dae9e1c-9957-4ce7-a236-a99d5779aadf", +// "sandboxId": "${SANDBOX_ID}", +// "sandboxTeamId": "460355b3-4f64-48f9-9a16-4442817f79f5", +// "sandboxTemplateId": "rki5dems9wqfm4r03t7g", +// "timestamp": "2025-08-06T20:59:29Z" +// }, +// [...] +// { +// "eventCategory": "lifecycle", +// "eventData": null, +// "eventLabel": "create", +// "sandboxBuildId": "a979a14b-bdcc-49e6-bc04-1189fc9fe7c2", +// "sandboxExecutionId": "1dae9e1c-9957-4ce7-a236-a99d5779aadf", +// "sandboxId": "${SANDBOX_ID}", +// "sandboxTeamId": "460355b3-4f64-48f9-9a16-4442817f79f5", +// "sandboxTemplateId": "rki5dems9wqfm4r03t7g", +// "timestamp": "2025-08-06T20:59:24Z" +// } +// ] +``` +```python Python +import requests +from e2b_code_interpreter import Sandbox + +sbx = Sandbox() + +# Get the latest events for a specific sandbox +resp1 = requests.get( + f"https://api.e2b.app/events/sandboxes/{sbx.sandbox_id}", + headers={ + "X-API-Key": E2B_API_KEY, + } +) +sandbox_events = resp1.json() + +# Get the latest 10 events for all sandboxes associated with the team +resp2 = requests.get( + "https://api.e2b.app/events/sandboxes?limit=10", + headers={ + "X-API-Key": E2B_API_KEY, + } +) +team_sandbox_events = resp2.json() + +print(team_sandbox_events) + +# [ +# { +# "eventCategory": "lifecycle", +# "eventData": null, +# "eventLabel": "kill", +# "sandboxBuildId": "a979a14b-bdcc-49e6-bc04-1189fc9fe7c2", +# "sandboxExecutionId": "1dae9e1c-9957-4ce7-a236-a99d5779aadf", +# "sandboxId": "${SANDBOX_ID}", +# "sandboxTeamId": "460355b3-4f64-48f9-9a16-4442817f79f5", +# "sandboxTemplateId": "rki5dems9wqfm4r03t7g", +# "timestamp": "2025-08-06T20:59:36Z" +# }, +# { +# "eventCategory": "lifecycle", +# "eventData": { +# "set_timeout": "2025-08-06T20:59:59Z" +# }, +# "eventLabel": "update", +# "sandboxBuildId": "a979a14b-bdcc-49e6-bc04-1189fc9fe7c2", +# "sandboxExecutionId": "1dae9e1c-9957-4ce7-a236-a99d5779aadf", +# "sandboxId": "${SANDBOX_ID}", +# "sandboxTeamId": "460355b3-4f64-48f9-9a16-4442817f79f5", +# "sandboxTemplateId": "rki5dems9wqfm4r03t7g", +# "timestamp": "2025-08-06T20:59:29Z" +# }, +# [...] +# { +# "eventCategory": "lifecycle", +# "eventData": null, +# "eventLabel": "create", +# "sandboxBuildId": "a979a14b-bdcc-49e6-bc04-1189fc9fe7c2", +# "sandboxExecutionId": "1dae9e1c-9957-4ce7-a236-a99d5779aadf", +# "sandboxId": "${SANDBOX_ID}", +# "sandboxTeamId": "460355b3-4f64-48f9-9a16-4442817f79f5", +# "sandboxTemplateId": "rki5dems9wqfm4r03t7g", +# "timestamp": "2025-08-06T20:59:24Z" +# } +# ] +``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox/lifecycle-events-webhooks/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox/lifecycle-events-webhooks/index.mdx new file mode 100644 index 0000000000..bf6aa23c9d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox/lifecycle-events-webhooks/index.mdx @@ -0,0 +1,270 @@ +--- +title: "Sandbox lifecycle webhooks" +sidebarTitle: Lifecycle events webhooks +--- + +Webhooks provide a way for notifications to be delivered to an external web server whenever certain sandbox lifecycle events occur. +This allows you to receive real-time updates about sandbox creation, updates, and termination without having to poll the API. +All webhook requests require authentication using your team [API key](/api-key#where-to-find-api-key). + +## Webhook management + +### Register webhook + +Register a new webhook to receive sandbox lifecycle events. +The webhook will be registered for the team ID associated with your API key. You will receive webhook notifications for sandbox lifecycle events from sandboxes created by your team with the [following payload](#webhook-payload). + + + +```js JavaScript & TypeScript +// Register a new webhook +const resp = await fetch( + 'https://api.e2b.app/events/webhooks/sandboxes', + { + method: 'POST', + headers: { + 'X-API-Key': E2B_API_KEY, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + url: 'https://your-webhook-endpoint.com/webhook', + events: ['create', 'kill', 'update'] + }), + } +) + +if (resp.status === 201) { + console.log('Webhook registered successfully') +} +``` +```python Python +import requests + +# Register a new webhook +resp = requests.post( + "https://api.e2b.app/events/webhooks/sandboxes", + headers={ + "X-API-Key": E2B_API_KEY, + "Content-Type": "application/json", + }, + json={ + "url": "https://your-webhook-endpoint.com/webhook", + "events": ["create", "kill", "update"] + } +) + +if resp.status_code == 201: + print("Webhook registered successfully") +``` + + + +### Get webhook configuration + +Retrieve the current webhook configuration for your team. + + +```js JavaScript & TypeScript +// Get current webhook configuration +const resp = await fetch( + 'https://api.e2b.app/events/webhooks/sandboxes', + { + method: 'GET', + headers: { + 'X-API-Key': E2B_API_KEY, + }, + } +) +const webhookConfig = await resp.json() +console.log(webhookConfig) +// { +// "teamID": "", +// "url": "https://your-webhook-endpoint.com/webhook", +// "events": ["create", "kill"] +// } + +``` +```python Python +import requests + +# Get current webhook configuration +resp = requests.get( + "https://api.e2b.app/events/webhooks/sandboxes", + headers={ + "X-API-Key": E2B_API_KEY, + } +) + +webhook_config = resp.json() +print(webhook_config) +# { +# "teamID": "", +# "events": ["create", "kill"] +# "url": "https://your-webhook-endpoint.com/webhook", +# } +``` + + +### Update webhook configuration + +Update an existing webhook configuration. The update will replace the previous configuration fields with provided fields. + + +```js JavaScript & TypeScript +// Update webhook configuration +const resp = await fetch( + 'https://api.e2b.app/events/webhooks/sandboxes', + { + method: 'PATCH', + headers: { + 'X-API-Key': E2B_API_KEY, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + url: 'https://your-updated-webhook-endpoint.com/webhook', + events: ['create'] + }), + } +) + +const updatedWebhookConfig = await resp.json() +console.log(updatedWebhookConfig) +// { +// "teamID": "", +// "events": ["create"], +// "url": "https://your-updated-webhook-endpoint.com/webhook" +// } +``` +```python Python +import requests + +# Update webhook configuration +resp = requests.patch( + "https://api.e2b.app/events/webhooks/sandboxes", + headers={ + "X-API-Key": E2B_API_KEY, + "Content-Type": "application/json", + }, + json={ + "url": "https://your-updated-webhook-endpoint.com/webhook", + "events": ["create"] + } +) + +updated_webhook_config = resp.json() +print(updated_webhook_config) +# { +# "teamID": "", +# "events": ["create"], +# "url": "https://your-updated-webhook-endpoint.com/webhook" +# } +``` + + +### Delete webhook + +Unregister the webhook. + + +```js JavaScript & TypeScript +// Delete webhook configuration +const resp = await fetch( + 'https://api.e2b.app/events/webhooks/sandboxes', + { + method: 'DELETE', + headers: { + 'X-API-Key': E2B_API_KEY, + }, + } +) + +if (resp.status === 200) { + console.log('Webhook deleted successfully') +} +``` +```python Python +import requests + +# Delete webhook configuration +resp = requests.delete( + "https://api.e2b.app/events/webhooks/sandboxes", + headers={ + "X-API-Key": E2B_API_KEY, + } +) + +if resp.status_code == 200: + print("Webhook deleted successfully") +``` + + +### Test webhook + +Send a test webhook to verify your endpoint is working correctly. + + +```js JavaScript & TypeScript +// Test webhook endpoint +const resp = await fetch( + 'https://api.e2b.app/events/webhooks/sandboxes/test', + { + method: 'POST', + headers: { + 'X-API-Key': E2B_API_KEY, + }, + } +) + +if (resp.status === 200) { + console.log('Test webhook sent successfully') +} +``` +```python Python +import requests + +# Test webhook endpoint +resp = requests.post( + "https://api.e2b.app/events/webhooks/sandboxes/test", + headers={ + "X-API-Key": E2B_API_KEY, + } +) + +if resp.status_code == 200: + print("Test webhook sent successfully") +``` + + +## Webhook payload + +When a webhook is triggered, your endpoint will receive a POST request with a JSON payload containing the sandbox event data. The payload structure matches the event format from the API: + +```json +{ + "eventCategory": "lifecycle", + "eventData": { + "sandbox_metadata": { + "": "" + } + }, + "eventLabel": "create", + "sandboxBuildId": "a979a14b-bdcc-49e6-bc04-1189fc9fe7c2", + "sandboxExecutionId": "1dae9a1c-9957-4ce7-a236-a99d5779aadf", + "sandboxId": "", + "sandboxTeamId": "", + "sandboxTemplateId": "rki5dems9wqfm4r03t7g", + "timestamp": "2025-08-06T20:59:24Z" +} +``` + +## Available event types + +The following event types can be subscribed to via webhooks, they are used as the `eventLabel` field in the [payload](#webhook-payload). + +- `create` - Sandbox creation +- `kill` - Sandbox termination +- `update` - Sandbox configuration updates +- `pause` - Sandbox pausing +- `resume` - Sandbox resuming + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox/list/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox/list/index.mdx new file mode 100644 index 0000000000..aa49e531a1 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox/list/index.mdx @@ -0,0 +1,339 @@ +--- +title: "List sandboxes" +--- + +You can list sandboxes using the `Sandbox.list()` method. + + + Once you have information about running sandbox, you can [connect](/sandbox/connect) to it using the `Sandbox.connect()` method. + + +### Listing sandboxes + +The `Sandbox.list()` method supports pagination. In the [advanced pagination](/sandbox/list#advanced-pagination) section, you can find more information about pagination techniques using the updated method. + + + ```js JavaScript & TypeScript highlight={6,11,14,24} + import { Sandbox, SandboxInfo } from '@e2b/code-interpreter' + + const sandbox = await Sandbox.create( + { + metadata: { + name: 'My Sandbox', + }, + }, + ) + + const paginator = Sandbox.list() + + // Get the first page of sandboxes (running and paused) + const firstPage = await paginator.nextItems() + + const runningSandbox = firstPage[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) + + // Get the next page of sandboxes + const nextPage = await paginator.nextItems() + ``` + ```python Python highlight={5,9,12,22} + from e2b_code_interpreter import Sandbox, SandboxInfo + + sandbox = Sandbox.create( + metadata={ + "name": "My Sandbox", + }, + ) + + paginator = Sandbox.list() + + # Get the first page of sandboxes (running and paused) + firstPage = paginator.next_items() + + running_sandbox = firstPage[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) + + # Get the next page of sandboxes + nextPage = paginator.next_items() + ``` + +The code above will output something like this: + + ```bash JavaScript & TypeScript + 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 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 + ``` + + + +### Filtering sandboxes + +Filter sandboxes by their current state. The state parameter can contain either "**running**" for running sandboxes or "**paused**" for paused sandboxes, or both. + + + ```js JavaScript & TypeScript highlight={9,13} + import { Sandbox } from '@e2b/code-interpreter' + + // Create a sandbox. + const sandbox = await Sandbox.create() + + // List sandboxes that are running or paused. + const paginator = Sandbox.list({ + query: { + state: ['running', 'paused'], + }, + }) + + const sandboxes = await paginator.nextItems() + ``` + ```python Python highlight={9,14} + from e2b_code_interpreter import Sandbox, SandboxQuery, SandboxState + + # Create a sandbox with metadata. + sandbox = Sandbox.create() + + # List sandboxes that are running or paused. + paginator = Sandbox.list( + query=SandboxQuery( + state=[SandboxState.RUNNING, SandboxState.PAUSED], + ), + ) + + # Get the first page of sandboxes (running and paused) + sandboxes = paginator.next_items() + ``` + + +Filter sandboxes by the metadata key value pairs specified during Sandbox creation. + + + ```js JavaScript & TypeScript highlight={6-8,15,18} + import { Sandbox } from '@e2b/code-interpreter' + + // Create sandbox with metadata. + const sandbox = await Sandbox.create({ + metadata: { + env: 'dev', + app: 'my-app', + userId: '123', + }, + }) + + // 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' }, + }, + }) + + const sandboxes = await paginator.nextItems() + ``` + ```python Python highlight={6-8,16-17} + from e2b_code_interpreter import Sandbox, SandboxQuery, SandboxState + + # Create sandbox with metadata. + sandbox = Sandbox.create( + metadata={ + "env": "dev", + "app": "my-app", + "user_id": "123", + }, + ) + + # List running sandboxes that has `userId` key with value `123` and `env` key with value `dev`. + paginator = Sandbox.list( + query=SandboxQuery( + metadata={ + "userId": "123", + "env": "dev", + } + ), + ) + + # Get the first page of sandboxes (running and paused) + sandboxes = paginator.next_items() + ``` + + +### Advanced pagination + +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. + + + ```js JavaScript & TypeScript highlight={4-5,16} + import { Sandbox } from '@e2b/code-interpreter' + + const paginator = Sandbox.list({ + limit: 100, + nextToken: '', + }) + + // Additional paginator properties + // Whether there is a next page + paginator.hasNext + + // Next page token + paginator.nextToken + + // Fetch the next page + await paginator.nextItems() + ``` + ```python Python highlight={5-6,13} + from e2b_code_interpreter import Sandbox + + # List running sandboxes that has `userId` key with value `123` and `env` key with value `dev`. + paginator = Sandbox.list( + limit=100, + next_token="", + ) + + paginator.has_next # Whether there is a next page + paginator.next_token # Next page token + + # Fetch the next page + paginator.next_items() + ``` + + +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: + + + ```js JavaScript & TypeScript highlight={7} + import { Sandbox } from '@e2b/code-interpreter' + + const paginator = Sandbox.list() + + // Loop through all pages + const sandboxes: SandboxInfo[] = [] + while (paginator.hasNext) { + const items = await paginator.nextItems() + sandboxes.push(...items) + } + ``` + ```python Python highlight={7} + from e2b_code_interpreter import Sandbox, SandboxQuery + + paginator = Sandbox.list() + + # Loop through all pages + sandboxes: list[SandboxInfo] = [] + while paginator.has_next: + items = paginator.next_items() + sandboxes.extend(items) + ``` + + +## Old SDK (v1.x.y) + + + If you're using SDK with version lower than `2.0.0`, the `Sandbox.list()` method behaves differently. + + + + + ```js JavaScript & TypeScript highlight={11} + 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() + 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 Python highlight={11} + from e2b_code_interpreter import Sandbox + + # Create a sandbox. + sandbox = Sandbox.create( + metadata: { + name: 'My Sandbox', + }, + ) + + # List all running sandboxes. + running_sandboxes = Sandbox.list() + 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) + ``` + + +## Filtering sandboxes + +You can filter sandboxes by specifying [Metadata](/sandbox/metadata) 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. + + + ```js JavaScript & TypeScript highlight={6-8,15} + import { Sandbox } from '@e2b/code-interpreter' + + // Create sandbox with metadata. + const sandbox = await Sandbox.create({ + metadata: { + env: 'dev', + app: 'my-app', + userId: '123', + }, + }) + + // 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' }, + }, + }) + ``` + ```python Python highlight={7-9,17-18} + from e2b_code_interpreter import Sandbox + from e2b.sandbox.sandbox_api import SandboxQuery + + # Create sandbox with metadata. + sandbox = Sandbox.create( + metadata={ + "env": "dev", + "app": "my-app", + "user_id": "123", + }, + ) + + # 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", + "env": "dev", + } + ), + ) + ``` + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox/metadata/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox/metadata/index.mdx new file mode 100644 index 0000000000..b45f88cbb3 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox/metadata/index.mdx @@ -0,0 +1,59 @@ +--- +title: "Sandbox metadata" +sidebarTitle: Metadata +--- + +Metadata is a way to attach arbitrary key-value pairs for a sandbox. + +This is useful in various scenarios, for example: +- Associate a sandbox with a user session. +- Store custom user data for a sandbox like API keys. +- Associate a sandbox with a user ID and [connect to it later](/sandbox/connect). + +You specify metadata when creating a sandbox and can access it later through listing running sandboxes with `Sandbox.list()` method. + + +If you're using the [beta version of the SDK](/sandbox/installing-beta-sdks), the `Sandbox.list()` method was updated. See [List Sandboxes](/sandbox/list#changes-in-the-beta-sdks) for more information. + + + +```js JavaScript & TypeScript highlight={6} +import { Sandbox } from '@e2b/code-interpreter' + +// Create sandbox with metadata. +const sandbox = await Sandbox.create({ + metadata: { + userId: '123', + }, +}) + +// List running sandboxes and access metadata. +const runningSandboxes = await Sandbox.list() +// Will print: +// { +// 'userId': '123', +// } +console.log(runningSandboxes[0].metadata) +``` +```python Python highlight={6} +from e2b_code_interpreter import Sandbox + +# Create sandbox with metadata. +sandbox = Sandbox.create( + metadata={ + 'userId': '123', + }, +) + +# List running sandboxes and access metadata. +running_sandboxes = Sandbox.list() +# Will print: +# { +# 'userId': '123', +# } +print(running_sandboxes[0].metadata) +``` + + +## Filtering sandboxes by metadata +You can also filter sandboxes by metadata, you can find more about it [here](/sandbox/list#filtering-sandboxes). \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox/metrics/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox/metrics/index.mdx new file mode 100644 index 0000000000..99769f479a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox/metrics/index.mdx @@ -0,0 +1,110 @@ +--- +title: "Sandbox metrics" +sidebarTitle: Metrics +--- + +The sandbox metrics allows you to get information about the sandbox's CPU, memory and disk usage. + +## Getting sandbox metrics +Getting the metrics of a sandbox returns an array of timestamped metrics containing CPU, memory and disk usage information. +The metrics are collected every 5 seconds. + +### Getting sandbox metrics using the SDKs + + +```js JavaScript & TypeScript highlight={9} +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = await Sandbox.create() +console.log('Sandbox created', sbx.sandboxId) + +// Wait for a few seconds to collect some metrics +await new Promise((resolve) => setTimeout(resolve, 10_000)) + +const metrics = await sbx.getMetrics() + +// You can also get the metrics by sandbox ID: +// const metrics = await Sandbox.getMetrics(sbx.sandboxId) + +console.log('Sandbox metrics:', metrics) + +// Sandbox metrics: +// [ +// { +// timestamp: 2025-07-28T08:04:05.000Z, +// cpuUsedPct: 20.33, +// cpuCount: 2, +// memUsed: 32681984, // in bytes +// memTotal: 507592704, // in bytes +// diskUsed: 1514856448, // in bytes +// diskTotal: 2573185024 // in bytes +// }, +// { +// timestamp: 2025-07-28T08:04:10.000Z, +// cpuUsedPct: 0.2, +// cpuCount: 2, +// memUsed: 33316864, // in bytes +// memTotal: 507592704, // in bytes +// diskUsed: 1514856448, // in bytes +// diskTotal: 2573185024 // in bytes +// } +// ] +``` +```python Python highlight={10} +from time import sleep +from e2b_code_interpreter import Sandbox + +sbx = Sandbox.create() +print('Sandbox created', sbx.sandbox_id) + +# Wait for a few seconds to collect some metrics +sleep(10) + +metrics = sbx.get_metrics() + +# You can also get the metrics by sandbox ID: +# metrics = Sandbox.get_metrics(sbx.sandbox_id) + +print('Sandbox metrics', metrics) + +# Sandbox metrics +# [ +# SandboxMetric( +# cpu_count=2, +# cpu_used_pct=13.97, +# disk_total=2573185024, # in bytes +# disk_used=1514856448, # in bytes +# mem_total=507592704, # in bytes +# mem_used=30588928, # in bytes +# timestamp=datetime.datetime(2025, 7, 28, 8, 8, 15, tzinfo=tzutc()), +# ), +# SandboxMetric( +# cpu_count=2, +# cpu_used_pct=0.1, +# disk_total=2573185024, # in bytes +# disk_used=1514856448, # in bytes +# mem_total=507592704, # in bytes +# mem_used=31084544, # in bytes +# timestamp=datetime.datetime(2025, 7, 28, 8, 8, 20, tzinfo=tzutc()), +# ), +# ] +``` + + +### Getting sandbox metrics using the CLI + +```bash Terminal highlight={1} +e2b sandbox metrics + +# Metrics for sandbox +# +# [2025-07-25 14:05:55Z] CPU: 8.27% / 2 Cores | Memory: 31 / 484 MiB | Disk: 1445 / 2453 MiB +# [2025-07-25 14:06:00Z] CPU: 0.5% / 2 Cores | Memory: 32 / 484 MiB | Disk: 1445 / 2453 MiB +# [2025-07-25 14:06:05Z] CPU: 0.1% / 2 Cores | Memory: 32 / 484 MiB | Disk: 1445 / 2453 MiB +# [2025-07-25 14:06:10Z] CPU: 0.3% / 2 Cores | Memory: 32 / 484 MiB | Disk: 1445 / 2453 MiB +``` + + + + It may take a second or more to get the first metrics after the sandbox is created. Until the first metrics are collected from the sandbox, you will get an empty array. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox/persistence/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox/persistence/index.mdx new file mode 100644 index 0000000000..86254c7cc2 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox/persistence/index.mdx @@ -0,0 +1,277 @@ +--- +title: "Sandbox persistence" +sidebarTitle: Persistence +--- + + +Sandbox persistence is currently in public beta: +1. Consider [some limitations](#limitations-while-in-beta). +2. The persistence is free for all users during the beta. + + +The sandbox persistence allows you to pause your sandbox and resume it later from the same state it was in when you paused it. + +This includes not only state of the sandbox's filesystem but also the sandbox's memory. This means all running processes, loaded variables, data, etc. + +## Sandbox State Transitions + +Understanding how sandboxes transition between different states is crucial for managing their lifecycle effectively. Here's a diagram showing the possible state transitions: + + + + + +### State descriptions + +- **Running**: The sandbox is actively running and can execute code. This is the initial state after creation. +- **Paused**: The sandbox execution is suspended but its state is preserved. +- **Killed**: The sandbox is terminated and all resources are released. This is a terminal state. + +### Changing sandbox's state + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() // Starts in Running state + +// Pause the sandbox +await sandbox.betaPause() // Running → Paused + +// Resume the sandbox +await sandbox.connect() // Running/Paused → Running + +// Kill the sandbox (from any state) +await sandbox.kill() // Running/Paused → Killed +``` + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() # Starts in Running state + +# Pause the sandbox +sandbox.betaPause() # Running → Paused + +# Resume the sandbox +sandbox.connect() # Running/Paused → Running + +# Kill the sandbox (from any state) +sandbox.kill() # Running/Paused → Killed +``` + + +## Pausing sandbox +When you pause a sandbox, both the sandbox's filesystem and memory state will be saved. This includes all the files in the sandbox's filesystem and all the running processes, loaded variables, data, etc. + + +```js JavaScript & TypeScript highlight={8-9} +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = await Sandbox.create() +console.log('Sandbox created', sbx.sandboxId) + +// Pause the sandbox +// You can save the sandbox ID in your database to resume the sandbox later +await sbx.betaPause() +console.log('Sandbox paused', sbx.sandboxId) +``` +```python Python highlight={8-9} +from e2b_code_interpreter import 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 +sbx.beta_pause() +print('Sandbox paused', sbx.sandbox_id) +``` + + + +## Resuming sandbox +When you resume a sandbox, it will be in the same state it was in when you paused it. +This means that all the files in the sandbox's filesystem will be restored and all the running processes, loaded variables, data, etc. will be restored. + + +```js JavaScript & TypeScript highlight={12-13} +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = await Sandbox.create() +console.log('Sandbox created', sbx.sandboxId) + +// Pause the sandbox +// You can save the sandbox ID in your database to resume the sandbox later +await sbx.betaPause() +console.log('Sandbox paused', sbx.sandboxId) + +// Connect to the sandbox (it will automatically resume the sandbox, if paused) +const sameSbx = await sbx.connect() +console.log('Connected to the sandbox', sameSbx.sandboxId) +``` +```python Python highlight={12-13} +from e2b_code_interpreter import 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 +sbx.beta_pause() +print('Sandbox paused', sandbox_id) + +# Connect to the sandbox (it will automatically resume the sandbox, if paused) +same_sbx = sbx.connect() +print('Connected to the sandbox', same_sbx.sandbox_id) +``` + + +## Listing paused sandboxes +You can list all paused sandboxes by calling the `Sandbox.list` method and supplying the `state` query parameter. +More information about using the method can be found in [List Sandboxes](/sandbox/list). + + +```js JavaScript & TypeScript highlight={4,7} +import { Sandbox, SandboxInfo } from '@e2b/code-interpreter' + +// List all paused sandboxes +const paginator = Sandbox.list({ query: { state: ['paused'] } }) + +// Get the first page of paused sandboxes +const sandboxes = await paginator.nextItems() + +// Get all paused sandboxes +while (paginator.hasNext) { + const items = await paginator.nextItems() + sandboxes.push(...items) +} +``` +```python Python highlight={4,7} +# List all paused sandboxes +from e2b_code_interpreter import Sandbox, SandboxQuery, SandboxState + +paginator = Sandbox.list(SandboxQuery(state=[SandboxState.PAUSED])) + +# Get the first page of paused sandboxes +sandboxes = paginator.next_items() + +# Get all paused sandboxes +while paginator.has_next: + items = paginator.next_items() + sandboxes.extend(items) +``` + + +## Removing paused sandboxes + +You can remove paused sandboxes by calling the `kill` method on the Sandbox instance. + + +```js JavaScript & TypeScript highlight={11,14} +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = await Sandbox.create() +console.log('Sandbox created', sbx.sandboxId) + +// Pause the sandbox +// You can save the sandbox ID in your database to resume the sandbox later +await sbx.betaPause() + +// Remove the sandbox +await sbx.kill() + +// Remove sandbox by id +await Sandbox.kill(sbx.sandboxId) +``` +```python Python highlight={9,12} +from e2b_code_interpreter import Sandbox + +sbx = Sandbox.create() + +# Pause the sandbox +sbx.beta_pause() + +# Remove the sandbox +sbx.kill() + +# Remove sandbox by id +Sandbox.kill(sbx.sandbox_id) +``` + + +## Sandbox's timeout +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.connect()`/`Sandbox.connect()` method like this: + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +const sbx = await Sandbox.connect(sandboxId, { timeoutMs: 60 * 1000 }) // 60 seconds +``` +```python Python +from e2b_code_interpreter import Sandbox + +sbx = Sandbox.connect(sandbox_id, timeout=60) # 60 seconds +``` + + + +### Auto-pause (beta) + +**Note: Auto-pause is currently in beta and available through `Sandbox.betaCreate()`/`Sandbox.beta_create()` method.** + +Sandboxes can now automatically pause after they time out. When a sandbox is paused, it stops consuming compute but preserves its state. The default inactivity timeout is 10 minutes. You can change the timeout by passing the `timeoutMs`/`timeout` parameter to the `Sandbox.connect()`/`Sandbox.connect()` method. + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +// Create sandbox with auto-pause enabled +const sandbox = await Sandbox.betaCreate({ + autoPause: true, + timeoutMs: 10 * 60 * 1000 // Optional: change the default timeout (10 minutes) +}) +```python Python +from e2b_code_interpreter import Sandbox +# Create sandbox with auto-pause enabled (Beta) +sandbox = Sandbox.beta_create( + auto_pause=True # Auto-pause after the sandbox times out + timeout=10 * 60, # Optional: change the default timeout (10 minutes) +) + + +The auto-pause is persistent, meaning that if your sandbox resumes and it times out, it will be automatically paused again. + +If you `.kill()` the sandbox, it will be permanently deleted and you won't be able to resume it. + + +```js JavaScript & TypeScript +import { Sandbox } from '@e2b/code-interpreter' + +// Create sandbox with auto-pause enabled (Beta) +const sandbox = await Sandbox.betaCreate({ + autoPause: true // Auto-pause after the sandbox times out +}) +``` +```python Python +from e2b_code_interpreter import Sandbox +# Create sandbox with auto-pause enabled (Beta) +sandbox = Sandbox.beta_create( + auto_pause=True # Auto-pause after the sandbox times out +) +``` + + +## Network +If you have a service (for example a server) running inside your sandbox and you pause the sandbox, the service won't be accessible from the outside and all the clients will be disconnected. +If you resume the sandbox, the service will be accessible again but you need to connect clients again. + + +## Limitations while in beta +- Pausing a sandbox takes about 4 seconds per 1 GiB of RAM +- Resuming a sandbox takes about 1 second +- Sandbox can be used up to 30 days + - After 30 days from the sandbox creation, the sandbox data may be deleted. This retention period is based on the original sandbox creation date and is not extended or reset by subsequent resumes. Attempting to resume a sandbox that was deleted or does not exist will result in a `NotFoundError` (JavaScript SDK) or `NotFoundException` (Python SDK). \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/sandbox/rate-limits/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sandbox/rate-limits/index.mdx new file mode 100644 index 0000000000..2f975eb177 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sandbox/rate-limits/index.mdx @@ -0,0 +1,128 @@ +--- +title: "Rate Limits" +sidebarTitle: "Rate limits" +--- + +This page describes API and sandbox rate limits of the E2B platform. + +## Table of Contents + +- [Sandbox lifecycle & management API](##sandbox-lifecycle-%26-management-api) +- [Sandbox operations & requests to sandboxes](#sandbox-operations-%26-requests-to-sandboxes) +- [Concurrent Sandboxes](#concurrent-sandboxes) +- [Sandbox creation rate](#sandbox-creation-rate) +- [Reaching limits](#reaching-limits) +- [Increasing and avoiding rate limits](#increasing-and-avoiding-rate-limits) + +Here's a limits breakdown table based on the plan: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PlanHobbyProEnterprise
Sandbox lifecycle & management API20,000 / 30s20,000 / 30sCustom
Sandbox operations40,000 / 60s per IP40,000 / 60s per IPCustom
Concurrent sandboxes20100 - 1,100*Custom
Sandbox creation rate1 / sec5 / secCustom
+ + + * Pro plan default is 100 concurrent sandboxes. Higher concurrency up to 1,100 is available as a separate addon that can be purchased. + + +--- + +## Sandbox lifecycle & management API + +**20,000 requests per 30 seconds** + +This rate limit applies to lifecycle and management operations such as sandbox create, kill, update, list, and other. + +--- + +## Sandbox operations & requests to sandboxes + +**40,000 requests per 60 seconds** + +This rate limits applies to operations to/within running sandboxes such as running code, listing files, running commands, etc. +This also includes requests made to custom ports in the sandbox. + +
This limit is enforced globally across all sandbox operations from a single IP address. + +--- + +## Concurrent sandboxes + +Number of concurrent sandboxes differs based on the pricing tier. + +### Hobby tier +**Up to 20 concurrent sandboxes** + +### Pro tier +**Starts at 100 concurrent sandboxes** + + +Can go up to 1,100 with a separate addon available for purchase. + + + +### Enterprise tier +**Custom limit - 1,100+ concurrent sandboxes** + +--- + +## Sandbox creation rate + +This limit controls how quickly you can create new sandboxes. + +### Hobby tier +**1 sandbox per second** + + +### Pro tier +**5 sandboxes per second** + +### Enterprise tier +**Custom limit - 5+ sandboxes per second** + +## Reaching limits + +When you reach the limits of your plan, subsequent requests/function calls will be effectively dropped and return the following: +- the `429 Too Many Requests` HTTP status code (when calling API/sandbox ports directly) +- `RateLimitError` in the JS/TS SDK +- `RateLimitException` in the Python SDK + +For 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.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 limits + +You can avoid rate limits by either increasing your plan or contacting our sales team to discuss your specific requirements and we can provide tailored limits to meet your needs at [enterprise@e2b.dev](mailto:enterprise@e2b.dev). diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.0/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.0/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.0/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.0/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.0/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.0/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.0/template/index.mdx new file mode 100644 index 0000000000..1a03bda563 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.0/template/index.mdx @@ -0,0 +1,94 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.1/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.1/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.1/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.1/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.1/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.1/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.1/template/index.mdx new file mode 100644 index 0000000000..1a03bda563 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.1/template/index.mdx @@ -0,0 +1,94 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.10/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.10/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.10/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.10/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.10/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.10/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.10/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.10/template/index.mdx new file mode 100644 index 0000000000..b121c54831 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.10/template/index.mdx @@ -0,0 +1,136 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.2/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.2/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.2/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.2/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.2/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.2/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.2/template/index.mdx new file mode 100644 index 0000000000..1a03bda563 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.2/template/index.mdx @@ -0,0 +1,94 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.3/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.3/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.3/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.3/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.3/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.3/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.3/template/index.mdx new file mode 100644 index 0000000000..1a03bda563 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.3/template/index.mdx @@ -0,0 +1,94 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.4/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.4/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.4/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.4/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.4/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.4/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.4/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.4/template/index.mdx new file mode 100644 index 0000000000..1a03bda563 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.4/template/index.mdx @@ -0,0 +1,94 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.5/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.5/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.5/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.5/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.5/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.5/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.5/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.5/template/index.mdx new file mode 100644 index 0000000000..1a03bda563 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.5/template/index.mdx @@ -0,0 +1,94 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.6/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.6/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.6/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.6/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.6/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.6/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.6/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.6/template/index.mdx new file mode 100644 index 0000000000..1a03bda563 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.6/template/index.mdx @@ -0,0 +1,94 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.7/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.7/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.7/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.7/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.7/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.7/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.7/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.7/template/index.mdx new file mode 100644 index 0000000000..b121c54831 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.7/template/index.mdx @@ -0,0 +1,136 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.8/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.8/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.8/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.8/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.8/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.8/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.8/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.8/template/index.mdx new file mode 100644 index 0000000000..b121c54831 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.8/template/index.mdx @@ -0,0 +1,136 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.9/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.9/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.9/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.9/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.9/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.9/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.9/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.9/template/index.mdx new file mode 100644 index 0000000000..b121c54831 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.0.9/template/index.mdx @@ -0,0 +1,136 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.0/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.0/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.0/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.0/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.0/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.0/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.0/template/index.mdx new file mode 100644 index 0000000000..b121c54831 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.0/template/index.mdx @@ -0,0 +1,136 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.1/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.1/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.1/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.1/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.1/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.1/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.1/template/index.mdx new file mode 100644 index 0000000000..b121c54831 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.1/template/index.mdx @@ -0,0 +1,136 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.2/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.2/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.2/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.2/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.2/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.2/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.2/template/index.mdx new file mode 100644 index 0000000000..b121c54831 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.2/template/index.mdx @@ -0,0 +1,136 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.3/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.3/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.3/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.3/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.3/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.3/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.3/template/index.mdx new file mode 100644 index 0000000000..b121c54831 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.2.3/template/index.mdx @@ -0,0 +1,136 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.0/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.0/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.0/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.0/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.0/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.0/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.0/template/index.mdx new file mode 100644 index 0000000000..b121c54831 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.0/template/index.mdx @@ -0,0 +1,136 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.1/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.1/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.1/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.1/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.1/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.1/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.1/template/index.mdx new file mode 100644 index 0000000000..b121c54831 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.1/template/index.mdx @@ -0,0 +1,136 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.2/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.2/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.2/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.2/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.2/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.2/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.2/template/index.mdx new file mode 100644 index 0000000000..b121c54831 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.2/template/index.mdx @@ -0,0 +1,136 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.3/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.3/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.3/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.3/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.3/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.3/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.3/template/index.mdx new file mode 100644 index 0000000000..b121c54831 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.3/template/index.mdx @@ -0,0 +1,136 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.4/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.4/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.4/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.4/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.4/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.4/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.4/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.4/template/index.mdx new file mode 100644 index 0000000000..b121c54831 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.3.4/template/index.mdx @@ -0,0 +1,136 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.0/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.0/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.0/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.0/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.0/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.0/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.0/template/index.mdx new file mode 100644 index 0000000000..b121c54831 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.0/template/index.mdx @@ -0,0 +1,136 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.1/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.1/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.1/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.1/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.1/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.1/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.1/template/index.mdx new file mode 100644 index 0000000000..e0965e3323 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.1/template/index.mdx @@ -0,0 +1,137 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.2/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.2/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.2/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.2/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.2/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.2/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.2/template/index.mdx new file mode 100644 index 0000000000..e0965e3323 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.2/template/index.mdx @@ -0,0 +1,137 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.3/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.3/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.3/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.3/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.3/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.3/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.3/template/index.mdx new file mode 100644 index 0000000000..e0965e3323 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.4.3/template/index.mdx @@ -0,0 +1,137 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.0/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.0/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.0/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.0/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.0/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.0/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.0/template/index.mdx new file mode 100644 index 0000000000..c70cf83fdc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.0/template/index.mdx @@ -0,0 +1,138 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.1/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.1/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.1/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.1/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.1/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.1/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.1/template/index.mdx new file mode 100644 index 0000000000..c70cf83fdc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.1/template/index.mdx @@ -0,0 +1,138 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.2/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.2/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.2/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.2/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.2/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.2/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.2/template/index.mdx new file mode 100644 index 0000000000..c70cf83fdc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.5.2/template/index.mdx @@ -0,0 +1,138 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.6.0/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.6.0/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.6.0/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.6.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.6.0/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.6.0/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.6.0/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.6.0/template/index.mdx new file mode 100644 index 0000000000..c70cf83fdc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.6.0/template/index.mdx @@ -0,0 +1,138 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.7.0/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.7.0/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.7.0/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.7.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.7.0/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.7.0/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.7.0/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.7.0/template/index.mdx new file mode 100644 index 0000000000..c70cf83fdc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.7.0/template/index.mdx @@ -0,0 +1,138 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.8.0/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.8.0/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.8.0/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.8.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.8.0/sandbox/index.mdx new file mode 100644 index 0000000000..ec8e950a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.8.0/sandbox/index.mdx @@ -0,0 +1,93 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.8.0/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.8.0/template/index.mdx new file mode 100644 index 0000000000..c70cf83fdc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.8.0/template/index.mdx @@ -0,0 +1,138 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.0/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.0/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.0/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.0/sandbox/index.mdx new file mode 100644 index 0000000000..a30f5ce054 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.0/sandbox/index.mdx @@ -0,0 +1,111 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + +## e2b sandbox metrics + + +show metrics for sandbox + +##### Usage + +```bash +e2b sandbox metrics [options] +``` + +##### Options + + + - `-f, --follow: keep streaming metrics until the sandbox is closed ` + - `--format : specify format for printing metrics (json, pretty) [default: pretty]` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.0/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.0/template/index.mdx new file mode 100644 index 0000000000..c70cf83fdc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.0/template/index.mdx @@ -0,0 +1,138 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.1/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.1/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.1/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.1/sandbox/index.mdx new file mode 100644 index 0000000000..a30f5ce054 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.1/sandbox/index.mdx @@ -0,0 +1,111 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + +## e2b sandbox metrics + + +show metrics for sandbox + +##### Usage + +```bash +e2b sandbox metrics [options] +``` + +##### Options + + + - `-f, --follow: keep streaming metrics until the sandbox is closed ` + - `--format : specify format for printing metrics (json, pretty) [default: pretty]` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.1/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.1/template/index.mdx new file mode 100644 index 0000000000..c70cf83fdc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.1/template/index.mdx @@ -0,0 +1,138 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.2/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.2/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.2/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.2/sandbox/index.mdx new file mode 100644 index 0000000000..a30f5ce054 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.2/sandbox/index.mdx @@ -0,0 +1,111 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all running sandboxes + +##### Usage + +```bash +e2b sandbox list [options] +``` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + +## e2b sandbox metrics + + +show metrics for sandbox + +##### Usage + +```bash +e2b sandbox metrics [options] +``` + +##### Options + + + - `-f, --follow: keep streaming metrics until the sandbox is closed ` + - `--format : specify format for printing metrics (json, pretty) [default: pretty]` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.2/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.2/template/index.mdx new file mode 100644 index 0000000000..c70cf83fdc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v1.9.2/template/index.mdx @@ -0,0 +1,138 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.0/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.0/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.0/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.0/sandbox/index.mdx new file mode 100644 index 0000000000..08c2d5a844 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.0/sandbox/index.mdx @@ -0,0 +1,118 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all sandboxes, by default it list only running ones + +##### Usage + +```bash +e2b sandbox list [options] +``` + +##### Options + + + - `-s, --state : filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : filter by metadata, eg. key1=value1 ` + - `-l, --limit : limit the number of sandboxes returned ` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox create + + +create sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox create [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + +## e2b sandbox metrics + + +show metrics for sandbox + +##### Usage + +```bash +e2b sandbox metrics [options] +``` + +##### Options + + + - `-f, --follow: keep streaming metrics until the sandbox is closed ` + - `--format : specify format for printing metrics (json, pretty) [default: pretty]` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.0/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.0/template/index.mdx new file mode 100644 index 0000000000..c70cf83fdc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.0/template/index.mdx @@ -0,0 +1,138 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.1/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.1/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.1/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.1/sandbox/index.mdx new file mode 100644 index 0000000000..08c2d5a844 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.1/sandbox/index.mdx @@ -0,0 +1,118 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all sandboxes, by default it list only running ones + +##### Usage + +```bash +e2b sandbox list [options] +``` + +##### Options + + + - `-s, --state : filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : filter by metadata, eg. key1=value1 ` + - `-l, --limit : limit the number of sandboxes returned ` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox create + + +create sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox create [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + +## e2b sandbox metrics + + +show metrics for sandbox + +##### Usage + +```bash +e2b sandbox metrics [options] +``` + +##### Options + + + - `-f, --follow: keep streaming metrics until the sandbox is closed ` + - `--format : specify format for printing metrics (json, pretty) [default: pretty]` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.1/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.1/template/index.mdx new file mode 100644 index 0000000000..c70cf83fdc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.1/template/index.mdx @@ -0,0 +1,138 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.2/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.2/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.2/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.2/sandbox/index.mdx new file mode 100644 index 0000000000..9c83f6ac37 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.2/sandbox/index.mdx @@ -0,0 +1,136 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all sandboxes, by default it list only running ones + +##### Usage + +```bash +e2b sandbox list [options] +``` + +##### Options + + + - `-s, --state : filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : filter by metadata, eg. key1=value1 ` + - `-l, --limit : limit the number of sandboxes returned ` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox create + + +create sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox create [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox spawn + + +create sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + +## e2b sandbox metrics + + +show metrics for sandbox + +##### Usage + +```bash +e2b sandbox metrics [options] +``` + +##### Options + + + - `-f, --follow: keep streaming metrics until the sandbox is closed ` + - `--format : specify format for printing metrics (json, pretty) [default: pretty]` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.2/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.2/template/index.mdx new file mode 100644 index 0000000000..c70cf83fdc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.2/template/index.mdx @@ -0,0 +1,138 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.3/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.3/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.3/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.3/sandbox/index.mdx new file mode 100644 index 0000000000..9c83f6ac37 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.3/sandbox/index.mdx @@ -0,0 +1,136 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all sandboxes, by default it list only running ones + +##### Usage + +```bash +e2b sandbox list [options] +``` + +##### Options + + + - `-s, --state : filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : filter by metadata, eg. key1=value1 ` + - `-l, --limit : limit the number of sandboxes returned ` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +##### Options + + + - `-a, --all: kill all running sandboxes ` + + +## e2b sandbox create + + +create sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox create [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox spawn + + +create sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + +## e2b sandbox metrics + + +show metrics for sandbox + +##### Usage + +```bash +e2b sandbox metrics [options] +``` + +##### Options + + + - `-f, --follow: keep streaming metrics until the sandbox is closed ` + - `--format : specify format for printing metrics (json, pretty) [default: pretty]` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.3/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.3/template/index.mdx new file mode 100644 index 0000000000..c70cf83fdc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.0.3/template/index.mdx @@ -0,0 +1,138 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.1.0/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.1.0/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.1.0/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.1.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.1.0/sandbox/index.mdx new file mode 100644 index 0000000000..a23bf130ce --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.1.0/sandbox/index.mdx @@ -0,0 +1,139 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all sandboxes, by default it list only running ones + +##### Usage + +```bash +e2b sandbox list [options] +``` + +##### Options + + + - `-s, --state : filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : filter by metadata, eg. key1=value1 ` + - `-l, --limit : limit the number of sandboxes returned ` + - `-f, --format : output format, eg. json, table ` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxIDs...] +``` + +##### Options + + + - `-a, --all: kill all sandboxes ` + - `-s, --state : when used with -a/--all flag, filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : when used with -a/--all flag, filter by metadata, eg. key1=value1 ` + + +## e2b sandbox create + + +create sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox create [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox spawn + + +create sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + +## e2b sandbox metrics + + +show metrics for sandbox + +##### Usage + +```bash +e2b sandbox metrics [options] +``` + +##### Options + + + - `-f, --follow: keep streaming metrics until the sandbox is closed ` + - `--format : specify format for printing metrics (json, pretty) [default: pretty]` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.1.0/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.1.0/template/index.mdx new file mode 100644 index 0000000000..84e1f54a46 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.1.0/template/index.mdx @@ -0,0 +1,139 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-f, --format : output format, eg. json, table ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.2.0/auth/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.2.0/auth/index.mdx new file mode 100644 index 0000000000..3062eb5af8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.2.0/auth/index.mdx @@ -0,0 +1,62 @@ +--- +title: Auth +--- + +## e2b auth + + +authentication commands + +##### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +##### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +##### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +##### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +##### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.2.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.2.0/sandbox/index.mdx new file mode 100644 index 0000000000..f36af22ab7 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.2.0/sandbox/index.mdx @@ -0,0 +1,139 @@ +--- +title: Sandbox +--- + +## e2b sandbox + + +work with sandboxes + +##### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +##### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all sandboxes, by default it list only running ones + +##### Usage + +```bash +e2b sandbox list [options] +``` + +##### Options + + + - `-s, --state : filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : filter by metadata, eg. key1=value1 ` + - `-l, --limit : limit the number of sandboxes returned ` + - `-f, --format : output format, eg. json, pretty ` + + +## e2b sandbox kill + + +kill sandbox + +##### Usage + +```bash +e2b sandbox kill [options] [sandboxIDs...] +``` + +##### Options + + + - `-a, --all: kill all sandboxes ` + - `-s, --state : when used with -a/--all flag, filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : when used with -a/--all flag, filter by metadata, eg. key1=value1 ` + + +## e2b sandbox create + + +create sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox create [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox spawn + + +create sandbox and connect terminal to it + +##### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +##### Usage + +```bash +e2b sandbox logs [options] +``` + +##### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + +## e2b sandbox metrics + + +show metrics for sandbox + +##### Usage + +```bash +e2b sandbox metrics [options] +``` + +##### Options + + + - `-f, --follow: keep streaming metrics until the sandbox is closed ` + - `--format : specify format for printing metrics (json, pretty) [default: pretty]` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.2.0/template/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.2.0/template/index.mdx new file mode 100644 index 0000000000..61a4dc7981 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/cli/v2.2.0/template/index.mdx @@ -0,0 +1,139 @@ +--- +title: Template +--- + +## e2b template + + +manage sandbox templates + +##### Usage + +```bash +e2b template [options] [command] +``` +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +##### Usage + +```bash +e2b template build [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +##### Usage + +```bash +e2b template list [options] +``` + +##### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-f, --format : output format, eg. json, pretty ` + + +## e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +##### Usage + +```bash +e2b template init [options] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +##### Usage + +```bash +e2b template delete [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +##### Usage + +```bash +e2b template publish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +##### Usage + +```bash +e2b template unpublish [options] [template] +``` + +##### Options + + + - `-p, --path : change root directory where command is executed to directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/charts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/charts/index.mdx new file mode 100644 index 0000000000..8959d67836 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/charts/index.mdx @@ -0,0 +1,244 @@ +--- +title: Charts +--- + +### ChartType + +Chart types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `BAR` | `"bar"` | +| `BOX_AND_WHISKER` | `"box_and_whisker"` | +| `LINE` | `"line"` | +| `PIE` | `"pie"` | +| `SCATTER` | `"scatter"` | +| `SUPERCHART` | `"superchart"` | +| `UNKNOWN` | `"unknown"` | + +*** + +### ScaleType + +Ax scale types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `ASINH` | `"asinh"` | +| `CATEGORICAL` | `"categorical"` | +| `DATETIME` | `"datetime"` | +| `FUNCTION` | `"function"` | +| `FUNCTIONLOG` | `"functionlog"` | +| `LINEAR` | `"linear"` | +| `LOG` | `"log"` | +| `LOGIT` | `"logit"` | +| `SYMLOG` | `"symlog"` | + +## Type Aliases + +### BarChart + +```ts +type BarChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BarData`[] | +| `type` | `ChartType.BAR` | + +*** + +### BarData + +```ts +type BarData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `group` | `string` | +| `label` | `string` | +| `value` | `string` | + +*** + +### BoxAndWhiskerChart + +```ts +type BoxAndWhiskerChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BoxAndWhiskerData`[] | +| `type` | `ChartType.BOX_AND_WHISKER` | + +*** + +### BoxAndWhiskerData + +```ts +type BoxAndWhiskerData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `first_quartile` | `number` | +| `label` | `string` | +| `max` | `number` | +| `median` | `number` | +| `min` | `number` | +| `outliers` | `number`[] | +| `third_quartile` | `number` | + +*** + +### Chart + +```ts +type Chart: object; +``` + +Represents a chart. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `any`[] | +| `title` | `string` | +| `type` | `ChartType` | + +*** + +### ChartTypes + +```ts +type ChartTypes: + | LineChart + | ScatterChart + | BarChart + | PieChart + | BoxAndWhiskerChart + | SuperChart; +``` + +*** + +### LineChart + +```ts +type LineChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.LINE` | + +*** + +### PieChart + +```ts +type PieChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `PieData`[] | +| `type` | `ChartType.PIE` | + +*** + +### PieData + +```ts +type PieData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `angle` | `number` | +| `label` | `string` | +| `radius` | `number` | + +*** + +### PointData + +```ts +type PointData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `label` | `string` | +| `points` | [`number` \| `string`, `number` \| `string`][] | + +*** + +### ScatterChart + +```ts +type ScatterChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.SCATTER` | + +*** + +### SuperChart + +```ts +type SuperChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `Chart`[] | +| `type` | `ChartType.SUPERCHART` | + +## Functions + +### deserializeChart() + +```ts +function deserializeChart(data: any): Chart +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `any` | + +#### Returns + +`Chart` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/consts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/consts/index.mdx new file mode 100644 index 0000000000..71f5db34eb --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/consts/index.mdx @@ -0,0 +1,17 @@ +--- +title: Consts +--- + +### DEFAULT\_TIMEOUT\_MS + +```ts +const DEFAULT_TIMEOUT_MS: 60000 = 60_000; +``` + +*** + +### JUPYTER\_PORT + +```ts +const JUPYTER_PORT: 49999 = 49999; +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/index/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/index/index.mdx new file mode 100644 index 0000000000..cb35ea04d7 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/index/index.mdx @@ -0,0 +1,107 @@ +--- +title: Index +--- + +### BarChart + +Re-exports BarChart + +### BarData + +Re-exports BarData + +### BoxAndWhiskerChart + +Re-exports BoxAndWhiskerChart + +### BoxAndWhiskerData + +Re-exports BoxAndWhiskerData + +### Chart + +Re-exports Chart + +### ChartType + +Re-exports ChartType + +### ChartTypes + +Re-exports ChartTypes + +### Context + +Re-exports Context + +### CreateCodeContextOpts + +Re-exports CreateCodeContextOpts + +### default + +Renames and re-exports Sandbox + +### Execution + +Re-exports Execution + +### ExecutionError + +Re-exports ExecutionError + +### LineChart + +Re-exports LineChart + +### Logs + +Re-exports Logs + +### MIMEType + +Re-exports MIMEType + +### OutputMessage + +Re-exports OutputMessage + +### PieChart + +Re-exports PieChart + +### PieData + +Re-exports PieData + +### PointData + +Re-exports PointData + +### RawData + +Re-exports RawData + +### Result + +Re-exports Result + +### RunCodeOpts + +Re-exports RunCodeOpts + +### Sandbox + +Re-exports Sandbox + +### ScaleType + +Re-exports ScaleType + +### ScatterChart + +Re-exports ScatterChart + +### SuperChart + +Re-exports SuperChart diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/messaging/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/messaging/index.mdx new file mode 100644 index 0000000000..f43428a047 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/messaging/index.mdx @@ -0,0 +1,330 @@ +--- +title: Messaging +--- + +### Execution + +Represents the result of a cell execution. + +#### Constructors + +```ts +new Execution( + results: Result[], + logs: Logs, + error?: ExecutionError, + executionCount?: number): Execution +``` + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | +| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | +| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount`? | `number` | `undefined` | Execution count of the cell. | + +###### Returns + +`Execution` + +#### Properties + +| Property | Modifier | Type | Default value | Description | +| ------ | ------ | ------ | ------ | ------ | +| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | +| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | +| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | + +#### Accessors + +### text + +```ts +get text(): undefined | string +``` + +Returns the text representation of the main result of the cell. + +###### Returns + +`undefined` \| `string` + +#### Methods + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the execution result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `error` | `undefined` \| `ExecutionError` | +| `logs` | `Logs` | +| `results` | `Result`[] | + +*** + +### ExecutionError + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + +#### Constructors + +```ts +new ExecutionError( + name: string, + value: string, + traceback: string): ExecutionError +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Name of the error. | +| `value` | `string` | Value of the error. | +| `traceback` | `string` | The raw traceback of the error. | + +###### Returns + +`ExecutionError` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `name` | `public` | `string` | Name of the error. | +| `traceback` | `public` | `string` | The raw traceback of the error. | +| `value` | `public` | `string` | Value of the error. | + +*** + +### OutputMessage + +Represents an output message from the sandbox code execution. + +#### Constructors + +```ts +new OutputMessage( + line: string, + timestamp: number, + error: boolean): OutputMessage +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `line` | `string` | The output line. | +| `timestamp` | `number` | Unix epoch in nanoseconds. | +| `error` | `boolean` | Whether the output is an error. | + +###### Returns + +`OutputMessage` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `error` | `readonly` | `boolean` | Whether the output is an error. | +| `line` | `readonly` | `string` | The output line. | +| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### Result + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + +#### Constructors + +```ts +new Result(rawData: RawData, isMainResult: boolean): Result +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `rawData` | `RawData` | +| `isMainResult` | `boolean` | + +###### Returns + +`Result` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | +| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | +| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | +| `html?` | `readonly` | `string` | HTML representation of the data. | +| `isMainResult` | `readonly` | `boolean` | - | +| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | +| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | +| `json?` | `readonly` | `string` | JSON representation of the data. | +| `latex?` | `readonly` | `string` | LaTeX representation of the data. | +| `markdown?` | `readonly` | `string` | Markdown representation of the data. | +| `pdf?` | `readonly` | `string` | PDF representation of the data. | +| `png?` | `readonly` | `string` | PNG representation of the data. | +| `raw` | `readonly` | `RawData` | - | +| `svg?` | `readonly` | `string` | SVG representation of the data. | +| `text?` | `readonly` | `string` | Text representation of the result. | + +#### Methods + +### formats() + +```ts +formats(): string[] +``` + +Returns all the formats available for the result. + +###### Returns + +`string`[] + +Array of strings representing the formats available for the result. + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `extra`? | `any` | +| `html` | `undefined` \| `string` | +| `javascript` | `undefined` \| `string` | +| `jpeg` | `undefined` \| `string` | +| `json` | `undefined` \| `string` | +| `latex` | `undefined` \| `string` | +| `markdown` | `undefined` \| `string` | +| `pdf` | `undefined` \| `string` | +| `png` | `undefined` \| `string` | +| `svg` | `undefined` \| `string` | +| `text` | `undefined` \| `string` | + +## Type Aliases + +### Logs + +```ts +type Logs: object; +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | +| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | + +*** + +### MIMEType + +```ts +type MIMEType: string; +``` + +Represents a MIME type. + +*** + +### RawData + +```ts +type RawData: object & E2BData; +``` + +Dictionary that maps MIME types to their corresponding representations of the data. + +## Functions + +### extractError() + +```ts +function extractError(res: Response): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `res` | `Response` | + +#### Returns + +`Promise`\<`undefined` \| `SandboxError`\> + +*** + +### parseOutput() + +```ts +function parseOutput( + execution: Execution, + line: string, + onStdout?: (output: OutputMessage) => any, + onStderr?: (output: OutputMessage) => any, + onResult?: (data: Result) => any, +onError?: (error: ExecutionError) => any): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `execution` | `Execution` | +| `line` | `string` | +| `onStdout`? | (`output`: `OutputMessage`) => `any` | +| `onStderr`? | (`output`: `OutputMessage`) => `any` | +| `onResult`? | (`data`: `Result`) => `any` | +| `onError`? | (`error`: `ExecutionError`) => `any` | + +#### Returns + +`Promise`\<`void`\> diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/sandbox/index.mdx new file mode 100644 index 0000000000..8bee4e3d24 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.0.4/sandbox/index.mdx @@ -0,0 +1,316 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +``` + +#### Methods + +### createCodeContext() + +```ts +createCodeContext(opts?: CreateCodeContextOpts): Promise +``` + +Creates a new context to run code in. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CreateCodeContextOpts` | options for creating the context. | + +###### Returns + +`Promise`\<`Context`\> + +context object. + +### runCode() + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object + +## Interfaces + +### CreateCodeContextOpts + +Options for creating a code context. + +#### Properties + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the context. + +###### Default + +```ts +/home/user +``` + +### language? + +```ts +optional language: string; +``` + +Language for the context. + +###### Default + +```ts +python +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### RunCodeOpts + +Options for running code. + +#### Properties + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for code execution. + +###### Default + +```ts +{} +``` + +### onError()? + +```ts +optional onError: (error: ExecutionError) => any; +``` + +Callback for handling the `ExecutionError` object. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `error` | `ExecutionError` | + +###### Returns + +`any` + +### onResult()? + +```ts +optional onResult: (data: Result) => any; +``` + +Callback for handling the final execution result. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `Result` | + +###### Returns + +`any` + +### onStderr()? + +```ts +optional onStderr: (output: OutputMessage) => any; +``` + +Callback for handling stderr messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### onStdout()? + +```ts +optional onStdout: (output: OutputMessage) => any; +``` + +Callback for handling stdout messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the code execution in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +## Type Aliases + +### Context + +```ts +type Context: object; +``` + +Represents a context for code execution. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `cwd` | `string` | The working directory of the context. | +| `id` | `string` | The ID of the context. | +| `language` | `string` | The language of the context. | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/charts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/charts/index.mdx new file mode 100644 index 0000000000..8959d67836 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/charts/index.mdx @@ -0,0 +1,244 @@ +--- +title: Charts +--- + +### ChartType + +Chart types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `BAR` | `"bar"` | +| `BOX_AND_WHISKER` | `"box_and_whisker"` | +| `LINE` | `"line"` | +| `PIE` | `"pie"` | +| `SCATTER` | `"scatter"` | +| `SUPERCHART` | `"superchart"` | +| `UNKNOWN` | `"unknown"` | + +*** + +### ScaleType + +Ax scale types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `ASINH` | `"asinh"` | +| `CATEGORICAL` | `"categorical"` | +| `DATETIME` | `"datetime"` | +| `FUNCTION` | `"function"` | +| `FUNCTIONLOG` | `"functionlog"` | +| `LINEAR` | `"linear"` | +| `LOG` | `"log"` | +| `LOGIT` | `"logit"` | +| `SYMLOG` | `"symlog"` | + +## Type Aliases + +### BarChart + +```ts +type BarChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BarData`[] | +| `type` | `ChartType.BAR` | + +*** + +### BarData + +```ts +type BarData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `group` | `string` | +| `label` | `string` | +| `value` | `string` | + +*** + +### BoxAndWhiskerChart + +```ts +type BoxAndWhiskerChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BoxAndWhiskerData`[] | +| `type` | `ChartType.BOX_AND_WHISKER` | + +*** + +### BoxAndWhiskerData + +```ts +type BoxAndWhiskerData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `first_quartile` | `number` | +| `label` | `string` | +| `max` | `number` | +| `median` | `number` | +| `min` | `number` | +| `outliers` | `number`[] | +| `third_quartile` | `number` | + +*** + +### Chart + +```ts +type Chart: object; +``` + +Represents a chart. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `any`[] | +| `title` | `string` | +| `type` | `ChartType` | + +*** + +### ChartTypes + +```ts +type ChartTypes: + | LineChart + | ScatterChart + | BarChart + | PieChart + | BoxAndWhiskerChart + | SuperChart; +``` + +*** + +### LineChart + +```ts +type LineChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.LINE` | + +*** + +### PieChart + +```ts +type PieChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `PieData`[] | +| `type` | `ChartType.PIE` | + +*** + +### PieData + +```ts +type PieData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `angle` | `number` | +| `label` | `string` | +| `radius` | `number` | + +*** + +### PointData + +```ts +type PointData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `label` | `string` | +| `points` | [`number` \| `string`, `number` \| `string`][] | + +*** + +### ScatterChart + +```ts +type ScatterChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.SCATTER` | + +*** + +### SuperChart + +```ts +type SuperChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `Chart`[] | +| `type` | `ChartType.SUPERCHART` | + +## Functions + +### deserializeChart() + +```ts +function deserializeChart(data: any): Chart +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `any` | + +#### Returns + +`Chart` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/consts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/consts/index.mdx new file mode 100644 index 0000000000..71f5db34eb --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/consts/index.mdx @@ -0,0 +1,17 @@ +--- +title: Consts +--- + +### DEFAULT\_TIMEOUT\_MS + +```ts +const DEFAULT_TIMEOUT_MS: 60000 = 60_000; +``` + +*** + +### JUPYTER\_PORT + +```ts +const JUPYTER_PORT: 49999 = 49999; +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/index/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/index/index.mdx new file mode 100644 index 0000000000..cb35ea04d7 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/index/index.mdx @@ -0,0 +1,107 @@ +--- +title: Index +--- + +### BarChart + +Re-exports BarChart + +### BarData + +Re-exports BarData + +### BoxAndWhiskerChart + +Re-exports BoxAndWhiskerChart + +### BoxAndWhiskerData + +Re-exports BoxAndWhiskerData + +### Chart + +Re-exports Chart + +### ChartType + +Re-exports ChartType + +### ChartTypes + +Re-exports ChartTypes + +### Context + +Re-exports Context + +### CreateCodeContextOpts + +Re-exports CreateCodeContextOpts + +### default + +Renames and re-exports Sandbox + +### Execution + +Re-exports Execution + +### ExecutionError + +Re-exports ExecutionError + +### LineChart + +Re-exports LineChart + +### Logs + +Re-exports Logs + +### MIMEType + +Re-exports MIMEType + +### OutputMessage + +Re-exports OutputMessage + +### PieChart + +Re-exports PieChart + +### PieData + +Re-exports PieData + +### PointData + +Re-exports PointData + +### RawData + +Re-exports RawData + +### Result + +Re-exports Result + +### RunCodeOpts + +Re-exports RunCodeOpts + +### Sandbox + +Re-exports Sandbox + +### ScaleType + +Re-exports ScaleType + +### ScatterChart + +Re-exports ScatterChart + +### SuperChart + +Re-exports SuperChart diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/messaging/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/messaging/index.mdx new file mode 100644 index 0000000000..f43428a047 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/messaging/index.mdx @@ -0,0 +1,330 @@ +--- +title: Messaging +--- + +### Execution + +Represents the result of a cell execution. + +#### Constructors + +```ts +new Execution( + results: Result[], + logs: Logs, + error?: ExecutionError, + executionCount?: number): Execution +``` + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | +| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | +| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount`? | `number` | `undefined` | Execution count of the cell. | + +###### Returns + +`Execution` + +#### Properties + +| Property | Modifier | Type | Default value | Description | +| ------ | ------ | ------ | ------ | ------ | +| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | +| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | +| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | + +#### Accessors + +### text + +```ts +get text(): undefined | string +``` + +Returns the text representation of the main result of the cell. + +###### Returns + +`undefined` \| `string` + +#### Methods + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the execution result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `error` | `undefined` \| `ExecutionError` | +| `logs` | `Logs` | +| `results` | `Result`[] | + +*** + +### ExecutionError + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + +#### Constructors + +```ts +new ExecutionError( + name: string, + value: string, + traceback: string): ExecutionError +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Name of the error. | +| `value` | `string` | Value of the error. | +| `traceback` | `string` | The raw traceback of the error. | + +###### Returns + +`ExecutionError` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `name` | `public` | `string` | Name of the error. | +| `traceback` | `public` | `string` | The raw traceback of the error. | +| `value` | `public` | `string` | Value of the error. | + +*** + +### OutputMessage + +Represents an output message from the sandbox code execution. + +#### Constructors + +```ts +new OutputMessage( + line: string, + timestamp: number, + error: boolean): OutputMessage +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `line` | `string` | The output line. | +| `timestamp` | `number` | Unix epoch in nanoseconds. | +| `error` | `boolean` | Whether the output is an error. | + +###### Returns + +`OutputMessage` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `error` | `readonly` | `boolean` | Whether the output is an error. | +| `line` | `readonly` | `string` | The output line. | +| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### Result + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + +#### Constructors + +```ts +new Result(rawData: RawData, isMainResult: boolean): Result +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `rawData` | `RawData` | +| `isMainResult` | `boolean` | + +###### Returns + +`Result` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | +| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | +| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | +| `html?` | `readonly` | `string` | HTML representation of the data. | +| `isMainResult` | `readonly` | `boolean` | - | +| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | +| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | +| `json?` | `readonly` | `string` | JSON representation of the data. | +| `latex?` | `readonly` | `string` | LaTeX representation of the data. | +| `markdown?` | `readonly` | `string` | Markdown representation of the data. | +| `pdf?` | `readonly` | `string` | PDF representation of the data. | +| `png?` | `readonly` | `string` | PNG representation of the data. | +| `raw` | `readonly` | `RawData` | - | +| `svg?` | `readonly` | `string` | SVG representation of the data. | +| `text?` | `readonly` | `string` | Text representation of the result. | + +#### Methods + +### formats() + +```ts +formats(): string[] +``` + +Returns all the formats available for the result. + +###### Returns + +`string`[] + +Array of strings representing the formats available for the result. + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `extra`? | `any` | +| `html` | `undefined` \| `string` | +| `javascript` | `undefined` \| `string` | +| `jpeg` | `undefined` \| `string` | +| `json` | `undefined` \| `string` | +| `latex` | `undefined` \| `string` | +| `markdown` | `undefined` \| `string` | +| `pdf` | `undefined` \| `string` | +| `png` | `undefined` \| `string` | +| `svg` | `undefined` \| `string` | +| `text` | `undefined` \| `string` | + +## Type Aliases + +### Logs + +```ts +type Logs: object; +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | +| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | + +*** + +### MIMEType + +```ts +type MIMEType: string; +``` + +Represents a MIME type. + +*** + +### RawData + +```ts +type RawData: object & E2BData; +``` + +Dictionary that maps MIME types to their corresponding representations of the data. + +## Functions + +### extractError() + +```ts +function extractError(res: Response): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `res` | `Response` | + +#### Returns + +`Promise`\<`undefined` \| `SandboxError`\> + +*** + +### parseOutput() + +```ts +function parseOutput( + execution: Execution, + line: string, + onStdout?: (output: OutputMessage) => any, + onStderr?: (output: OutputMessage) => any, + onResult?: (data: Result) => any, +onError?: (error: ExecutionError) => any): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `execution` | `Execution` | +| `line` | `string` | +| `onStdout`? | (`output`: `OutputMessage`) => `any` | +| `onStderr`? | (`output`: `OutputMessage`) => `any` | +| `onResult`? | (`data`: `Result`) => `any` | +| `onError`? | (`error`: `ExecutionError`) => `any` | + +#### Returns + +`Promise`\<`void`\> diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/sandbox/index.mdx new file mode 100644 index 0000000000..8bee4e3d24 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.0/sandbox/index.mdx @@ -0,0 +1,316 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +``` + +#### Methods + +### createCodeContext() + +```ts +createCodeContext(opts?: CreateCodeContextOpts): Promise +``` + +Creates a new context to run code in. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CreateCodeContextOpts` | options for creating the context. | + +###### Returns + +`Promise`\<`Context`\> + +context object. + +### runCode() + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object + +## Interfaces + +### CreateCodeContextOpts + +Options for creating a code context. + +#### Properties + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the context. + +###### Default + +```ts +/home/user +``` + +### language? + +```ts +optional language: string; +``` + +Language for the context. + +###### Default + +```ts +python +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### RunCodeOpts + +Options for running code. + +#### Properties + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for code execution. + +###### Default + +```ts +{} +``` + +### onError()? + +```ts +optional onError: (error: ExecutionError) => any; +``` + +Callback for handling the `ExecutionError` object. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `error` | `ExecutionError` | + +###### Returns + +`any` + +### onResult()? + +```ts +optional onResult: (data: Result) => any; +``` + +Callback for handling the final execution result. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `Result` | + +###### Returns + +`any` + +### onStderr()? + +```ts +optional onStderr: (output: OutputMessage) => any; +``` + +Callback for handling stderr messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### onStdout()? + +```ts +optional onStdout: (output: OutputMessage) => any; +``` + +Callback for handling stdout messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the code execution in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +## Type Aliases + +### Context + +```ts +type Context: object; +``` + +Represents a context for code execution. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `cwd` | `string` | The working directory of the context. | +| `id` | `string` | The ID of the context. | +| `language` | `string` | The language of the context. | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/charts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/charts/index.mdx new file mode 100644 index 0000000000..8959d67836 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/charts/index.mdx @@ -0,0 +1,244 @@ +--- +title: Charts +--- + +### ChartType + +Chart types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `BAR` | `"bar"` | +| `BOX_AND_WHISKER` | `"box_and_whisker"` | +| `LINE` | `"line"` | +| `PIE` | `"pie"` | +| `SCATTER` | `"scatter"` | +| `SUPERCHART` | `"superchart"` | +| `UNKNOWN` | `"unknown"` | + +*** + +### ScaleType + +Ax scale types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `ASINH` | `"asinh"` | +| `CATEGORICAL` | `"categorical"` | +| `DATETIME` | `"datetime"` | +| `FUNCTION` | `"function"` | +| `FUNCTIONLOG` | `"functionlog"` | +| `LINEAR` | `"linear"` | +| `LOG` | `"log"` | +| `LOGIT` | `"logit"` | +| `SYMLOG` | `"symlog"` | + +## Type Aliases + +### BarChart + +```ts +type BarChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BarData`[] | +| `type` | `ChartType.BAR` | + +*** + +### BarData + +```ts +type BarData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `group` | `string` | +| `label` | `string` | +| `value` | `string` | + +*** + +### BoxAndWhiskerChart + +```ts +type BoxAndWhiskerChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BoxAndWhiskerData`[] | +| `type` | `ChartType.BOX_AND_WHISKER` | + +*** + +### BoxAndWhiskerData + +```ts +type BoxAndWhiskerData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `first_quartile` | `number` | +| `label` | `string` | +| `max` | `number` | +| `median` | `number` | +| `min` | `number` | +| `outliers` | `number`[] | +| `third_quartile` | `number` | + +*** + +### Chart + +```ts +type Chart: object; +``` + +Represents a chart. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `any`[] | +| `title` | `string` | +| `type` | `ChartType` | + +*** + +### ChartTypes + +```ts +type ChartTypes: + | LineChart + | ScatterChart + | BarChart + | PieChart + | BoxAndWhiskerChart + | SuperChart; +``` + +*** + +### LineChart + +```ts +type LineChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.LINE` | + +*** + +### PieChart + +```ts +type PieChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `PieData`[] | +| `type` | `ChartType.PIE` | + +*** + +### PieData + +```ts +type PieData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `angle` | `number` | +| `label` | `string` | +| `radius` | `number` | + +*** + +### PointData + +```ts +type PointData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `label` | `string` | +| `points` | [`number` \| `string`, `number` \| `string`][] | + +*** + +### ScatterChart + +```ts +type ScatterChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.SCATTER` | + +*** + +### SuperChart + +```ts +type SuperChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `Chart`[] | +| `type` | `ChartType.SUPERCHART` | + +## Functions + +### deserializeChart() + +```ts +function deserializeChart(data: any): Chart +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `any` | + +#### Returns + +`Chart` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/consts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/consts/index.mdx new file mode 100644 index 0000000000..71f5db34eb --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/consts/index.mdx @@ -0,0 +1,17 @@ +--- +title: Consts +--- + +### DEFAULT\_TIMEOUT\_MS + +```ts +const DEFAULT_TIMEOUT_MS: 60000 = 60_000; +``` + +*** + +### JUPYTER\_PORT + +```ts +const JUPYTER_PORT: 49999 = 49999; +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/index/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/index/index.mdx new file mode 100644 index 0000000000..cb35ea04d7 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/index/index.mdx @@ -0,0 +1,107 @@ +--- +title: Index +--- + +### BarChart + +Re-exports BarChart + +### BarData + +Re-exports BarData + +### BoxAndWhiskerChart + +Re-exports BoxAndWhiskerChart + +### BoxAndWhiskerData + +Re-exports BoxAndWhiskerData + +### Chart + +Re-exports Chart + +### ChartType + +Re-exports ChartType + +### ChartTypes + +Re-exports ChartTypes + +### Context + +Re-exports Context + +### CreateCodeContextOpts + +Re-exports CreateCodeContextOpts + +### default + +Renames and re-exports Sandbox + +### Execution + +Re-exports Execution + +### ExecutionError + +Re-exports ExecutionError + +### LineChart + +Re-exports LineChart + +### Logs + +Re-exports Logs + +### MIMEType + +Re-exports MIMEType + +### OutputMessage + +Re-exports OutputMessage + +### PieChart + +Re-exports PieChart + +### PieData + +Re-exports PieData + +### PointData + +Re-exports PointData + +### RawData + +Re-exports RawData + +### Result + +Re-exports Result + +### RunCodeOpts + +Re-exports RunCodeOpts + +### Sandbox + +Re-exports Sandbox + +### ScaleType + +Re-exports ScaleType + +### ScatterChart + +Re-exports ScatterChart + +### SuperChart + +Re-exports SuperChart diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/messaging/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/messaging/index.mdx new file mode 100644 index 0000000000..f43428a047 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/messaging/index.mdx @@ -0,0 +1,330 @@ +--- +title: Messaging +--- + +### Execution + +Represents the result of a cell execution. + +#### Constructors + +```ts +new Execution( + results: Result[], + logs: Logs, + error?: ExecutionError, + executionCount?: number): Execution +``` + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | +| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | +| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount`? | `number` | `undefined` | Execution count of the cell. | + +###### Returns + +`Execution` + +#### Properties + +| Property | Modifier | Type | Default value | Description | +| ------ | ------ | ------ | ------ | ------ | +| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | +| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | +| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | + +#### Accessors + +### text + +```ts +get text(): undefined | string +``` + +Returns the text representation of the main result of the cell. + +###### Returns + +`undefined` \| `string` + +#### Methods + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the execution result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `error` | `undefined` \| `ExecutionError` | +| `logs` | `Logs` | +| `results` | `Result`[] | + +*** + +### ExecutionError + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + +#### Constructors + +```ts +new ExecutionError( + name: string, + value: string, + traceback: string): ExecutionError +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Name of the error. | +| `value` | `string` | Value of the error. | +| `traceback` | `string` | The raw traceback of the error. | + +###### Returns + +`ExecutionError` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `name` | `public` | `string` | Name of the error. | +| `traceback` | `public` | `string` | The raw traceback of the error. | +| `value` | `public` | `string` | Value of the error. | + +*** + +### OutputMessage + +Represents an output message from the sandbox code execution. + +#### Constructors + +```ts +new OutputMessage( + line: string, + timestamp: number, + error: boolean): OutputMessage +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `line` | `string` | The output line. | +| `timestamp` | `number` | Unix epoch in nanoseconds. | +| `error` | `boolean` | Whether the output is an error. | + +###### Returns + +`OutputMessage` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `error` | `readonly` | `boolean` | Whether the output is an error. | +| `line` | `readonly` | `string` | The output line. | +| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### Result + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + +#### Constructors + +```ts +new Result(rawData: RawData, isMainResult: boolean): Result +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `rawData` | `RawData` | +| `isMainResult` | `boolean` | + +###### Returns + +`Result` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | +| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | +| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | +| `html?` | `readonly` | `string` | HTML representation of the data. | +| `isMainResult` | `readonly` | `boolean` | - | +| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | +| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | +| `json?` | `readonly` | `string` | JSON representation of the data. | +| `latex?` | `readonly` | `string` | LaTeX representation of the data. | +| `markdown?` | `readonly` | `string` | Markdown representation of the data. | +| `pdf?` | `readonly` | `string` | PDF representation of the data. | +| `png?` | `readonly` | `string` | PNG representation of the data. | +| `raw` | `readonly` | `RawData` | - | +| `svg?` | `readonly` | `string` | SVG representation of the data. | +| `text?` | `readonly` | `string` | Text representation of the result. | + +#### Methods + +### formats() + +```ts +formats(): string[] +``` + +Returns all the formats available for the result. + +###### Returns + +`string`[] + +Array of strings representing the formats available for the result. + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `extra`? | `any` | +| `html` | `undefined` \| `string` | +| `javascript` | `undefined` \| `string` | +| `jpeg` | `undefined` \| `string` | +| `json` | `undefined` \| `string` | +| `latex` | `undefined` \| `string` | +| `markdown` | `undefined` \| `string` | +| `pdf` | `undefined` \| `string` | +| `png` | `undefined` \| `string` | +| `svg` | `undefined` \| `string` | +| `text` | `undefined` \| `string` | + +## Type Aliases + +### Logs + +```ts +type Logs: object; +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | +| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | + +*** + +### MIMEType + +```ts +type MIMEType: string; +``` + +Represents a MIME type. + +*** + +### RawData + +```ts +type RawData: object & E2BData; +``` + +Dictionary that maps MIME types to their corresponding representations of the data. + +## Functions + +### extractError() + +```ts +function extractError(res: Response): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `res` | `Response` | + +#### Returns + +`Promise`\<`undefined` \| `SandboxError`\> + +*** + +### parseOutput() + +```ts +function parseOutput( + execution: Execution, + line: string, + onStdout?: (output: OutputMessage) => any, + onStderr?: (output: OutputMessage) => any, + onResult?: (data: Result) => any, +onError?: (error: ExecutionError) => any): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `execution` | `Execution` | +| `line` | `string` | +| `onStdout`? | (`output`: `OutputMessage`) => `any` | +| `onStderr`? | (`output`: `OutputMessage`) => `any` | +| `onResult`? | (`data`: `Result`) => `any` | +| `onError`? | (`error`: `ExecutionError`) => `any` | + +#### Returns + +`Promise`\<`void`\> diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/sandbox/index.mdx new file mode 100644 index 0000000000..8bee4e3d24 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.1.1/sandbox/index.mdx @@ -0,0 +1,316 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +``` + +#### Methods + +### createCodeContext() + +```ts +createCodeContext(opts?: CreateCodeContextOpts): Promise +``` + +Creates a new context to run code in. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CreateCodeContextOpts` | options for creating the context. | + +###### Returns + +`Promise`\<`Context`\> + +context object. + +### runCode() + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object + +## Interfaces + +### CreateCodeContextOpts + +Options for creating a code context. + +#### Properties + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the context. + +###### Default + +```ts +/home/user +``` + +### language? + +```ts +optional language: string; +``` + +Language for the context. + +###### Default + +```ts +python +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### RunCodeOpts + +Options for running code. + +#### Properties + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for code execution. + +###### Default + +```ts +{} +``` + +### onError()? + +```ts +optional onError: (error: ExecutionError) => any; +``` + +Callback for handling the `ExecutionError` object. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `error` | `ExecutionError` | + +###### Returns + +`any` + +### onResult()? + +```ts +optional onResult: (data: Result) => any; +``` + +Callback for handling the final execution result. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `Result` | + +###### Returns + +`any` + +### onStderr()? + +```ts +optional onStderr: (output: OutputMessage) => any; +``` + +Callback for handling stderr messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### onStdout()? + +```ts +optional onStdout: (output: OutputMessage) => any; +``` + +Callback for handling stdout messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the code execution in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +## Type Aliases + +### Context + +```ts +type Context: object; +``` + +Represents a context for code execution. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `cwd` | `string` | The working directory of the context. | +| `id` | `string` | The ID of the context. | +| `language` | `string` | The language of the context. | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/charts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/charts/index.mdx new file mode 100644 index 0000000000..8959d67836 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/charts/index.mdx @@ -0,0 +1,244 @@ +--- +title: Charts +--- + +### ChartType + +Chart types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `BAR` | `"bar"` | +| `BOX_AND_WHISKER` | `"box_and_whisker"` | +| `LINE` | `"line"` | +| `PIE` | `"pie"` | +| `SCATTER` | `"scatter"` | +| `SUPERCHART` | `"superchart"` | +| `UNKNOWN` | `"unknown"` | + +*** + +### ScaleType + +Ax scale types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `ASINH` | `"asinh"` | +| `CATEGORICAL` | `"categorical"` | +| `DATETIME` | `"datetime"` | +| `FUNCTION` | `"function"` | +| `FUNCTIONLOG` | `"functionlog"` | +| `LINEAR` | `"linear"` | +| `LOG` | `"log"` | +| `LOGIT` | `"logit"` | +| `SYMLOG` | `"symlog"` | + +## Type Aliases + +### BarChart + +```ts +type BarChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BarData`[] | +| `type` | `ChartType.BAR` | + +*** + +### BarData + +```ts +type BarData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `group` | `string` | +| `label` | `string` | +| `value` | `string` | + +*** + +### BoxAndWhiskerChart + +```ts +type BoxAndWhiskerChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BoxAndWhiskerData`[] | +| `type` | `ChartType.BOX_AND_WHISKER` | + +*** + +### BoxAndWhiskerData + +```ts +type BoxAndWhiskerData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `first_quartile` | `number` | +| `label` | `string` | +| `max` | `number` | +| `median` | `number` | +| `min` | `number` | +| `outliers` | `number`[] | +| `third_quartile` | `number` | + +*** + +### Chart + +```ts +type Chart: object; +``` + +Represents a chart. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `any`[] | +| `title` | `string` | +| `type` | `ChartType` | + +*** + +### ChartTypes + +```ts +type ChartTypes: + | LineChart + | ScatterChart + | BarChart + | PieChart + | BoxAndWhiskerChart + | SuperChart; +``` + +*** + +### LineChart + +```ts +type LineChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.LINE` | + +*** + +### PieChart + +```ts +type PieChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `PieData`[] | +| `type` | `ChartType.PIE` | + +*** + +### PieData + +```ts +type PieData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `angle` | `number` | +| `label` | `string` | +| `radius` | `number` | + +*** + +### PointData + +```ts +type PointData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `label` | `string` | +| `points` | [`number` \| `string`, `number` \| `string`][] | + +*** + +### ScatterChart + +```ts +type ScatterChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.SCATTER` | + +*** + +### SuperChart + +```ts +type SuperChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `Chart`[] | +| `type` | `ChartType.SUPERCHART` | + +## Functions + +### deserializeChart() + +```ts +function deserializeChart(data: any): Chart +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `any` | + +#### Returns + +`Chart` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/consts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/consts/index.mdx new file mode 100644 index 0000000000..71f5db34eb --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/consts/index.mdx @@ -0,0 +1,17 @@ +--- +title: Consts +--- + +### DEFAULT\_TIMEOUT\_MS + +```ts +const DEFAULT_TIMEOUT_MS: 60000 = 60_000; +``` + +*** + +### JUPYTER\_PORT + +```ts +const JUPYTER_PORT: 49999 = 49999; +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/index/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/index/index.mdx new file mode 100644 index 0000000000..cb35ea04d7 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/index/index.mdx @@ -0,0 +1,107 @@ +--- +title: Index +--- + +### BarChart + +Re-exports BarChart + +### BarData + +Re-exports BarData + +### BoxAndWhiskerChart + +Re-exports BoxAndWhiskerChart + +### BoxAndWhiskerData + +Re-exports BoxAndWhiskerData + +### Chart + +Re-exports Chart + +### ChartType + +Re-exports ChartType + +### ChartTypes + +Re-exports ChartTypes + +### Context + +Re-exports Context + +### CreateCodeContextOpts + +Re-exports CreateCodeContextOpts + +### default + +Renames and re-exports Sandbox + +### Execution + +Re-exports Execution + +### ExecutionError + +Re-exports ExecutionError + +### LineChart + +Re-exports LineChart + +### Logs + +Re-exports Logs + +### MIMEType + +Re-exports MIMEType + +### OutputMessage + +Re-exports OutputMessage + +### PieChart + +Re-exports PieChart + +### PieData + +Re-exports PieData + +### PointData + +Re-exports PointData + +### RawData + +Re-exports RawData + +### Result + +Re-exports Result + +### RunCodeOpts + +Re-exports RunCodeOpts + +### Sandbox + +Re-exports Sandbox + +### ScaleType + +Re-exports ScaleType + +### ScatterChart + +Re-exports ScatterChart + +### SuperChart + +Re-exports SuperChart diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/messaging/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/messaging/index.mdx new file mode 100644 index 0000000000..f43428a047 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/messaging/index.mdx @@ -0,0 +1,330 @@ +--- +title: Messaging +--- + +### Execution + +Represents the result of a cell execution. + +#### Constructors + +```ts +new Execution( + results: Result[], + logs: Logs, + error?: ExecutionError, + executionCount?: number): Execution +``` + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | +| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | +| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount`? | `number` | `undefined` | Execution count of the cell. | + +###### Returns + +`Execution` + +#### Properties + +| Property | Modifier | Type | Default value | Description | +| ------ | ------ | ------ | ------ | ------ | +| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | +| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | +| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | + +#### Accessors + +### text + +```ts +get text(): undefined | string +``` + +Returns the text representation of the main result of the cell. + +###### Returns + +`undefined` \| `string` + +#### Methods + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the execution result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `error` | `undefined` \| `ExecutionError` | +| `logs` | `Logs` | +| `results` | `Result`[] | + +*** + +### ExecutionError + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + +#### Constructors + +```ts +new ExecutionError( + name: string, + value: string, + traceback: string): ExecutionError +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Name of the error. | +| `value` | `string` | Value of the error. | +| `traceback` | `string` | The raw traceback of the error. | + +###### Returns + +`ExecutionError` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `name` | `public` | `string` | Name of the error. | +| `traceback` | `public` | `string` | The raw traceback of the error. | +| `value` | `public` | `string` | Value of the error. | + +*** + +### OutputMessage + +Represents an output message from the sandbox code execution. + +#### Constructors + +```ts +new OutputMessage( + line: string, + timestamp: number, + error: boolean): OutputMessage +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `line` | `string` | The output line. | +| `timestamp` | `number` | Unix epoch in nanoseconds. | +| `error` | `boolean` | Whether the output is an error. | + +###### Returns + +`OutputMessage` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `error` | `readonly` | `boolean` | Whether the output is an error. | +| `line` | `readonly` | `string` | The output line. | +| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### Result + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + +#### Constructors + +```ts +new Result(rawData: RawData, isMainResult: boolean): Result +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `rawData` | `RawData` | +| `isMainResult` | `boolean` | + +###### Returns + +`Result` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | +| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | +| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | +| `html?` | `readonly` | `string` | HTML representation of the data. | +| `isMainResult` | `readonly` | `boolean` | - | +| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | +| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | +| `json?` | `readonly` | `string` | JSON representation of the data. | +| `latex?` | `readonly` | `string` | LaTeX representation of the data. | +| `markdown?` | `readonly` | `string` | Markdown representation of the data. | +| `pdf?` | `readonly` | `string` | PDF representation of the data. | +| `png?` | `readonly` | `string` | PNG representation of the data. | +| `raw` | `readonly` | `RawData` | - | +| `svg?` | `readonly` | `string` | SVG representation of the data. | +| `text?` | `readonly` | `string` | Text representation of the result. | + +#### Methods + +### formats() + +```ts +formats(): string[] +``` + +Returns all the formats available for the result. + +###### Returns + +`string`[] + +Array of strings representing the formats available for the result. + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `extra`? | `any` | +| `html` | `undefined` \| `string` | +| `javascript` | `undefined` \| `string` | +| `jpeg` | `undefined` \| `string` | +| `json` | `undefined` \| `string` | +| `latex` | `undefined` \| `string` | +| `markdown` | `undefined` \| `string` | +| `pdf` | `undefined` \| `string` | +| `png` | `undefined` \| `string` | +| `svg` | `undefined` \| `string` | +| `text` | `undefined` \| `string` | + +## Type Aliases + +### Logs + +```ts +type Logs: object; +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | +| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | + +*** + +### MIMEType + +```ts +type MIMEType: string; +``` + +Represents a MIME type. + +*** + +### RawData + +```ts +type RawData: object & E2BData; +``` + +Dictionary that maps MIME types to their corresponding representations of the data. + +## Functions + +### extractError() + +```ts +function extractError(res: Response): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `res` | `Response` | + +#### Returns + +`Promise`\<`undefined` \| `SandboxError`\> + +*** + +### parseOutput() + +```ts +function parseOutput( + execution: Execution, + line: string, + onStdout?: (output: OutputMessage) => any, + onStderr?: (output: OutputMessage) => any, + onResult?: (data: Result) => any, +onError?: (error: ExecutionError) => any): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `execution` | `Execution` | +| `line` | `string` | +| `onStdout`? | (`output`: `OutputMessage`) => `any` | +| `onStderr`? | (`output`: `OutputMessage`) => `any` | +| `onResult`? | (`data`: `Result`) => `any` | +| `onError`? | (`error`: `ExecutionError`) => `any` | + +#### Returns + +`Promise`\<`void`\> diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/sandbox/index.mdx new file mode 100644 index 0000000000..8bee4e3d24 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.2.0/sandbox/index.mdx @@ -0,0 +1,316 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +``` + +#### Methods + +### createCodeContext() + +```ts +createCodeContext(opts?: CreateCodeContextOpts): Promise +``` + +Creates a new context to run code in. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CreateCodeContextOpts` | options for creating the context. | + +###### Returns + +`Promise`\<`Context`\> + +context object. + +### runCode() + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object + +## Interfaces + +### CreateCodeContextOpts + +Options for creating a code context. + +#### Properties + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the context. + +###### Default + +```ts +/home/user +``` + +### language? + +```ts +optional language: string; +``` + +Language for the context. + +###### Default + +```ts +python +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### RunCodeOpts + +Options for running code. + +#### Properties + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for code execution. + +###### Default + +```ts +{} +``` + +### onError()? + +```ts +optional onError: (error: ExecutionError) => any; +``` + +Callback for handling the `ExecutionError` object. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `error` | `ExecutionError` | + +###### Returns + +`any` + +### onResult()? + +```ts +optional onResult: (data: Result) => any; +``` + +Callback for handling the final execution result. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `Result` | + +###### Returns + +`any` + +### onStderr()? + +```ts +optional onStderr: (output: OutputMessage) => any; +``` + +Callback for handling stderr messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### onStdout()? + +```ts +optional onStdout: (output: OutputMessage) => any; +``` + +Callback for handling stdout messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the code execution in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +## Type Aliases + +### Context + +```ts +type Context: object; +``` + +Represents a context for code execution. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `cwd` | `string` | The working directory of the context. | +| `id` | `string` | The ID of the context. | +| `language` | `string` | The language of the context. | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/charts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/charts/index.mdx new file mode 100644 index 0000000000..8959d67836 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/charts/index.mdx @@ -0,0 +1,244 @@ +--- +title: Charts +--- + +### ChartType + +Chart types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `BAR` | `"bar"` | +| `BOX_AND_WHISKER` | `"box_and_whisker"` | +| `LINE` | `"line"` | +| `PIE` | `"pie"` | +| `SCATTER` | `"scatter"` | +| `SUPERCHART` | `"superchart"` | +| `UNKNOWN` | `"unknown"` | + +*** + +### ScaleType + +Ax scale types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `ASINH` | `"asinh"` | +| `CATEGORICAL` | `"categorical"` | +| `DATETIME` | `"datetime"` | +| `FUNCTION` | `"function"` | +| `FUNCTIONLOG` | `"functionlog"` | +| `LINEAR` | `"linear"` | +| `LOG` | `"log"` | +| `LOGIT` | `"logit"` | +| `SYMLOG` | `"symlog"` | + +## Type Aliases + +### BarChart + +```ts +type BarChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BarData`[] | +| `type` | `ChartType.BAR` | + +*** + +### BarData + +```ts +type BarData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `group` | `string` | +| `label` | `string` | +| `value` | `string` | + +*** + +### BoxAndWhiskerChart + +```ts +type BoxAndWhiskerChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BoxAndWhiskerData`[] | +| `type` | `ChartType.BOX_AND_WHISKER` | + +*** + +### BoxAndWhiskerData + +```ts +type BoxAndWhiskerData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `first_quartile` | `number` | +| `label` | `string` | +| `max` | `number` | +| `median` | `number` | +| `min` | `number` | +| `outliers` | `number`[] | +| `third_quartile` | `number` | + +*** + +### Chart + +```ts +type Chart: object; +``` + +Represents a chart. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `any`[] | +| `title` | `string` | +| `type` | `ChartType` | + +*** + +### ChartTypes + +```ts +type ChartTypes: + | LineChart + | ScatterChart + | BarChart + | PieChart + | BoxAndWhiskerChart + | SuperChart; +``` + +*** + +### LineChart + +```ts +type LineChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.LINE` | + +*** + +### PieChart + +```ts +type PieChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `PieData`[] | +| `type` | `ChartType.PIE` | + +*** + +### PieData + +```ts +type PieData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `angle` | `number` | +| `label` | `string` | +| `radius` | `number` | + +*** + +### PointData + +```ts +type PointData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `label` | `string` | +| `points` | [`number` \| `string`, `number` \| `string`][] | + +*** + +### ScatterChart + +```ts +type ScatterChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.SCATTER` | + +*** + +### SuperChart + +```ts +type SuperChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `Chart`[] | +| `type` | `ChartType.SUPERCHART` | + +## Functions + +### deserializeChart() + +```ts +function deserializeChart(data: any): Chart +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `any` | + +#### Returns + +`Chart` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/consts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/consts/index.mdx new file mode 100644 index 0000000000..71f5db34eb --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/consts/index.mdx @@ -0,0 +1,17 @@ +--- +title: Consts +--- + +### DEFAULT\_TIMEOUT\_MS + +```ts +const DEFAULT_TIMEOUT_MS: 60000 = 60_000; +``` + +*** + +### JUPYTER\_PORT + +```ts +const JUPYTER_PORT: 49999 = 49999; +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/index/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/index/index.mdx new file mode 100644 index 0000000000..cb35ea04d7 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/index/index.mdx @@ -0,0 +1,107 @@ +--- +title: Index +--- + +### BarChart + +Re-exports BarChart + +### BarData + +Re-exports BarData + +### BoxAndWhiskerChart + +Re-exports BoxAndWhiskerChart + +### BoxAndWhiskerData + +Re-exports BoxAndWhiskerData + +### Chart + +Re-exports Chart + +### ChartType + +Re-exports ChartType + +### ChartTypes + +Re-exports ChartTypes + +### Context + +Re-exports Context + +### CreateCodeContextOpts + +Re-exports CreateCodeContextOpts + +### default + +Renames and re-exports Sandbox + +### Execution + +Re-exports Execution + +### ExecutionError + +Re-exports ExecutionError + +### LineChart + +Re-exports LineChart + +### Logs + +Re-exports Logs + +### MIMEType + +Re-exports MIMEType + +### OutputMessage + +Re-exports OutputMessage + +### PieChart + +Re-exports PieChart + +### PieData + +Re-exports PieData + +### PointData + +Re-exports PointData + +### RawData + +Re-exports RawData + +### Result + +Re-exports Result + +### RunCodeOpts + +Re-exports RunCodeOpts + +### Sandbox + +Re-exports Sandbox + +### ScaleType + +Re-exports ScaleType + +### ScatterChart + +Re-exports ScatterChart + +### SuperChart + +Re-exports SuperChart diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/messaging/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/messaging/index.mdx new file mode 100644 index 0000000000..f43428a047 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/messaging/index.mdx @@ -0,0 +1,330 @@ +--- +title: Messaging +--- + +### Execution + +Represents the result of a cell execution. + +#### Constructors + +```ts +new Execution( + results: Result[], + logs: Logs, + error?: ExecutionError, + executionCount?: number): Execution +``` + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | +| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | +| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount`? | `number` | `undefined` | Execution count of the cell. | + +###### Returns + +`Execution` + +#### Properties + +| Property | Modifier | Type | Default value | Description | +| ------ | ------ | ------ | ------ | ------ | +| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | +| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | +| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | + +#### Accessors + +### text + +```ts +get text(): undefined | string +``` + +Returns the text representation of the main result of the cell. + +###### Returns + +`undefined` \| `string` + +#### Methods + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the execution result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `error` | `undefined` \| `ExecutionError` | +| `logs` | `Logs` | +| `results` | `Result`[] | + +*** + +### ExecutionError + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + +#### Constructors + +```ts +new ExecutionError( + name: string, + value: string, + traceback: string): ExecutionError +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Name of the error. | +| `value` | `string` | Value of the error. | +| `traceback` | `string` | The raw traceback of the error. | + +###### Returns + +`ExecutionError` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `name` | `public` | `string` | Name of the error. | +| `traceback` | `public` | `string` | The raw traceback of the error. | +| `value` | `public` | `string` | Value of the error. | + +*** + +### OutputMessage + +Represents an output message from the sandbox code execution. + +#### Constructors + +```ts +new OutputMessage( + line: string, + timestamp: number, + error: boolean): OutputMessage +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `line` | `string` | The output line. | +| `timestamp` | `number` | Unix epoch in nanoseconds. | +| `error` | `boolean` | Whether the output is an error. | + +###### Returns + +`OutputMessage` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `error` | `readonly` | `boolean` | Whether the output is an error. | +| `line` | `readonly` | `string` | The output line. | +| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### Result + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + +#### Constructors + +```ts +new Result(rawData: RawData, isMainResult: boolean): Result +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `rawData` | `RawData` | +| `isMainResult` | `boolean` | + +###### Returns + +`Result` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | +| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | +| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | +| `html?` | `readonly` | `string` | HTML representation of the data. | +| `isMainResult` | `readonly` | `boolean` | - | +| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | +| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | +| `json?` | `readonly` | `string` | JSON representation of the data. | +| `latex?` | `readonly` | `string` | LaTeX representation of the data. | +| `markdown?` | `readonly` | `string` | Markdown representation of the data. | +| `pdf?` | `readonly` | `string` | PDF representation of the data. | +| `png?` | `readonly` | `string` | PNG representation of the data. | +| `raw` | `readonly` | `RawData` | - | +| `svg?` | `readonly` | `string` | SVG representation of the data. | +| `text?` | `readonly` | `string` | Text representation of the result. | + +#### Methods + +### formats() + +```ts +formats(): string[] +``` + +Returns all the formats available for the result. + +###### Returns + +`string`[] + +Array of strings representing the formats available for the result. + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `extra`? | `any` | +| `html` | `undefined` \| `string` | +| `javascript` | `undefined` \| `string` | +| `jpeg` | `undefined` \| `string` | +| `json` | `undefined` \| `string` | +| `latex` | `undefined` \| `string` | +| `markdown` | `undefined` \| `string` | +| `pdf` | `undefined` \| `string` | +| `png` | `undefined` \| `string` | +| `svg` | `undefined` \| `string` | +| `text` | `undefined` \| `string` | + +## Type Aliases + +### Logs + +```ts +type Logs: object; +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | +| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | + +*** + +### MIMEType + +```ts +type MIMEType: string; +``` + +Represents a MIME type. + +*** + +### RawData + +```ts +type RawData: object & E2BData; +``` + +Dictionary that maps MIME types to their corresponding representations of the data. + +## Functions + +### extractError() + +```ts +function extractError(res: Response): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `res` | `Response` | + +#### Returns + +`Promise`\<`undefined` \| `SandboxError`\> + +*** + +### parseOutput() + +```ts +function parseOutput( + execution: Execution, + line: string, + onStdout?: (output: OutputMessage) => any, + onStderr?: (output: OutputMessage) => any, + onResult?: (data: Result) => any, +onError?: (error: ExecutionError) => any): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `execution` | `Execution` | +| `line` | `string` | +| `onStdout`? | (`output`: `OutputMessage`) => `any` | +| `onStderr`? | (`output`: `OutputMessage`) => `any` | +| `onResult`? | (`data`: `Result`) => `any` | +| `onError`? | (`error`: `ExecutionError`) => `any` | + +#### Returns + +`Promise`\<`void`\> diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/sandbox/index.mdx new file mode 100644 index 0000000000..8bee4e3d24 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.0/sandbox/index.mdx @@ -0,0 +1,316 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +``` + +#### Methods + +### createCodeContext() + +```ts +createCodeContext(opts?: CreateCodeContextOpts): Promise +``` + +Creates a new context to run code in. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CreateCodeContextOpts` | options for creating the context. | + +###### Returns + +`Promise`\<`Context`\> + +context object. + +### runCode() + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object + +## Interfaces + +### CreateCodeContextOpts + +Options for creating a code context. + +#### Properties + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the context. + +###### Default + +```ts +/home/user +``` + +### language? + +```ts +optional language: string; +``` + +Language for the context. + +###### Default + +```ts +python +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### RunCodeOpts + +Options for running code. + +#### Properties + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for code execution. + +###### Default + +```ts +{} +``` + +### onError()? + +```ts +optional onError: (error: ExecutionError) => any; +``` + +Callback for handling the `ExecutionError` object. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `error` | `ExecutionError` | + +###### Returns + +`any` + +### onResult()? + +```ts +optional onResult: (data: Result) => any; +``` + +Callback for handling the final execution result. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `Result` | + +###### Returns + +`any` + +### onStderr()? + +```ts +optional onStderr: (output: OutputMessage) => any; +``` + +Callback for handling stderr messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### onStdout()? + +```ts +optional onStdout: (output: OutputMessage) => any; +``` + +Callback for handling stdout messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the code execution in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +## Type Aliases + +### Context + +```ts +type Context: object; +``` + +Represents a context for code execution. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `cwd` | `string` | The working directory of the context. | +| `id` | `string` | The ID of the context. | +| `language` | `string` | The language of the context. | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/charts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/charts/index.mdx new file mode 100644 index 0000000000..8959d67836 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/charts/index.mdx @@ -0,0 +1,244 @@ +--- +title: Charts +--- + +### ChartType + +Chart types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `BAR` | `"bar"` | +| `BOX_AND_WHISKER` | `"box_and_whisker"` | +| `LINE` | `"line"` | +| `PIE` | `"pie"` | +| `SCATTER` | `"scatter"` | +| `SUPERCHART` | `"superchart"` | +| `UNKNOWN` | `"unknown"` | + +*** + +### ScaleType + +Ax scale types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `ASINH` | `"asinh"` | +| `CATEGORICAL` | `"categorical"` | +| `DATETIME` | `"datetime"` | +| `FUNCTION` | `"function"` | +| `FUNCTIONLOG` | `"functionlog"` | +| `LINEAR` | `"linear"` | +| `LOG` | `"log"` | +| `LOGIT` | `"logit"` | +| `SYMLOG` | `"symlog"` | + +## Type Aliases + +### BarChart + +```ts +type BarChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BarData`[] | +| `type` | `ChartType.BAR` | + +*** + +### BarData + +```ts +type BarData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `group` | `string` | +| `label` | `string` | +| `value` | `string` | + +*** + +### BoxAndWhiskerChart + +```ts +type BoxAndWhiskerChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BoxAndWhiskerData`[] | +| `type` | `ChartType.BOX_AND_WHISKER` | + +*** + +### BoxAndWhiskerData + +```ts +type BoxAndWhiskerData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `first_quartile` | `number` | +| `label` | `string` | +| `max` | `number` | +| `median` | `number` | +| `min` | `number` | +| `outliers` | `number`[] | +| `third_quartile` | `number` | + +*** + +### Chart + +```ts +type Chart: object; +``` + +Represents a chart. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `any`[] | +| `title` | `string` | +| `type` | `ChartType` | + +*** + +### ChartTypes + +```ts +type ChartTypes: + | LineChart + | ScatterChart + | BarChart + | PieChart + | BoxAndWhiskerChart + | SuperChart; +``` + +*** + +### LineChart + +```ts +type LineChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.LINE` | + +*** + +### PieChart + +```ts +type PieChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `PieData`[] | +| `type` | `ChartType.PIE` | + +*** + +### PieData + +```ts +type PieData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `angle` | `number` | +| `label` | `string` | +| `radius` | `number` | + +*** + +### PointData + +```ts +type PointData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `label` | `string` | +| `points` | [`number` \| `string`, `number` \| `string`][] | + +*** + +### ScatterChart + +```ts +type ScatterChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.SCATTER` | + +*** + +### SuperChart + +```ts +type SuperChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `Chart`[] | +| `type` | `ChartType.SUPERCHART` | + +## Functions + +### deserializeChart() + +```ts +function deserializeChart(data: any): Chart +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `any` | + +#### Returns + +`Chart` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/consts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/consts/index.mdx new file mode 100644 index 0000000000..71f5db34eb --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/consts/index.mdx @@ -0,0 +1,17 @@ +--- +title: Consts +--- + +### DEFAULT\_TIMEOUT\_MS + +```ts +const DEFAULT_TIMEOUT_MS: 60000 = 60_000; +``` + +*** + +### JUPYTER\_PORT + +```ts +const JUPYTER_PORT: 49999 = 49999; +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/index/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/index/index.mdx new file mode 100644 index 0000000000..cb35ea04d7 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/index/index.mdx @@ -0,0 +1,107 @@ +--- +title: Index +--- + +### BarChart + +Re-exports BarChart + +### BarData + +Re-exports BarData + +### BoxAndWhiskerChart + +Re-exports BoxAndWhiskerChart + +### BoxAndWhiskerData + +Re-exports BoxAndWhiskerData + +### Chart + +Re-exports Chart + +### ChartType + +Re-exports ChartType + +### ChartTypes + +Re-exports ChartTypes + +### Context + +Re-exports Context + +### CreateCodeContextOpts + +Re-exports CreateCodeContextOpts + +### default + +Renames and re-exports Sandbox + +### Execution + +Re-exports Execution + +### ExecutionError + +Re-exports ExecutionError + +### LineChart + +Re-exports LineChart + +### Logs + +Re-exports Logs + +### MIMEType + +Re-exports MIMEType + +### OutputMessage + +Re-exports OutputMessage + +### PieChart + +Re-exports PieChart + +### PieData + +Re-exports PieData + +### PointData + +Re-exports PointData + +### RawData + +Re-exports RawData + +### Result + +Re-exports Result + +### RunCodeOpts + +Re-exports RunCodeOpts + +### Sandbox + +Re-exports Sandbox + +### ScaleType + +Re-exports ScaleType + +### ScatterChart + +Re-exports ScatterChart + +### SuperChart + +Re-exports SuperChart diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/messaging/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/messaging/index.mdx new file mode 100644 index 0000000000..f43428a047 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/messaging/index.mdx @@ -0,0 +1,330 @@ +--- +title: Messaging +--- + +### Execution + +Represents the result of a cell execution. + +#### Constructors + +```ts +new Execution( + results: Result[], + logs: Logs, + error?: ExecutionError, + executionCount?: number): Execution +``` + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | +| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | +| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount`? | `number` | `undefined` | Execution count of the cell. | + +###### Returns + +`Execution` + +#### Properties + +| Property | Modifier | Type | Default value | Description | +| ------ | ------ | ------ | ------ | ------ | +| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | +| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | +| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | + +#### Accessors + +### text + +```ts +get text(): undefined | string +``` + +Returns the text representation of the main result of the cell. + +###### Returns + +`undefined` \| `string` + +#### Methods + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the execution result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `error` | `undefined` \| `ExecutionError` | +| `logs` | `Logs` | +| `results` | `Result`[] | + +*** + +### ExecutionError + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + +#### Constructors + +```ts +new ExecutionError( + name: string, + value: string, + traceback: string): ExecutionError +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Name of the error. | +| `value` | `string` | Value of the error. | +| `traceback` | `string` | The raw traceback of the error. | + +###### Returns + +`ExecutionError` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `name` | `public` | `string` | Name of the error. | +| `traceback` | `public` | `string` | The raw traceback of the error. | +| `value` | `public` | `string` | Value of the error. | + +*** + +### OutputMessage + +Represents an output message from the sandbox code execution. + +#### Constructors + +```ts +new OutputMessage( + line: string, + timestamp: number, + error: boolean): OutputMessage +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `line` | `string` | The output line. | +| `timestamp` | `number` | Unix epoch in nanoseconds. | +| `error` | `boolean` | Whether the output is an error. | + +###### Returns + +`OutputMessage` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `error` | `readonly` | `boolean` | Whether the output is an error. | +| `line` | `readonly` | `string` | The output line. | +| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### Result + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + +#### Constructors + +```ts +new Result(rawData: RawData, isMainResult: boolean): Result +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `rawData` | `RawData` | +| `isMainResult` | `boolean` | + +###### Returns + +`Result` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | +| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | +| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | +| `html?` | `readonly` | `string` | HTML representation of the data. | +| `isMainResult` | `readonly` | `boolean` | - | +| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | +| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | +| `json?` | `readonly` | `string` | JSON representation of the data. | +| `latex?` | `readonly` | `string` | LaTeX representation of the data. | +| `markdown?` | `readonly` | `string` | Markdown representation of the data. | +| `pdf?` | `readonly` | `string` | PDF representation of the data. | +| `png?` | `readonly` | `string` | PNG representation of the data. | +| `raw` | `readonly` | `RawData` | - | +| `svg?` | `readonly` | `string` | SVG representation of the data. | +| `text?` | `readonly` | `string` | Text representation of the result. | + +#### Methods + +### formats() + +```ts +formats(): string[] +``` + +Returns all the formats available for the result. + +###### Returns + +`string`[] + +Array of strings representing the formats available for the result. + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `extra`? | `any` | +| `html` | `undefined` \| `string` | +| `javascript` | `undefined` \| `string` | +| `jpeg` | `undefined` \| `string` | +| `json` | `undefined` \| `string` | +| `latex` | `undefined` \| `string` | +| `markdown` | `undefined` \| `string` | +| `pdf` | `undefined` \| `string` | +| `png` | `undefined` \| `string` | +| `svg` | `undefined` \| `string` | +| `text` | `undefined` \| `string` | + +## Type Aliases + +### Logs + +```ts +type Logs: object; +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | +| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | + +*** + +### MIMEType + +```ts +type MIMEType: string; +``` + +Represents a MIME type. + +*** + +### RawData + +```ts +type RawData: object & E2BData; +``` + +Dictionary that maps MIME types to their corresponding representations of the data. + +## Functions + +### extractError() + +```ts +function extractError(res: Response): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `res` | `Response` | + +#### Returns + +`Promise`\<`undefined` \| `SandboxError`\> + +*** + +### parseOutput() + +```ts +function parseOutput( + execution: Execution, + line: string, + onStdout?: (output: OutputMessage) => any, + onStderr?: (output: OutputMessage) => any, + onResult?: (data: Result) => any, +onError?: (error: ExecutionError) => any): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `execution` | `Execution` | +| `line` | `string` | +| `onStdout`? | (`output`: `OutputMessage`) => `any` | +| `onStderr`? | (`output`: `OutputMessage`) => `any` | +| `onResult`? | (`data`: `Result`) => `any` | +| `onError`? | (`error`: `ExecutionError`) => `any` | + +#### Returns + +`Promise`\<`void`\> diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/sandbox/index.mdx new file mode 100644 index 0000000000..8bee4e3d24 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v1.5.1/sandbox/index.mdx @@ -0,0 +1,316 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +``` + +#### Methods + +### createCodeContext() + +```ts +createCodeContext(opts?: CreateCodeContextOpts): Promise +``` + +Creates a new context to run code in. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CreateCodeContextOpts` | options for creating the context. | + +###### Returns + +`Promise`\<`Context`\> + +context object. + +### runCode() + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object + +## Interfaces + +### CreateCodeContextOpts + +Options for creating a code context. + +#### Properties + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the context. + +###### Default + +```ts +/home/user +``` + +### language? + +```ts +optional language: string; +``` + +Language for the context. + +###### Default + +```ts +python +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### RunCodeOpts + +Options for running code. + +#### Properties + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for code execution. + +###### Default + +```ts +{} +``` + +### onError()? + +```ts +optional onError: (error: ExecutionError) => any; +``` + +Callback for handling the `ExecutionError` object. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `error` | `ExecutionError` | + +###### Returns + +`any` + +### onResult()? + +```ts +optional onResult: (data: Result) => any; +``` + +Callback for handling the final execution result. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `Result` | + +###### Returns + +`any` + +### onStderr()? + +```ts +optional onStderr: (output: OutputMessage) => any; +``` + +Callback for handling stderr messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### onStdout()? + +```ts +optional onStdout: (output: OutputMessage) => any; +``` + +Callback for handling stdout messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the code execution in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +## Type Aliases + +### Context + +```ts +type Context: object; +``` + +Represents a context for code execution. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `cwd` | `string` | The working directory of the context. | +| `id` | `string` | The ID of the context. | +| `language` | `string` | The language of the context. | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/charts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/charts/index.mdx new file mode 100644 index 0000000000..8959d67836 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/charts/index.mdx @@ -0,0 +1,244 @@ +--- +title: Charts +--- + +### ChartType + +Chart types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `BAR` | `"bar"` | +| `BOX_AND_WHISKER` | `"box_and_whisker"` | +| `LINE` | `"line"` | +| `PIE` | `"pie"` | +| `SCATTER` | `"scatter"` | +| `SUPERCHART` | `"superchart"` | +| `UNKNOWN` | `"unknown"` | + +*** + +### ScaleType + +Ax scale types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `ASINH` | `"asinh"` | +| `CATEGORICAL` | `"categorical"` | +| `DATETIME` | `"datetime"` | +| `FUNCTION` | `"function"` | +| `FUNCTIONLOG` | `"functionlog"` | +| `LINEAR` | `"linear"` | +| `LOG` | `"log"` | +| `LOGIT` | `"logit"` | +| `SYMLOG` | `"symlog"` | + +## Type Aliases + +### BarChart + +```ts +type BarChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BarData`[] | +| `type` | `ChartType.BAR` | + +*** + +### BarData + +```ts +type BarData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `group` | `string` | +| `label` | `string` | +| `value` | `string` | + +*** + +### BoxAndWhiskerChart + +```ts +type BoxAndWhiskerChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BoxAndWhiskerData`[] | +| `type` | `ChartType.BOX_AND_WHISKER` | + +*** + +### BoxAndWhiskerData + +```ts +type BoxAndWhiskerData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `first_quartile` | `number` | +| `label` | `string` | +| `max` | `number` | +| `median` | `number` | +| `min` | `number` | +| `outliers` | `number`[] | +| `third_quartile` | `number` | + +*** + +### Chart + +```ts +type Chart: object; +``` + +Represents a chart. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `any`[] | +| `title` | `string` | +| `type` | `ChartType` | + +*** + +### ChartTypes + +```ts +type ChartTypes: + | LineChart + | ScatterChart + | BarChart + | PieChart + | BoxAndWhiskerChart + | SuperChart; +``` + +*** + +### LineChart + +```ts +type LineChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.LINE` | + +*** + +### PieChart + +```ts +type PieChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `PieData`[] | +| `type` | `ChartType.PIE` | + +*** + +### PieData + +```ts +type PieData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `angle` | `number` | +| `label` | `string` | +| `radius` | `number` | + +*** + +### PointData + +```ts +type PointData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `label` | `string` | +| `points` | [`number` \| `string`, `number` \| `string`][] | + +*** + +### ScatterChart + +```ts +type ScatterChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.SCATTER` | + +*** + +### SuperChart + +```ts +type SuperChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `Chart`[] | +| `type` | `ChartType.SUPERCHART` | + +## Functions + +### deserializeChart() + +```ts +function deserializeChart(data: any): Chart +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `any` | + +#### Returns + +`Chart` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/consts/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/consts/index.mdx new file mode 100644 index 0000000000..71f5db34eb --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/consts/index.mdx @@ -0,0 +1,17 @@ +--- +title: Consts +--- + +### DEFAULT\_TIMEOUT\_MS + +```ts +const DEFAULT_TIMEOUT_MS: 60000 = 60_000; +``` + +*** + +### JUPYTER\_PORT + +```ts +const JUPYTER_PORT: 49999 = 49999; +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/index/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/index/index.mdx new file mode 100644 index 0000000000..cb35ea04d7 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/index/index.mdx @@ -0,0 +1,107 @@ +--- +title: Index +--- + +### BarChart + +Re-exports BarChart + +### BarData + +Re-exports BarData + +### BoxAndWhiskerChart + +Re-exports BoxAndWhiskerChart + +### BoxAndWhiskerData + +Re-exports BoxAndWhiskerData + +### Chart + +Re-exports Chart + +### ChartType + +Re-exports ChartType + +### ChartTypes + +Re-exports ChartTypes + +### Context + +Re-exports Context + +### CreateCodeContextOpts + +Re-exports CreateCodeContextOpts + +### default + +Renames and re-exports Sandbox + +### Execution + +Re-exports Execution + +### ExecutionError + +Re-exports ExecutionError + +### LineChart + +Re-exports LineChart + +### Logs + +Re-exports Logs + +### MIMEType + +Re-exports MIMEType + +### OutputMessage + +Re-exports OutputMessage + +### PieChart + +Re-exports PieChart + +### PieData + +Re-exports PieData + +### PointData + +Re-exports PointData + +### RawData + +Re-exports RawData + +### Result + +Re-exports Result + +### RunCodeOpts + +Re-exports RunCodeOpts + +### Sandbox + +Re-exports Sandbox + +### ScaleType + +Re-exports ScaleType + +### ScatterChart + +Re-exports ScatterChart + +### SuperChart + +Re-exports SuperChart diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/messaging/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/messaging/index.mdx new file mode 100644 index 0000000000..f43428a047 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/messaging/index.mdx @@ -0,0 +1,330 @@ +--- +title: Messaging +--- + +### Execution + +Represents the result of a cell execution. + +#### Constructors + +```ts +new Execution( + results: Result[], + logs: Logs, + error?: ExecutionError, + executionCount?: number): Execution +``` + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | +| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | +| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount`? | `number` | `undefined` | Execution count of the cell. | + +###### Returns + +`Execution` + +#### Properties + +| Property | Modifier | Type | Default value | Description | +| ------ | ------ | ------ | ------ | ------ | +| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | +| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | +| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | + +#### Accessors + +### text + +```ts +get text(): undefined | string +``` + +Returns the text representation of the main result of the cell. + +###### Returns + +`undefined` \| `string` + +#### Methods + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the execution result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `error` | `undefined` \| `ExecutionError` | +| `logs` | `Logs` | +| `results` | `Result`[] | + +*** + +### ExecutionError + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + +#### Constructors + +```ts +new ExecutionError( + name: string, + value: string, + traceback: string): ExecutionError +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Name of the error. | +| `value` | `string` | Value of the error. | +| `traceback` | `string` | The raw traceback of the error. | + +###### Returns + +`ExecutionError` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `name` | `public` | `string` | Name of the error. | +| `traceback` | `public` | `string` | The raw traceback of the error. | +| `value` | `public` | `string` | Value of the error. | + +*** + +### OutputMessage + +Represents an output message from the sandbox code execution. + +#### Constructors + +```ts +new OutputMessage( + line: string, + timestamp: number, + error: boolean): OutputMessage +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `line` | `string` | The output line. | +| `timestamp` | `number` | Unix epoch in nanoseconds. | +| `error` | `boolean` | Whether the output is an error. | + +###### Returns + +`OutputMessage` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `error` | `readonly` | `boolean` | Whether the output is an error. | +| `line` | `readonly` | `string` | The output line. | +| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### Result + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + +#### Constructors + +```ts +new Result(rawData: RawData, isMainResult: boolean): Result +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `rawData` | `RawData` | +| `isMainResult` | `boolean` | + +###### Returns + +`Result` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | +| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | +| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | +| `html?` | `readonly` | `string` | HTML representation of the data. | +| `isMainResult` | `readonly` | `boolean` | - | +| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | +| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | +| `json?` | `readonly` | `string` | JSON representation of the data. | +| `latex?` | `readonly` | `string` | LaTeX representation of the data. | +| `markdown?` | `readonly` | `string` | Markdown representation of the data. | +| `pdf?` | `readonly` | `string` | PDF representation of the data. | +| `png?` | `readonly` | `string` | PNG representation of the data. | +| `raw` | `readonly` | `RawData` | - | +| `svg?` | `readonly` | `string` | SVG representation of the data. | +| `text?` | `readonly` | `string` | Text representation of the result. | + +#### Methods + +### formats() + +```ts +formats(): string[] +``` + +Returns all the formats available for the result. + +###### Returns + +`string`[] + +Array of strings representing the formats available for the result. + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `extra`? | `any` | +| `html` | `undefined` \| `string` | +| `javascript` | `undefined` \| `string` | +| `jpeg` | `undefined` \| `string` | +| `json` | `undefined` \| `string` | +| `latex` | `undefined` \| `string` | +| `markdown` | `undefined` \| `string` | +| `pdf` | `undefined` \| `string` | +| `png` | `undefined` \| `string` | +| `svg` | `undefined` \| `string` | +| `text` | `undefined` \| `string` | + +## Type Aliases + +### Logs + +```ts +type Logs: object; +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | +| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | + +*** + +### MIMEType + +```ts +type MIMEType: string; +``` + +Represents a MIME type. + +*** + +### RawData + +```ts +type RawData: object & E2BData; +``` + +Dictionary that maps MIME types to their corresponding representations of the data. + +## Functions + +### extractError() + +```ts +function extractError(res: Response): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `res` | `Response` | + +#### Returns + +`Promise`\<`undefined` \| `SandboxError`\> + +*** + +### parseOutput() + +```ts +function parseOutput( + execution: Execution, + line: string, + onStdout?: (output: OutputMessage) => any, + onStderr?: (output: OutputMessage) => any, + onResult?: (data: Result) => any, +onError?: (error: ExecutionError) => any): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `execution` | `Execution` | +| `line` | `string` | +| `onStdout`? | (`output`: `OutputMessage`) => `any` | +| `onStderr`? | (`output`: `OutputMessage`) => `any` | +| `onResult`? | (`data`: `Result`) => `any` | +| `onError`? | (`error`: `ExecutionError`) => `any` | + +#### Returns + +`Promise`\<`void`\> diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/sandbox/index.mdx new file mode 100644 index 0000000000..8bee4e3d24 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-js-sdk/v2.0.0/sandbox/index.mdx @@ -0,0 +1,316 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +``` + +#### Methods + +### createCodeContext() + +```ts +createCodeContext(opts?: CreateCodeContextOpts): Promise +``` + +Creates a new context to run code in. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CreateCodeContextOpts` | options for creating the context. | + +###### Returns + +`Promise`\<`Context`\> + +context object. + +### runCode() + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object + +## Interfaces + +### CreateCodeContextOpts + +Options for creating a code context. + +#### Properties + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the context. + +###### Default + +```ts +/home/user +``` + +### language? + +```ts +optional language: string; +``` + +Language for the context. + +###### Default + +```ts +python +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### RunCodeOpts + +Options for running code. + +#### Properties + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for code execution. + +###### Default + +```ts +{} +``` + +### onError()? + +```ts +optional onError: (error: ExecutionError) => any; +``` + +Callback for handling the `ExecutionError` object. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `error` | `ExecutionError` | + +###### Returns + +`any` + +### onResult()? + +```ts +optional onResult: (data: Result) => any; +``` + +Callback for handling the final execution result. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `Result` | + +###### Returns + +`any` + +### onStderr()? + +```ts +optional onStderr: (output: OutputMessage) => any; +``` + +Callback for handling stderr messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### onStdout()? + +```ts +optional onStdout: (output: OutputMessage) => any; +``` + +Callback for handling stdout messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the code execution in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +## Type Aliases + +### Context + +```ts +type Context: object; +``` + +Represents a context for code execution. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `cwd` | `string` | The working directory of the context. | +| `id` | `string` | The ID of the context. | +| `language` | `string` | The language of the context. | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.1/sandbox/index.mdx new file mode 100644 index 0000000000..5d65c408ca --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.1/sandbox/index.mdx @@ -0,0 +1,726 @@ +--- +title: Sandbox +--- + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + +## OutputMessage + +```python Python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + +### line + +The output line. + + +### timestamp + +Unix epoch in nanoseconds + + +### error + +Whether the output is an error. + + +## ExecutionError + +```python Python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + +### name + +Name of the error. + + +### value + +Value of the error. + + +### traceback + +The raw traceback of the error. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + +## MIMEType + +```python Python +class MIMEType(str) +``` + +Represents a MIME type. + + +## Result + +```python Python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + +### extra + +Extra data that can be included. Not part of the standard types. + + +### formats + +```python Python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + +### \_\_str\_\_ + +```python Python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + +### \_repr\_html\_ + +```python Python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + +### \_repr\_markdown\_ + +```python Python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + +### \_repr\_svg\_ + +```python Python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + +### \_repr\_png\_ + +```python Python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + +### \_repr\_jpeg\_ + +```python Python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + +### \_repr\_pdf\_ + +```python Python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + +### \_repr\_latex\_ + +```python Python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + +### \_repr\_json\_ + +```python Python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + +### \_repr\_javascript\_ + +```python Python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + +## Logs + +```python Python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + +### serialize\_results + +```python Python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + +## Execution + +```python Python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + +### logs + +Logs printed to stdout and stderr during execution. + + +### error + +Error object if an error occurred, None otherwise. + + +### execution\_count + +Execution count of the cell. + + +### text + +```python Python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + +## Context + +```python Python +@dataclass +class Context() +``` + +Represents a context for code execution. + + +### id + +The ID of the context. + + +### language + +The language of the context. + + +### cwd + +The working directory of the context. + + + + +## ChartType + +```python Python +class ChartType(str, enum.Enum) +``` + +Chart types + + +## ScaleType + +```python Python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + +## Chart + +```python Python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + +## Sandbox + +```python Python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +``` + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.2/sandbox/index.mdx new file mode 100644 index 0000000000..f7003e555a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.2/sandbox/index.mdx @@ -0,0 +1,726 @@ +--- +title: Sandbox +--- + + + + + + +## ChartType + +```python Python +class ChartType(str, enum.Enum) +``` + +Chart types + + +## ScaleType + +```python Python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + +## Chart + +```python Python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + + + + + +## Sandbox + +```python Python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +``` + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + +## OutputMessage + +```python Python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + +### line + +The output line. + + +### timestamp + +Unix epoch in nanoseconds + + +### error + +Whether the output is an error. + + +## ExecutionError + +```python Python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + +### name + +Name of the error. + + +### value + +Value of the error. + + +### traceback + +The raw traceback of the error. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + +## MIMEType + +```python Python +class MIMEType(str) +``` + +Represents a MIME type. + + +## Result + +```python Python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + +### extra + +Extra data that can be included. Not part of the standard types. + + +### formats + +```python Python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + +### \_\_str\_\_ + +```python Python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + +### \_repr\_html\_ + +```python Python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + +### \_repr\_markdown\_ + +```python Python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + +### \_repr\_svg\_ + +```python Python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + +### \_repr\_png\_ + +```python Python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + +### \_repr\_jpeg\_ + +```python Python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + +### \_repr\_pdf\_ + +```python Python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + +### \_repr\_latex\_ + +```python Python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + +### \_repr\_json\_ + +```python Python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + +### \_repr\_javascript\_ + +```python Python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + +## Logs + +```python Python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + +### serialize\_results + +```python Python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + +## Execution + +```python Python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + +### logs + +Logs printed to stdout and stderr during execution. + + +### error + +Error object if an error occurred, None otherwise. + + +### execution\_count + +Execution count of the cell. + + +### text + +```python Python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + +## Context + +```python Python +@dataclass +class Context() +``` + +Represents a context for code execution. + + +### id + +The ID of the context. + + +### language + +The language of the context. + + +### cwd + +The working directory of the context. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.3/sandbox/index.mdx new file mode 100644 index 0000000000..fdddff5e0a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.3/sandbox/index.mdx @@ -0,0 +1,726 @@ +--- +title: Sandbox +--- + + + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + +## Sandbox + +```python Python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +``` + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + + + +## ChartType + +```python Python +class ChartType(str, enum.Enum) +``` + +Chart types + + +## ScaleType + +```python Python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + +## Chart + +```python Python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + +## OutputMessage + +```python Python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + +### line + +The output line. + + +### timestamp + +Unix epoch in nanoseconds + + +### error + +Whether the output is an error. + + +## ExecutionError + +```python Python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + +### name + +Name of the error. + + +### value + +Value of the error. + + +### traceback + +The raw traceback of the error. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + +## MIMEType + +```python Python +class MIMEType(str) +``` + +Represents a MIME type. + + +## Result + +```python Python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + +### extra + +Extra data that can be included. Not part of the standard types. + + +### formats + +```python Python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + +### \_\_str\_\_ + +```python Python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + +### \_repr\_html\_ + +```python Python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + +### \_repr\_markdown\_ + +```python Python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + +### \_repr\_svg\_ + +```python Python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + +### \_repr\_png\_ + +```python Python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + +### \_repr\_jpeg\_ + +```python Python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + +### \_repr\_pdf\_ + +```python Python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + +### \_repr\_latex\_ + +```python Python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + +### \_repr\_json\_ + +```python Python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + +### \_repr\_javascript\_ + +```python Python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + +## Logs + +```python Python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + +### serialize\_results + +```python Python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + +## Execution + +```python Python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + +### logs + +Logs printed to stdout and stderr during execution. + + +### error + +Error object if an error occurred, None otherwise. + + +### execution\_count + +Execution count of the cell. + + +### text + +```python Python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + +## Context + +```python Python +@dataclass +class Context() +``` + +Represents a context for code execution. + + +### id + +The ID of the context. + + +### language + +The language of the context. + + +### cwd + +The working directory of the context. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.4/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.4/sandbox/index.mdx new file mode 100644 index 0000000000..5d65c408ca --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.4/sandbox/index.mdx @@ -0,0 +1,726 @@ +--- +title: Sandbox +--- + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + +## OutputMessage + +```python Python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + +### line + +The output line. + + +### timestamp + +Unix epoch in nanoseconds + + +### error + +Whether the output is an error. + + +## ExecutionError + +```python Python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + +### name + +Name of the error. + + +### value + +Value of the error. + + +### traceback + +The raw traceback of the error. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + +## MIMEType + +```python Python +class MIMEType(str) +``` + +Represents a MIME type. + + +## Result + +```python Python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + +### extra + +Extra data that can be included. Not part of the standard types. + + +### formats + +```python Python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + +### \_\_str\_\_ + +```python Python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + +### \_repr\_html\_ + +```python Python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + +### \_repr\_markdown\_ + +```python Python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + +### \_repr\_svg\_ + +```python Python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + +### \_repr\_png\_ + +```python Python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + +### \_repr\_jpeg\_ + +```python Python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + +### \_repr\_pdf\_ + +```python Python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + +### \_repr\_latex\_ + +```python Python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + +### \_repr\_json\_ + +```python Python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + +### \_repr\_javascript\_ + +```python Python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + +## Logs + +```python Python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + +### serialize\_results + +```python Python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + +## Execution + +```python Python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + +### logs + +Logs printed to stdout and stderr during execution. + + +### error + +Error object if an error occurred, None otherwise. + + +### execution\_count + +Execution count of the cell. + + +### text + +```python Python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + +## Context + +```python Python +@dataclass +class Context() +``` + +Represents a context for code execution. + + +### id + +The ID of the context. + + +### language + +The language of the context. + + +### cwd + +The working directory of the context. + + + + +## ChartType + +```python Python +class ChartType(str, enum.Enum) +``` + +Chart types + + +## ScaleType + +```python Python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + +## Chart + +```python Python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + +## Sandbox + +```python Python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +``` + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.5/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.5/sandbox/index.mdx new file mode 100644 index 0000000000..16bfcb97e5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.0.5/sandbox/index.mdx @@ -0,0 +1,726 @@ +--- +title: Sandbox +--- + + + + + + +## OutputMessage + +```python Python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + +### line + +The output line. + + +### timestamp + +Unix epoch in nanoseconds + + +### error + +Whether the output is an error. + + +## ExecutionError + +```python Python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + +### name + +Name of the error. + + +### value + +Value of the error. + + +### traceback + +The raw traceback of the error. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + +## MIMEType + +```python Python +class MIMEType(str) +``` + +Represents a MIME type. + + +## Result + +```python Python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + +### extra + +Extra data that can be included. Not part of the standard types. + + +### formats + +```python Python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + +### \_\_str\_\_ + +```python Python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + +### \_repr\_html\_ + +```python Python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + +### \_repr\_markdown\_ + +```python Python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + +### \_repr\_svg\_ + +```python Python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + +### \_repr\_png\_ + +```python Python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + +### \_repr\_jpeg\_ + +```python Python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + +### \_repr\_pdf\_ + +```python Python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + +### \_repr\_latex\_ + +```python Python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + +### \_repr\_json\_ + +```python Python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + +### \_repr\_javascript\_ + +```python Python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + +## Logs + +```python Python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + +### serialize\_results + +```python Python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + +## Execution + +```python Python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + +### logs + +Logs printed to stdout and stderr during execution. + + +### error + +Error object if an error occurred, None otherwise. + + +### execution\_count + +Execution count of the cell. + + +### text + +```python Python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + +## Context + +```python Python +@dataclass +class Context() +``` + +Represents a context for code execution. + + +### id + +The ID of the context. + + +### language + +The language of the context. + + +### cwd + +The working directory of the context. + + + + +## ChartType + +```python Python +class ChartType(str, enum.Enum) +``` + +Chart types + + +## ScaleType + +```python Python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + +## Chart + +```python Python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + +## Sandbox + +```python Python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +``` + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.1.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.1.0/sandbox/index.mdx new file mode 100644 index 0000000000..4322033e14 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.1.0/sandbox/index.mdx @@ -0,0 +1,726 @@ +--- +title: Sandbox +--- + + + + + + +## ChartType + +```python Python +class ChartType(str, enum.Enum) +``` + +Chart types + + +## ScaleType + +```python Python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + +## Chart + +```python Python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + + + +## OutputMessage + +```python Python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + +### line + +The output line. + + +### timestamp + +Unix epoch in nanoseconds + + +### error + +Whether the output is an error. + + +## ExecutionError + +```python Python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + +### name + +Name of the error. + + +### value + +Value of the error. + + +### traceback + +The raw traceback of the error. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + +## MIMEType + +```python Python +class MIMEType(str) +``` + +Represents a MIME type. + + +## Result + +```python Python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + +### extra + +Extra data that can be included. Not part of the standard types. + + +### formats + +```python Python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + +### \_\_str\_\_ + +```python Python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + +### \_repr\_html\_ + +```python Python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + +### \_repr\_markdown\_ + +```python Python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + +### \_repr\_svg\_ + +```python Python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + +### \_repr\_png\_ + +```python Python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + +### \_repr\_jpeg\_ + +```python Python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + +### \_repr\_pdf\_ + +```python Python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + +### \_repr\_latex\_ + +```python Python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + +### \_repr\_json\_ + +```python Python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + +### \_repr\_javascript\_ + +```python Python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + +## Logs + +```python Python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + +### serialize\_results + +```python Python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + +## Execution + +```python Python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + +### logs + +Logs printed to stdout and stderr during execution. + + +### error + +Error object if an error occurred, None otherwise. + + +### execution\_count + +Execution count of the cell. + + +### text + +```python Python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + +## Context + +```python Python +@dataclass +class Context() +``` + +Represents a context for code execution. + + +### id + +The ID of the context. + + +### language + +The language of the context. + + +### cwd + +The working directory of the context. + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + +## Sandbox + +```python Python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +``` + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.1.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.1.1/sandbox/index.mdx new file mode 100644 index 0000000000..4322033e14 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.1.1/sandbox/index.mdx @@ -0,0 +1,726 @@ +--- +title: Sandbox +--- + + + + + + +## ChartType + +```python Python +class ChartType(str, enum.Enum) +``` + +Chart types + + +## ScaleType + +```python Python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + +## Chart + +```python Python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + + + +## OutputMessage + +```python Python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + +### line + +The output line. + + +### timestamp + +Unix epoch in nanoseconds + + +### error + +Whether the output is an error. + + +## ExecutionError + +```python Python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + +### name + +Name of the error. + + +### value + +Value of the error. + + +### traceback + +The raw traceback of the error. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + +## MIMEType + +```python Python +class MIMEType(str) +``` + +Represents a MIME type. + + +## Result + +```python Python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + +### extra + +Extra data that can be included. Not part of the standard types. + + +### formats + +```python Python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + +### \_\_str\_\_ + +```python Python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + +### \_repr\_html\_ + +```python Python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + +### \_repr\_markdown\_ + +```python Python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + +### \_repr\_svg\_ + +```python Python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + +### \_repr\_png\_ + +```python Python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + +### \_repr\_jpeg\_ + +```python Python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + +### \_repr\_pdf\_ + +```python Python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + +### \_repr\_latex\_ + +```python Python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + +### \_repr\_json\_ + +```python Python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + +### \_repr\_javascript\_ + +```python Python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + +## Logs + +```python Python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + +### serialize\_results + +```python Python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + +## Execution + +```python Python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + +### logs + +Logs printed to stdout and stderr during execution. + + +### error + +Error object if an error occurred, None otherwise. + + +### execution\_count + +Execution count of the cell. + + +### text + +```python Python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + +## Context + +```python Python +@dataclass +class Context() +``` + +Represents a context for code execution. + + +### id + +The ID of the context. + + +### language + +The language of the context. + + +### cwd + +The working directory of the context. + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + +## Sandbox + +```python Python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +``` + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.2.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.2.0/sandbox/index.mdx new file mode 100644 index 0000000000..4322033e14 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.2.0/sandbox/index.mdx @@ -0,0 +1,726 @@ +--- +title: Sandbox +--- + + + + + + +## ChartType + +```python Python +class ChartType(str, enum.Enum) +``` + +Chart types + + +## ScaleType + +```python Python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + +## Chart + +```python Python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + + + +## OutputMessage + +```python Python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + +### line + +The output line. + + +### timestamp + +Unix epoch in nanoseconds + + +### error + +Whether the output is an error. + + +## ExecutionError + +```python Python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + +### name + +Name of the error. + + +### value + +Value of the error. + + +### traceback + +The raw traceback of the error. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + +## MIMEType + +```python Python +class MIMEType(str) +``` + +Represents a MIME type. + + +## Result + +```python Python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + +### extra + +Extra data that can be included. Not part of the standard types. + + +### formats + +```python Python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + +### \_\_str\_\_ + +```python Python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + +### \_repr\_html\_ + +```python Python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + +### \_repr\_markdown\_ + +```python Python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + +### \_repr\_svg\_ + +```python Python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + +### \_repr\_png\_ + +```python Python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + +### \_repr\_jpeg\_ + +```python Python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + +### \_repr\_pdf\_ + +```python Python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + +### \_repr\_latex\_ + +```python Python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + +### \_repr\_json\_ + +```python Python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + +### \_repr\_javascript\_ + +```python Python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + +## Logs + +```python Python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + +### serialize\_results + +```python Python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + +## Execution + +```python Python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + +### logs + +Logs printed to stdout and stderr during execution. + + +### error + +Error object if an error occurred, None otherwise. + + +### execution\_count + +Execution count of the cell. + + +### text + +```python Python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + +## Context + +```python Python +@dataclass +class Context() +``` + +Represents a context for code execution. + + +### id + +The ID of the context. + + +### language + +The language of the context. + + +### cwd + +The working directory of the context. + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + +## Sandbox + +```python Python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +``` + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.2.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.2.1/sandbox/index.mdx new file mode 100644 index 0000000000..829a22ec5c --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.2.1/sandbox/index.mdx @@ -0,0 +1,726 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +``` + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + + + +## ChartType + +```python Python +class ChartType(str, enum.Enum) +``` + +Chart types + + +## ScaleType + +```python Python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + +## Chart + +```python Python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + +## OutputMessage + +```python Python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + +### line + +The output line. + + +### timestamp + +Unix epoch in nanoseconds + + +### error + +Whether the output is an error. + + +## ExecutionError + +```python Python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + +### name + +Name of the error. + + +### value + +Value of the error. + + +### traceback + +The raw traceback of the error. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + +## MIMEType + +```python Python +class MIMEType(str) +``` + +Represents a MIME type. + + +## Result + +```python Python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + +### extra + +Extra data that can be included. Not part of the standard types. + + +### formats + +```python Python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + +### \_\_str\_\_ + +```python Python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + +### \_repr\_html\_ + +```python Python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + +### \_repr\_markdown\_ + +```python Python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + +### \_repr\_svg\_ + +```python Python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + +### \_repr\_png\_ + +```python Python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + +### \_repr\_jpeg\_ + +```python Python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + +### \_repr\_pdf\_ + +```python Python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + +### \_repr\_latex\_ + +```python Python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + +### \_repr\_json\_ + +```python Python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + +### \_repr\_javascript\_ + +```python Python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + +## Logs + +```python Python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + +### serialize\_results + +```python Python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + +## Execution + +```python Python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + +### logs + +Logs printed to stdout and stderr during execution. + + +### error + +Error object if an error occurred, None otherwise. + + +### execution\_count + +Execution count of the cell. + + +### text + +```python Python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + +## Context + +```python Python +@dataclass +class Context() +``` + +Represents a context for code execution. + + +### id + +The ID of the context. + + +### language + +The language of the context. + + +### cwd + +The working directory of the context. + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.5.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.5.0/sandbox/index.mdx new file mode 100644 index 0000000000..a721916527 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.5.0/sandbox/index.mdx @@ -0,0 +1,726 @@ +--- +title: Sandbox +--- + + + + + + +## OutputMessage + +```python Python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + +### line + +The output line. + + +### timestamp + +Unix epoch in nanoseconds + + +### error + +Whether the output is an error. + + +## ExecutionError + +```python Python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + +### name + +Name of the error. + + +### value + +Value of the error. + + +### traceback + +The raw traceback of the error. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + +## MIMEType + +```python Python +class MIMEType(str) +``` + +Represents a MIME type. + + +## Result + +```python Python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + +### extra + +Extra data that can be included. Not part of the standard types. + + +### formats + +```python Python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + +### \_\_str\_\_ + +```python Python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + +### \_repr\_html\_ + +```python Python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + +### \_repr\_markdown\_ + +```python Python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + +### \_repr\_svg\_ + +```python Python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + +### \_repr\_png\_ + +```python Python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + +### \_repr\_jpeg\_ + +```python Python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + +### \_repr\_pdf\_ + +```python Python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + +### \_repr\_latex\_ + +```python Python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + +### \_repr\_json\_ + +```python Python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + +### \_repr\_javascript\_ + +```python Python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + +## Logs + +```python Python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + +### serialize\_results + +```python Python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + +## Execution + +```python Python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + +### logs + +Logs printed to stdout and stderr during execution. + + +### error + +Error object if an error occurred, None otherwise. + + +### execution\_count + +Execution count of the cell. + + +### text + +```python Python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + +## Context + +```python Python +@dataclass +class Context() +``` + +Represents a context for code execution. + + +### id + +The ID of the context. + + +### language + +The language of the context. + + +### cwd + +The working directory of the context. + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + +## ChartType + +```python Python +class ChartType(str, enum.Enum) +``` + +Chart types + + +## ScaleType + +```python Python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + +## Chart + +```python Python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + + + +## Sandbox + +```python Python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +``` + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.5.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.5.1/sandbox/index.mdx new file mode 100644 index 0000000000..a721916527 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.5.1/sandbox/index.mdx @@ -0,0 +1,726 @@ +--- +title: Sandbox +--- + + + + + + +## OutputMessage + +```python Python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + +### line + +The output line. + + +### timestamp + +Unix epoch in nanoseconds + + +### error + +Whether the output is an error. + + +## ExecutionError + +```python Python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + +### name + +Name of the error. + + +### value + +Value of the error. + + +### traceback + +The raw traceback of the error. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + +## MIMEType + +```python Python +class MIMEType(str) +``` + +Represents a MIME type. + + +## Result + +```python Python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + +### extra + +Extra data that can be included. Not part of the standard types. + + +### formats + +```python Python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + +### \_\_str\_\_ + +```python Python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + +### \_repr\_html\_ + +```python Python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + +### \_repr\_markdown\_ + +```python Python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + +### \_repr\_svg\_ + +```python Python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + +### \_repr\_png\_ + +```python Python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + +### \_repr\_jpeg\_ + +```python Python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + +### \_repr\_pdf\_ + +```python Python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + +### \_repr\_latex\_ + +```python Python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + +### \_repr\_json\_ + +```python Python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + +### \_repr\_javascript\_ + +```python Python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + +## Logs + +```python Python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + +### serialize\_results + +```python Python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + +## Execution + +```python Python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + +### logs + +Logs printed to stdout and stderr during execution. + + +### error + +Error object if an error occurred, None otherwise. + + +### execution\_count + +Execution count of the cell. + + +### text + +```python Python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + +## Context + +```python Python +@dataclass +class Context() +``` + +Represents a context for code execution. + + +### id + +The ID of the context. + + +### language + +The language of the context. + + +### cwd + +The working directory of the context. + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + +## ChartType + +```python Python +class ChartType(str, enum.Enum) +``` + +Chart types + + +## ScaleType + +```python Python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + +## Chart + +```python Python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + + + +## Sandbox + +```python Python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +``` + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.5.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.5.2/sandbox/index.mdx new file mode 100644 index 0000000000..54295403b5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v1.5.2/sandbox/index.mdx @@ -0,0 +1,726 @@ +--- +title: Sandbox +--- + + + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + +## Sandbox + +```python Python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +``` + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + +## OutputMessage + +```python Python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + +### line + +The output line. + + +### timestamp + +Unix epoch in nanoseconds + + +### error + +Whether the output is an error. + + +## ExecutionError + +```python Python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + +### name + +Name of the error. + + +### value + +Value of the error. + + +### traceback + +The raw traceback of the error. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + +## MIMEType + +```python Python +class MIMEType(str) +``` + +Represents a MIME type. + + +## Result + +```python Python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + +### extra + +Extra data that can be included. Not part of the standard types. + + +### formats + +```python Python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + +### \_\_str\_\_ + +```python Python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + +### \_repr\_html\_ + +```python Python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + +### \_repr\_markdown\_ + +```python Python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + +### \_repr\_svg\_ + +```python Python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + +### \_repr\_png\_ + +```python Python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + +### \_repr\_jpeg\_ + +```python Python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + +### \_repr\_pdf\_ + +```python Python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + +### \_repr\_latex\_ + +```python Python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + +### \_repr\_json\_ + +```python Python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + +### \_repr\_javascript\_ + +```python Python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + +## Logs + +```python Python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + +### serialize\_results + +```python Python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + +## Execution + +```python Python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + +### logs + +Logs printed to stdout and stderr during execution. + + +### error + +Error object if an error occurred, None otherwise. + + +### execution\_count + +Execution count of the cell. + + +### text + +```python Python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + +## Context + +```python Python +@dataclass +class Context() +``` + +Represents a context for code execution. + + +### id + +The ID of the context. + + +### language + +The language of the context. + + +### cwd + +The working directory of the context. + + + + + + +## ChartType + +```python Python +class ChartType(str, enum.Enum) +``` + +Chart types + + +## ScaleType + +```python Python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + +## Chart + +```python Python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v2.0.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v2.0.0/sandbox/index.mdx new file mode 100644 index 0000000000..54b98fefb4 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/code-interpreter-python-sdk/v2.0.0/sandbox/index.mdx @@ -0,0 +1,726 @@ +--- +title: Sandbox +--- + + + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + +## Sandbox + +```python Python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() +``` + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### run\_code + +```python Python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + +### create\_code\_context + +```python Python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + +## OutputMessage + +```python Python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + +### line + +The output line. + + +### timestamp + +Unix epoch in nanoseconds + + +### error + +Whether the output is an error. + + +## ExecutionError + +```python Python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + +### name + +Name of the error. + + +### value + +Value of the error. + + +### traceback + +The raw traceback of the error. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + +## MIMEType + +```python Python +class MIMEType(str) +``` + +Represents a MIME type. + + +## Result + +```python Python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + +### extra + +Extra data that can be included. Not part of the standard types. + + +### formats + +```python Python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + +### \_\_str\_\_ + +```python Python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + +### \_repr\_html\_ + +```python Python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + +### \_repr\_markdown\_ + +```python Python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + +### \_repr\_svg\_ + +```python Python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + +### \_repr\_png\_ + +```python Python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + +### \_repr\_jpeg\_ + +```python Python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + +### \_repr\_pdf\_ + +```python Python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + +### \_repr\_latex\_ + +```python Python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + +### \_repr\_json\_ + +```python Python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + +### \_repr\_javascript\_ + +```python Python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + +## Logs + +```python Python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + +### serialize\_results + +```python Python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + +## Execution + +```python Python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + +### logs + +Logs printed to stdout and stderr during execution. + + +### error + +Error object if an error occurred, None otherwise. + + +### execution\_count + +Execution count of the cell. + + +### text + +```python Python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + +### to\_json + +```python Python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + +## Context + +```python Python +@dataclass +class Context() +``` + +Represents a context for code execution. + + +### id + +The ID of the context. + + +### language + +The language of the context. + + +### cwd + +The working directory of the context. + + + + + + +## ChartType + +```python Python +class ChartType(str, enum.Enum) +``` + +Chart types + + +## ScaleType + +```python Python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + +## Chart + +```python Python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.0.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.0.1/sandbox/index.mdx new file mode 100644 index 0000000000..b1ef54ed83 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.0.1/sandbox/index.mdx @@ -0,0 +1,418 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Methods + +### doubleClick() + +```ts +doubleClick(): Promise +``` + +Double left click on the current mouse position. + +###### Returns + +`Promise`\<`CommandResult`\> + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current mouse position. + +###### Returns + +`Promise`\<`object`\> + +An object with `x` and `y` coordinates. + +| Name | Type | +| ------ | ------ | +| `x` | `number` | +| `y` | `number` | + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`object`\> + +An object with `width` and `height` properties. + +| Name | Type | +| ------ | ------ | +| `height` | `number` | +| `width` | `number` | + +### getVideoStreamUrl() + +```ts +getVideoStreamUrl(): Promise +``` + +###### Returns + +`Promise`\<`string`\> + +### hotkey() + +```ts +hotkey(...keys: string[]): Promise +``` + +Press a hotkey. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| ...`keys` | `string`[] | The keys to press (e.g. `hotkey("ctrl", "c")` will press Ctrl+C). | + +###### Returns + +`Promise`\<`CommandResult`\> + +### leftClick() + +```ts +leftClick(): Promise +``` + +Left click on the current mouse position. + +###### Returns + +`Promise`\<`CommandResult`\> + +### middleClick() + +```ts +middleClick(): Promise +``` + +Middle click on the current mouse position. + +###### Returns + +`Promise`\<`CommandResult`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`CommandResult`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. +Note that you'll need to wait for the application to be opened. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +### press() + +```ts +press(key: string): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` | The key to press (e.g. "enter", "space", "backspace", etc.). | + +###### Returns + +`Promise`\<`CommandResult`\> + +### rightClick() + +```ts +rightClick(): Promise +``` + +Right click on the current mouse position. + +###### Returns + +`Promise`\<`CommandResult`\> + +### runPyautoguiCode() + +```ts +runPyautoguiCode(code: string, opts: object): Promise +``` + +Run the given Python code that uses pyautogui. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `code` | `string` | +| `opts` | `object` | +| `opts.onStderr`? | (`data`: `string`) => `void` | +| `opts.onStdout`? | (`data`: `string`) => `void` | + +###### Returns + +`Promise`\<`CommandResult`\> + +### scroll() + +```ts +scroll(amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `amount` | `number` | The amount to scroll. | + +###### Returns + +`Promise`\<`CommandResult`\> + +### takeScreenshot() + +###### takeScreenshot() + +```ts +takeScreenshot(): Promise +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\> + +A Uint8Array bytes representation of the screenshot. + +###### takeScreenshot(format) + +```ts +takeScreenshot(format: "bytes"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +A Uint8Array bytes representation of the screenshot. + +###### takeScreenshot(format) + +```ts +takeScreenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### takeScreenshot(format) + +```ts +takeScreenshot(format: "stream"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +A ReadableStream of bytes representation of the screenshot. + +### write() + +```ts +write(text: string): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | + +###### Returns + +`Promise`\<`CommandResult`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +#### Properties + +### onVideoStreamStart()? + +```ts +optional onVideoStreamStart: (url: string) => void; +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `url` | `string` | + +###### Returns + +`void` + +### videoStream? + +```ts +optional videoStream: boolean; +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.0.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.0.2/sandbox/index.mdx new file mode 100644 index 0000000000..b1ef54ed83 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.0.2/sandbox/index.mdx @@ -0,0 +1,418 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Methods + +### doubleClick() + +```ts +doubleClick(): Promise +``` + +Double left click on the current mouse position. + +###### Returns + +`Promise`\<`CommandResult`\> + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current mouse position. + +###### Returns + +`Promise`\<`object`\> + +An object with `x` and `y` coordinates. + +| Name | Type | +| ------ | ------ | +| `x` | `number` | +| `y` | `number` | + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`object`\> + +An object with `width` and `height` properties. + +| Name | Type | +| ------ | ------ | +| `height` | `number` | +| `width` | `number` | + +### getVideoStreamUrl() + +```ts +getVideoStreamUrl(): Promise +``` + +###### Returns + +`Promise`\<`string`\> + +### hotkey() + +```ts +hotkey(...keys: string[]): Promise +``` + +Press a hotkey. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| ...`keys` | `string`[] | The keys to press (e.g. `hotkey("ctrl", "c")` will press Ctrl+C). | + +###### Returns + +`Promise`\<`CommandResult`\> + +### leftClick() + +```ts +leftClick(): Promise +``` + +Left click on the current mouse position. + +###### Returns + +`Promise`\<`CommandResult`\> + +### middleClick() + +```ts +middleClick(): Promise +``` + +Middle click on the current mouse position. + +###### Returns + +`Promise`\<`CommandResult`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`CommandResult`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. +Note that you'll need to wait for the application to be opened. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +### press() + +```ts +press(key: string): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` | The key to press (e.g. "enter", "space", "backspace", etc.). | + +###### Returns + +`Promise`\<`CommandResult`\> + +### rightClick() + +```ts +rightClick(): Promise +``` + +Right click on the current mouse position. + +###### Returns + +`Promise`\<`CommandResult`\> + +### runPyautoguiCode() + +```ts +runPyautoguiCode(code: string, opts: object): Promise +``` + +Run the given Python code that uses pyautogui. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `code` | `string` | +| `opts` | `object` | +| `opts.onStderr`? | (`data`: `string`) => `void` | +| `opts.onStdout`? | (`data`: `string`) => `void` | + +###### Returns + +`Promise`\<`CommandResult`\> + +### scroll() + +```ts +scroll(amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `amount` | `number` | The amount to scroll. | + +###### Returns + +`Promise`\<`CommandResult`\> + +### takeScreenshot() + +###### takeScreenshot() + +```ts +takeScreenshot(): Promise +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\> + +A Uint8Array bytes representation of the screenshot. + +###### takeScreenshot(format) + +```ts +takeScreenshot(format: "bytes"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +A Uint8Array bytes representation of the screenshot. + +###### takeScreenshot(format) + +```ts +takeScreenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### takeScreenshot(format) + +```ts +takeScreenshot(format: "stream"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +A ReadableStream of bytes representation of the screenshot. + +### write() + +```ts +write(text: string): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | + +###### Returns + +`Promise`\<`CommandResult`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +#### Properties + +### onVideoStreamStart()? + +```ts +optional onVideoStreamStart: (url: string) => void; +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `url` | `string` | + +###### Returns + +`void` + +### videoStream? + +```ts +optional videoStream: boolean; +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.0.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.0.3/sandbox/index.mdx new file mode 100644 index 0000000000..39ee0fea71 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.0.3/sandbox/index.mdx @@ -0,0 +1,437 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `display` | `readonly` | `string` | +| `stream` | `readonly` | `VNCServer` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(): Promise +``` + +Double left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`null` \| `CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`null` \| `ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### leftClick() + +```ts +leftClick(): Promise +``` + +Left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(): Promise +``` + +Middle click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` | The key to press (e.g. "enter", "space", "backspace", etc.). | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(): Promise +``` + +Right click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### Call Signature + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### Call Signature + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### Call Signature + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### Call Signature + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "up" | "down", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"up"` \| `"down"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | \{ `chunkSize`: `number`; `delayInMs`: `number`; \} | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### Call Signature + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +``` + +###### Call Signature + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +``` + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### enableAuth? + +```ts +optional enableAuth: boolean; +``` + +Whether to enable authentication for noVNC connections. + +### port? + +```ts +optional port: number; +``` + +Port number for the noVNC proxy server. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. + +### vncPort? + +```ts +optional vncPort: number; +``` + +Port number for the VNC server. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.1.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.1.1/sandbox/index.mdx new file mode 100644 index 0000000000..39ee0fea71 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.1.1/sandbox/index.mdx @@ -0,0 +1,437 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `display` | `readonly` | `string` | +| `stream` | `readonly` | `VNCServer` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(): Promise +``` + +Double left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`null` \| `CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`null` \| `ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### leftClick() + +```ts +leftClick(): Promise +``` + +Left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(): Promise +``` + +Middle click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` | The key to press (e.g. "enter", "space", "backspace", etc.). | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(): Promise +``` + +Right click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### Call Signature + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### Call Signature + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### Call Signature + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### Call Signature + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "up" | "down", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"up"` \| `"down"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | \{ `chunkSize`: `number`; `delayInMs`: `number`; \} | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### Call Signature + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +``` + +###### Call Signature + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +``` + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### enableAuth? + +```ts +optional enableAuth: boolean; +``` + +Whether to enable authentication for noVNC connections. + +### port? + +```ts +optional port: number; +``` + +Port number for the noVNC proxy server. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. + +### vncPort? + +```ts +optional vncPort: number; +``` + +Port number for the VNC server. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.2.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.2.0/sandbox/index.mdx new file mode 100644 index 0000000000..4d976ab1fa --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.2.0/sandbox/index.mdx @@ -0,0 +1,437 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `display` | `readonly` | `string` | +| `stream` | `readonly` | `VNCServer` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(): Promise +``` + +Double left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### leftClick() + +```ts +leftClick(): Promise +``` + +Left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(): Promise +``` + +Middle click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` | The key to press (e.g. "enter", "space", "backspace", etc.). | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(): Promise +``` + +Right click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### Call Signature + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### Call Signature + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### Call Signature + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### Call Signature + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "up" | "down", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"up"` \| `"down"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | \{ `chunkSize`: `number`; `delayInMs`: `number`; \} | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### Call Signature + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +``` + +###### Call Signature + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +``` + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### enableAuth? + +```ts +optional enableAuth: boolean; +``` + +Whether to enable authentication for noVNC connections. + +### port? + +```ts +optional port: number; +``` + +Port number for the noVNC proxy server. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. + +### vncPort? + +```ts +optional vncPort: number; +``` + +Port number for the VNC server. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.3.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.3.0/sandbox/index.mdx new file mode 100644 index 0000000000..0a542abb3f --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.3.0/sandbox/index.mdx @@ -0,0 +1,413 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `display` | `readonly` | `string` | +| `stream` | `readonly` | `VNCServer` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(): Promise +``` + +Double left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### leftClick() + +```ts +leftClick(): Promise +``` + +Left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(): Promise +``` + +Middle click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` | The key to press (e.g. "enter", "space", "backspace", etc.). | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(): Promise +``` + +Right click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### Call Signature + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### Call Signature + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### Call Signature + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### Call Signature + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "up" | "down", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"up"` \| `"down"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | \{ `chunkSize`: `number`; `delayInMs`: `number`; \} | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### Call Signature + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +``` + +###### Call Signature + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +``` + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.4.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.4.0/sandbox/index.mdx new file mode 100644 index 0000000000..baff718b34 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.4.0/sandbox/index.mdx @@ -0,0 +1,446 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `display` | `readonly` | `string` | +| `stream` | `readonly` | `VNCServer` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(): Promise +``` + +Double left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### leftClick() + +```ts +leftClick(): Promise +``` + +Left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(): Promise +``` + +Middle click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(): Promise +``` + +Right click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "up" | "down", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"up"` \| `"down"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.5.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.5.0/sandbox/index.mdx new file mode 100644 index 0000000000..443f1e8360 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.5.0/sandbox/index.mdx @@ -0,0 +1,482 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `display` | `readonly` | `string` | +| `stream` | `readonly` | `VNCServer` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(): Promise +``` + +Double left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### leftClick() + +```ts +leftClick(): Promise +``` + +Left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(): Promise +``` + +Middle click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(): Promise +``` + +Right click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "up" | "down", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"up"` \| `"down"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.6.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.6.0/sandbox/index.mdx new file mode 100644 index 0000000000..443f1e8360 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.6.0/sandbox/index.mdx @@ -0,0 +1,482 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `display` | `readonly` | `string` | +| `stream` | `readonly` | `VNCServer` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(): Promise +``` + +Double left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### leftClick() + +```ts +leftClick(): Promise +``` + +Left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(): Promise +``` + +Middle click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(): Promise +``` + +Right click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "up" | "down", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"up"` \| `"down"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.6.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.6.1/sandbox/index.mdx new file mode 100644 index 0000000000..1670b16f2f --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.6.1/sandbox/index.mdx @@ -0,0 +1,482 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `display` | `readonly` | `string` | +| `stream` | `readonly` | `VNCServer` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(): Promise +``` + +Double left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### leftClick() + +```ts +leftClick(): Promise +``` + +Left click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(): Promise +``` + +Middle click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(): Promise +``` + +Right click on the current mouse position. + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.6.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.6.2/sandbox/index.mdx new file mode 100644 index 0000000000..ae727e3a0a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.6.2/sandbox/index.mdx @@ -0,0 +1,510 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `display` | `readonly` | `string` | +| `stream` | `readonly` | `VNCServer` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.7.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.7.0/sandbox/index.mdx new file mode 100644 index 0000000000..ae727e3a0a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.7.0/sandbox/index.mdx @@ -0,0 +1,510 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `display` | `readonly` | `string` | +| `stream` | `readonly` | `VNCServer` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.7.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.7.1/sandbox/index.mdx new file mode 100644 index 0000000000..ae727e3a0a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.7.1/sandbox/index.mdx @@ -0,0 +1,510 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `display` | `readonly` | `string` | +| `stream` | `readonly` | `VNCServer` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.7.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.7.2/sandbox/index.mdx new file mode 100644 index 0000000000..6a22ae391f --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.7.2/sandbox/index.mdx @@ -0,0 +1,564 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `display` | `readonly` | `string` | +| `stream` | `readonly` | `VNCServer` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getApplicationWindows() + +```ts +getApplicationWindows(application: string): Promise +``` + +Get the window ID of the window with the given title. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `application` | `string` | + +###### Returns + +`Promise`\<`string`[]\> + +The ID of the window. + +### getCurrentWindowId() + +```ts +getCurrentWindowId(): Promise +``` + +Get the current window ID. + +###### Returns + +`Promise`\<`string`\> + +The ID of the current window. + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### getWindowTitle() + +```ts +getWindowTitle(windowId: string): Promise +``` + +Get the title of the window with the given ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `windowId` | `string` | The ID of the window. | + +###### Returns + +`Promise`\<`string`\> + +The title of the window. + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.7.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.7.3/sandbox/index.mdx new file mode 100644 index 0000000000..6a22ae391f --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.7.3/sandbox/index.mdx @@ -0,0 +1,564 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `display` | `readonly` | `string` | +| `stream` | `readonly` | `VNCServer` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getApplicationWindows() + +```ts +getApplicationWindows(application: string): Promise +``` + +Get the window ID of the window with the given title. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `application` | `string` | + +###### Returns + +`Promise`\<`string`[]\> + +The ID of the window. + +### getCurrentWindowId() + +```ts +getCurrentWindowId(): Promise +``` + +Get the current window ID. + +###### Returns + +`Promise`\<`string`\> + +The ID of the current window. + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### getWindowTitle() + +```ts +getWindowTitle(windowId: string): Promise +``` + +Get the title of the window with the given ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `windowId` | `string` | The ID of the window. | + +###### Returns + +`Promise`\<`string`\> + +The title of the window. + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.8.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.8.0/sandbox/index.mdx new file mode 100644 index 0000000000..6a22ae391f --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.8.0/sandbox/index.mdx @@ -0,0 +1,564 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `display` | `readonly` | `string` | +| `stream` | `readonly` | `VNCServer` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getApplicationWindows() + +```ts +getApplicationWindows(application: string): Promise +``` + +Get the window ID of the window with the given title. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `application` | `string` | + +###### Returns + +`Promise`\<`string`[]\> + +The ID of the window. + +### getCurrentWindowId() + +```ts +getCurrentWindowId(): Promise +``` + +Get the current window ID. + +###### Returns + +`Promise`\<`string`\> + +The ID of the current window. + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### getWindowTitle() + +```ts +getWindowTitle(windowId: string): Promise +``` + +Get the title of the window with the given ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `windowId` | `string` | The ID of the window. | + +###### Returns + +`Promise`\<`string`\> + +The title of the window. + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.8.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.8.1/sandbox/index.mdx new file mode 100644 index 0000000000..903a295cfb --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.8.1/sandbox/index.mdx @@ -0,0 +1,564 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | Default value | +| ------ | ------ | ------ | ------ | +| `display` | `public` | `string` | `':0'` | +| `stream` | `public` | `VNCServer` | `undefined` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getApplicationWindows() + +```ts +getApplicationWindows(application: string): Promise +``` + +Get the window ID of the window with the given title. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `application` | `string` | + +###### Returns + +`Promise`\<`string`[]\> + +The ID of the window. + +### getCurrentWindowId() + +```ts +getCurrentWindowId(): Promise +``` + +Get the current window ID. + +###### Returns + +`Promise`\<`string`\> + +The ID of the current window. + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### getWindowTitle() + +```ts +getWindowTitle(windowId: string): Promise +``` + +Get the title of the window with the given ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `windowId` | `string` | The ID of the window. | + +###### Returns + +`Promise`\<`string`\> + +The title of the window. + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.9.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.9.0/sandbox/index.mdx new file mode 100644 index 0000000000..2373e30e4a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.9.0/sandbox/index.mdx @@ -0,0 +1,583 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | Default value | +| ------ | ------ | ------ | ------ | +| `display` | `public` | `string` | `':0'` | +| `stream` | `public` | `VNCServer` | `undefined` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getApplicationWindows() + +```ts +getApplicationWindows(application: string): Promise +``` + +Get the window ID of the window with the given title. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `application` | `string` | + +###### Returns + +`Promise`\<`string`[]\> + +The ID of the window. + +### getCurrentWindowId() + +```ts +getCurrentWindowId(): Promise +``` + +Get the current window ID. + +###### Returns + +`Promise`\<`string`\> + +The ID of the current window. + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### getWindowTitle() + +```ts +getWindowTitle(windowId: string): Promise +``` + +Get the title of the window with the given ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `windowId` | `string` | The ID of the window. | + +###### Returns + +`Promise`\<`string`\> + +The title of the window. + +### launch() + +```ts +launch(application: string, uri?: string): Promise +``` + +Launch an application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `application` | `string` | The application to launch. | +| `uri`? | `string` | The URI to open in the application. | + +###### Returns + +`Promise`\<`void`\> + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.9.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.9.1/sandbox/index.mdx new file mode 100644 index 0000000000..2373e30e4a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.9.1/sandbox/index.mdx @@ -0,0 +1,583 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | Default value | +| ------ | ------ | ------ | ------ | +| `display` | `public` | `string` | `':0'` | +| `stream` | `public` | `VNCServer` | `undefined` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getApplicationWindows() + +```ts +getApplicationWindows(application: string): Promise +``` + +Get the window ID of the window with the given title. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `application` | `string` | + +###### Returns + +`Promise`\<`string`[]\> + +The ID of the window. + +### getCurrentWindowId() + +```ts +getCurrentWindowId(): Promise +``` + +Get the current window ID. + +###### Returns + +`Promise`\<`string`\> + +The ID of the current window. + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### getWindowTitle() + +```ts +getWindowTitle(windowId: string): Promise +``` + +Get the title of the window with the given ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `windowId` | `string` | The ID of the window. | + +###### Returns + +`Promise`\<`string`\> + +The title of the window. + +### launch() + +```ts +launch(application: string, uri?: string): Promise +``` + +Launch an application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `application` | `string` | The application to launch. | +| `uri`? | `string` | The URI to open in the application. | + +###### Returns + +`Promise`\<`void`\> + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.9.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.9.2/sandbox/index.mdx new file mode 100644 index 0000000000..2373e30e4a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v1.9.2/sandbox/index.mdx @@ -0,0 +1,583 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | Default value | +| ------ | ------ | ------ | ------ | +| `display` | `public` | `string` | `':0'` | +| `stream` | `public` | `VNCServer` | `undefined` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getApplicationWindows() + +```ts +getApplicationWindows(application: string): Promise +``` + +Get the window ID of the window with the given title. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `application` | `string` | + +###### Returns + +`Promise`\<`string`[]\> + +The ID of the window. + +### getCurrentWindowId() + +```ts +getCurrentWindowId(): Promise +``` + +Get the current window ID. + +###### Returns + +`Promise`\<`string`\> + +The ID of the current window. + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### getWindowTitle() + +```ts +getWindowTitle(windowId: string): Promise +``` + +Get the title of the window with the given ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `windowId` | `string` | The ID of the window. | + +###### Returns + +`Promise`\<`string`\> + +The title of the window. + +### launch() + +```ts +launch(application: string, uri?: string): Promise +``` + +Launch an application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `application` | `string` | The application to launch. | +| `uri`? | `string` | The URI to open in the application. | + +###### Returns + +`Promise`\<`void`\> + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v2.0.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v2.0.0/sandbox/index.mdx new file mode 100644 index 0000000000..71ba9f0fa5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v2.0.0/sandbox/index.mdx @@ -0,0 +1,696 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | Default value | +| ------ | ------ | ------ | ------ | +| `display` | `public` | `string` | `':0'` | +| `stream` | `public` | `VNCServer` | `undefined` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getApplicationWindows() + +```ts +getApplicationWindows(application: string): Promise +``` + +Get the window ID of the window with the given title. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `application` | `string` | + +###### Returns + +`Promise`\<`string`[]\> + +The ID of the window. + +### getCurrentWindowId() + +```ts +getCurrentWindowId(): Promise +``` + +Get the current window ID. + +###### Returns + +`Promise`\<`string`\> + +The ID of the current window. + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### getWindowTitle() + +```ts +getWindowTitle(windowId: string): Promise +``` + +Get the title of the window with the given ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `windowId` | `string` | The ID of the window. | + +###### Returns + +`Promise`\<`string`\> + +The title of the window. + +### launch() + +```ts +launch(application: string, uri?: string): Promise +``` + +Launch an application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `application` | `string` | The application to launch. | +| `uri`? | `string` | The URI to open in the application. | + +###### Returns + +`Promise`\<`void`\> + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxBetaCreateOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. + +*** + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v2.0.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v2.0.1/sandbox/index.mdx new file mode 100644 index 0000000000..71ba9f0fa5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-js-sdk/v2.0.1/sandbox/index.mdx @@ -0,0 +1,696 @@ +--- +title: Sandbox +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | Default value | +| ------ | ------ | ------ | ------ | +| `display` | `public` | `string` | `':0'` | +| `stream` | `public` | `VNCServer` | `undefined` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getApplicationWindows() + +```ts +getApplicationWindows(application: string): Promise +``` + +Get the window ID of the window with the given title. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `application` | `string` | + +###### Returns + +`Promise`\<`string`[]\> + +The ID of the window. + +### getCurrentWindowId() + +```ts +getCurrentWindowId(): Promise +``` + +Get the current window ID. + +###### Returns + +`Promise`\<`string`\> + +The ID of the current window. + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### getWindowTitle() + +```ts +getWindowTitle(windowId: string): Promise +``` + +Get the title of the window with the given ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `windowId` | `string` | The ID of the window. | + +###### Returns + +`Promise`\<`string`\> + +The title of the window. + +### launch() + +```ts +launch(application: string, uri?: string): Promise +``` + +Launch an application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `application` | `string` | The application to launch. | +| `uri`? | `string` | The URI to open in the application. | + +###### Returns + +`Promise`\<`void`\> + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxBetaCreateOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. + +*** + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.0.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.0.1/sandbox/index.mdx new file mode 100644 index 0000000000..ff51d7b863 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.0.1/sandbox/index.mdx @@ -0,0 +1,202 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### get\_video\_stream\_url + +```python Python +def get_video_stream_url() +``` + +Get the video stream URL. + + +### take\_screenshot + +```python Python +@overload +def take_screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### take\_screenshot + +```python Python +@overload +def take_screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### take\_screenshot + +```python Python +def take_screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click() +``` + +Left click on the current mouse position. + + +### double\_click + +```python Python +def double_click() +``` + +Double left click on the current mouse position. + + +### right\_click + +```python Python +def right_click() +``` + +Right click on the current mouse position. + + +### middle\_click + +```python Python +def middle_click() +``` + +Middle click on the current mouse position. + + +### scroll + +```python Python +def scroll(amount: int) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() +``` + +Get the current cursor position. + +**Returns**: + +A tuple with the x and y coordinates. + + +### get\_screen\_size + +```python Python +def get_screen_size() +``` + +Get the current screen size. + +**Returns**: + +A tuple with the width and height. + + +### write + +```python Python +def write(text: str) +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. + + +### press + +```python Python +def press(key: str) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### hotkey + +```python Python +def hotkey(*keys) +``` + +Press a hotkey. + +**Arguments**: + +- `keys`: The keys to press (e.g. `hotkey("ctrl", "c")` will press Ctrl+C). + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.0.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.0.2/sandbox/index.mdx new file mode 100644 index 0000000000..5f62c71f32 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.0.2/sandbox/index.mdx @@ -0,0 +1,232 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click() +``` + +Left click on the current mouse position. + + +### double\_click + +```python Python +def double_click() +``` + +Double left click on the current mouse position. + + +### right\_click + +```python Python +def right_click() +``` + +Right click on the current mouse position. + + +### middle\_click + +```python Python +def middle_click() +``` + +Middle click on the current mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: str) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.0.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.0.3/sandbox/index.mdx new file mode 100644 index 0000000000..5f62c71f32 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.0.3/sandbox/index.mdx @@ -0,0 +1,232 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click() +``` + +Left click on the current mouse position. + + +### double\_click + +```python Python +def double_click() +``` + +Double left click on the current mouse position. + + +### right\_click + +```python Python +def right_click() +``` + +Right click on the current mouse position. + + +### middle\_click + +```python Python +def middle_click() +``` + +Middle click on the current mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: str) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.1.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.1.1/sandbox/index.mdx new file mode 100644 index 0000000000..5f62c71f32 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.1.1/sandbox/index.mdx @@ -0,0 +1,232 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click() +``` + +Left click on the current mouse position. + + +### double\_click + +```python Python +def double_click() +``` + +Double left click on the current mouse position. + + +### right\_click + +```python Python +def right_click() +``` + +Right click on the current mouse position. + + +### middle\_click + +```python Python +def middle_click() +``` + +Middle click on the current mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: str) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.2.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.2.0/sandbox/index.mdx new file mode 100644 index 0000000000..5f62c71f32 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.2.0/sandbox/index.mdx @@ -0,0 +1,232 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click() +``` + +Left click on the current mouse position. + + +### double\_click + +```python Python +def double_click() +``` + +Double left click on the current mouse position. + + +### right\_click + +```python Python +def right_click() +``` + +Right click on the current mouse position. + + +### middle\_click + +```python Python +def middle_click() +``` + +Middle click on the current mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: str) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.3.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.3.0/sandbox/index.mdx new file mode 100644 index 0000000000..ed97f6019f --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.3.0/sandbox/index.mdx @@ -0,0 +1,259 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click() +``` + +Left click on the current mouse position. + + +### double\_click + +```python Python +def double_click() +``` + +Double left click on the current mouse position. + + +### right\_click + +```python Python +def right_click() +``` + +Right click on the current mouse position. + + +### middle\_click + +```python Python +def middle_click() +``` + +Middle click on the current mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: str | list[str]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.4.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.4.0/sandbox/index.mdx new file mode 100644 index 0000000000..9759864ac8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.4.0/sandbox/index.mdx @@ -0,0 +1,277 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click() +``` + +Left click on the current mouse position. + + +### double\_click + +```python Python +def double_click() +``` + +Double left click on the current mouse position. + + +### right\_click + +```python Python +def right_click() +``` + +Right click on the current mouse position. + + +### middle\_click + +```python Python +def middle_click() +``` + +Middle click on the current mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: str | list[str]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.5.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.5.0/sandbox/index.mdx new file mode 100644 index 0000000000..9759864ac8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.5.0/sandbox/index.mdx @@ -0,0 +1,277 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click() +``` + +Left click on the current mouse position. + + +### double\_click + +```python Python +def double_click() +``` + +Double left click on the current mouse position. + + +### right\_click + +```python Python +def right_click() +``` + +Right click on the current mouse position. + + +### middle\_click + +```python Python +def middle_click() +``` + +Middle click on the current mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: str | list[str]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.5.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.5.1/sandbox/index.mdx new file mode 100644 index 0000000000..9759864ac8 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.5.1/sandbox/index.mdx @@ -0,0 +1,277 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click() +``` + +Left click on the current mouse position. + + +### double\_click + +```python Python +def double_click() +``` + +Double left click on the current mouse position. + + +### right\_click + +```python Python +def right_click() +``` + +Right click on the current mouse position. + + +### middle\_click + +```python Python +def middle_click() +``` + +Middle click on the current mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: str | list[str]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.5.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.5.2/sandbox/index.mdx new file mode 100644 index 0000000000..645b4cae88 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.5.2/sandbox/index.mdx @@ -0,0 +1,268 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + +### double\_click + +```python Python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + +### middle\_click + +```python Python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: str | list[str]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.0/sandbox/index.mdx new file mode 100644 index 0000000000..645b4cae88 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.0/sandbox/index.mdx @@ -0,0 +1,268 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + +### double\_click + +```python Python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + +### middle\_click + +```python Python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: str | list[str]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.1/sandbox/index.mdx new file mode 100644 index 0000000000..645b4cae88 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.1/sandbox/index.mdx @@ -0,0 +1,268 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + +### double\_click + +```python Python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + +### middle\_click + +```python Python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: str | list[str]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.2/sandbox/index.mdx new file mode 100644 index 0000000000..7a05510280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.2/sandbox/index.mdx @@ -0,0 +1,295 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + +### double\_click + +```python Python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + +### middle\_click + +```python Python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: str | list[str]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + +### get\_current\_window\_id + +```python Python +def get_current_window_id() -> str +``` + +Get the current window ID. + + +### get\_application\_windows + +```python Python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + +### get\_window\_title + +```python Python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.3/sandbox/index.mdx new file mode 100644 index 0000000000..7a05510280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.3/sandbox/index.mdx @@ -0,0 +1,295 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + +### double\_click + +```python Python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + +### middle\_click + +```python Python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: str | list[str]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + +### get\_current\_window\_id + +```python Python +def get_current_window_id() -> str +``` + +Get the current window ID. + + +### get\_application\_windows + +```python Python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + +### get\_window\_title + +```python Python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.4/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.4/sandbox/index.mdx new file mode 100644 index 0000000000..a12307964b --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.4/sandbox/index.mdx @@ -0,0 +1,295 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + +### double\_click + +```python Python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + +### middle\_click + +```python Python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: Union[str, list[str]]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + +### get\_current\_window\_id + +```python Python +def get_current_window_id() -> str +``` + +Get the current window ID. + + +### get\_application\_windows + +```python Python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + +### get\_window\_title + +```python Python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.5/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.5/sandbox/index.mdx new file mode 100644 index 0000000000..a12307964b --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.6.5/sandbox/index.mdx @@ -0,0 +1,295 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + +### double\_click + +```python Python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + +### middle\_click + +```python Python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: Union[str, list[str]]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + +### get\_current\_window\_id + +```python Python +def get_current_window_id() -> str +``` + +Get the current window ID. + + +### get\_application\_windows + +```python Python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + +### get\_window\_title + +```python Python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.0/sandbox/index.mdx new file mode 100644 index 0000000000..3abd981c69 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.0/sandbox/index.mdx @@ -0,0 +1,304 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + +### double\_click + +```python Python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + +### middle\_click + +```python Python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: Union[str, list[str]]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + +### get\_current\_window\_id + +```python Python +def get_current_window_id() -> str +``` + +Get the current window ID. + + +### get\_application\_windows + +```python Python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + +### get\_window\_title + +```python Python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + + +### launch + +```python Python +def launch(application: str, uri: Optional[str] = None) +``` + +Launch an application. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.1/sandbox/index.mdx new file mode 100644 index 0000000000..3abd981c69 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.1/sandbox/index.mdx @@ -0,0 +1,304 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + +### double\_click + +```python Python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + +### middle\_click + +```python Python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: Union[str, list[str]]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + +### get\_current\_window\_id + +```python Python +def get_current_window_id() -> str +``` + +Get the current window ID. + + +### get\_application\_windows + +```python Python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + +### get\_window\_title + +```python Python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + + +### launch + +```python Python +def launch(application: str, uri: Optional[str] = None) +``` + +Launch an application. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.2/sandbox/index.mdx new file mode 100644 index 0000000000..0999d909c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.2/sandbox/index.mdx @@ -0,0 +1,306 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the requests made to the returned sandbox + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + +### double\_click + +```python Python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + +### middle\_click + +```python Python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: Union[str, list[str]]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + +### get\_current\_window\_id + +```python Python +def get_current_window_id() -> str +``` + +Get the current window ID. + + +### get\_application\_windows + +```python Python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + +### get\_window\_title + +```python Python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + + +### launch + +```python Python +def launch(application: str, uri: Optional[str] = None) +``` + +Launch an application. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.3/sandbox/index.mdx new file mode 100644 index 0000000000..0999d909c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.3/sandbox/index.mdx @@ -0,0 +1,306 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the requests made to the returned sandbox + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + +### double\_click + +```python Python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + +### middle\_click + +```python Python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: Union[str, list[str]]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + +### get\_current\_window\_id + +```python Python +def get_current_window_id() -> str +``` + +Get the current window ID. + + +### get\_application\_windows + +```python Python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + +### get\_window\_title + +```python Python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + + +### launch + +```python Python +def launch(application: str, uri: Optional[str] = None) +``` + +Launch an application. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.4/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.4/sandbox/index.mdx new file mode 100644 index 0000000000..0999d909c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v1.7.4/sandbox/index.mdx @@ -0,0 +1,306 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### \_\_init\_\_ + +```python Python +def __init__(resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new desktop sandbox. + +By default, the sandbox is created from the `desktop` template. + +**Arguments**: + +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: If True, the sandbox will be created in debug mode, defaults to `E2B_DEBUG` environment variable +- `sandbox_id`: Sandbox ID to connect to, defaults to `E2B_SANDBOX_ID` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the requests made to the returned sandbox + +**Returns**: + +sandbox instance for the new sandbox + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + +### double\_click + +```python Python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + +### middle\_click + +```python Python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: Union[str, list[str]]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + +### get\_current\_window\_id + +```python Python +def get_current_window_id() -> str +``` + +Get the current window ID. + + +### get\_application\_windows + +```python Python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + +### get\_window\_title + +```python Python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + + +### launch + +```python Python +def launch(application: str, uri: Optional[str] = None) +``` + +Launch an application. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v2.0.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v2.0.0/sandbox/index.mdx new file mode 100644 index 0000000000..39877085d7 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v2.0.0/sandbox/index.mdx @@ -0,0 +1,345 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### create + +```python Python +@classmethod +def create(cls, + template: Optional[str] = None, + resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `desktop` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_create + +```python Python +@classmethod +def beta_create(cls, + template: Optional[str] = None, + resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + timeout: Optional[int] = None, + auto_pause: Optional[bool] = False, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = 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. + +Create a new sandbox. + +By default, the sandbox is created from the default `desktop` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + +### double\_click + +```python Python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + +### middle\_click + +```python Python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: Union[str, list[str]]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + +### get\_current\_window\_id + +```python Python +def get_current_window_id() -> str +``` + +Get the current window ID. + + +### get\_application\_windows + +```python Python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + +### get\_window\_title + +```python Python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + + +### launch + +```python Python +def launch(application: str, uri: Optional[str] = None) +``` + +Launch an application. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v2.0.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v2.0.1/sandbox/index.mdx new file mode 100644 index 0000000000..39877085d7 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/desktop-python-sdk/v2.0.1/sandbox/index.mdx @@ -0,0 +1,345 @@ +--- +title: Sandbox +--- + + + + + + +## Sandbox + +```python Python +class Sandbox(SandboxBase) +``` + + +### create + +```python Python +@classmethod +def create(cls, + template: Optional[str] = None, + resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `desktop` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_create + +```python Python +@classmethod +def beta_create(cls, + template: Optional[str] = None, + resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + timeout: Optional[int] = None, + auto_pause: Optional[bool] = False, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = 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. + +Create a new sandbox. + +By default, the sandbox is created from the default `desktop` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + +### screenshot + +```python Python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + +### screenshot + +```python Python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + +### left\_click + +```python Python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + +### double\_click + +```python Python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + +### middle\_click + +```python Python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + +### scroll + +```python Python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + +### move\_mouse + +```python Python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + +### mouse\_press + +```python Python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + +### mouse\_release + +```python Python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + +### get\_cursor\_position + +```python Python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + +### get\_screen\_size + +```python Python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + +### write + +```python Python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + +### press + +```python Python +def press(key: Union[str, list[str]]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + +### drag + +```python Python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + +### wait + +```python Python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + +### open + +```python Python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + +### get\_current\_window\_id + +```python Python +def get_current_window_id() -> str +``` + +Get the current window ID. + + +### get\_application\_windows + +```python Python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + +### get\_window\_title + +```python Python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + + +### launch + +```python Python +def launch(application: str, uri: Optional[str] = None) +``` + +Launch an application. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/index.mdx new file mode 100644 index 0000000000..9697eb718c --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/index.mdx @@ -0,0 +1,7 @@ +--- +title: SDK Reference +--- + +This is the SDK reference for the [E2B CLI & Core SDK](https://github.com/e2b-dev/e2b), [Code Interpreter SDK](https://github.com/e2b-dev/code-interpreter), and [Desktop Sandbox SDK](https://github.com/e2b-dev/desktop). + +The reference is intended to be limited to low-level descriptions of various programmatic functionality. If you’re just getting started with E2B, we would instead recommend looking at the [documentation]() first or to get started quickly with an example. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.0/errors/index.mdx new file mode 100644 index 0000000000..e2085f08de --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.0/errors/index.mdx @@ -0,0 +1,208 @@ +--- +title: Errors +--- + +## Classes + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +##### new AuthenticationError() + +> **new AuthenticationError**(`message`): `AuthenticationError` + +###### Parameters + +• **message**: `any` + +###### Returns + +`AuthenticationError` + +###### Defined in + +errors.ts:72 + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +##### new InvalidArgumentError() + +> **new InvalidArgumentError**(`message`): `InvalidArgumentError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`InvalidArgumentError` + +###### Defined in + +errors.ts:42 + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +##### new NotEnoughSpaceError() + +> **new NotEnoughSpaceError**(`message`): `NotEnoughSpaceError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`NotEnoughSpaceError` + +###### Defined in + +errors.ts:52 + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +##### new NotFoundError() + +> **new NotFoundError**(`message`): `NotFoundError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`NotFoundError` + +###### Defined in + +errors.ts:62 + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` + +#### Constructors + +##### new SandboxError() + +> **new SandboxError**(`message`): `SandboxError` + +###### Parameters + +• **message**: `any` + +###### Returns + +`SandboxError` + +###### Defined in + +errors.ts:14 + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +##### new TemplateError() + +> **new TemplateError**(`message`): `TemplateError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`TemplateError` + +###### Defined in + +errors.ts:82 + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +##### new TimeoutError() + +> **new TimeoutError**(`message`): `TimeoutError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`TimeoutError` + +###### Defined in + +errors.ts:32 + +## Functions + +### formatSandboxTimeoutError() + +> **formatSandboxTimeoutError**(`message`): `TimeoutError` + +#### Parameters + +• **message**: `string` + +#### Returns + +`TimeoutError` + +#### Defined in + +errors.ts:2 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.0/filesystem/index.mdx new file mode 100644 index 0000000000..88dd2dc55a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.0/filesystem/index.mdx @@ -0,0 +1,520 @@ +--- +title: Filesystem +--- + +## Enumerations + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +##### DIR + +> **DIR**: `"dir"` + +Filesystem object is a directory. + +###### Defined in + +sandbox/filesystem/index.ts:55 + +##### FILE + +> **FILE**: `"file"` + +Filesystem object is a file. + +###### Defined in + +sandbox/filesystem/index.ts:51 + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +##### new Filesystem() + +> **new Filesystem**(`transport`, `envdApi`, `connectionConfig`): `Filesystem` + +###### Parameters + +• **transport**: `Transport` + +• **envdApi**: `EnvdApiClient` + +• **connectionConfig**: `ConnectionConfig` + +###### Returns + +`Filesystem` + +###### Defined in + +sandbox/filesystem/index.ts:104 + +#### Methods + +##### exists() + +> **exists**(`path`, `opts`?): `Promise`\<`boolean`\> + +Check if a file or a directory exists. + +###### Parameters + +• **path**: `string` + +path to a file or a directory + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +###### Defined in + +sandbox/filesystem/index.ts:399 + +##### list() + +> **list**(`path`, `opts`?): `Promise`\<`EntryInfo`[]\> + +List entries in a directory. + +###### Parameters + +• **path**: `string` + +path to the directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +###### Defined in + +sandbox/filesystem/index.ts:270 + +##### makeDir() + +> **makeDir**(`path`, `opts`?): `Promise`\<`boolean`\> + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +• **path**: `string` + +path to a new directory. For example '/dirA/dirB' when creating 'dirB'. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +###### Defined in + +sandbox/filesystem/index.ts:308 + +##### read() + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`string`\> + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### Defined in + +sandbox/filesystem/index.ts:123 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`Uint8Array`\> + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### Defined in + +sandbox/filesystem/index.ts:138 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`Blob`\> + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### Defined in + +sandbox/filesystem/index.ts:153 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +###### Defined in + +sandbox/filesystem/index.ts:168 + +##### remove() + +> **remove**(`path`, `opts`?): `Promise`\<`void`\> + +Remove a file or directory. + +###### Parameters + +• **path**: `string` + +path to a file or directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/filesystem/index.ts:377 + +##### rename() + +> **rename**(`oldPath`, `newPath`, `opts`?): `Promise`\<`EntryInfo`\> + +Rename a file or directory. + +###### Parameters + +• **oldPath**: `string` + +path to the file or directory to rename. + +• **newPath**: `string` + +new path for the file or directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +###### Defined in + +sandbox/filesystem/index.ts:339 + +##### watchDir() + +> **watchDir**(`path`, `onEvent`, `opts`?): `Promise`\<`WatchHandle`\> + +Start watching a directory for filesystem events. + +###### Parameters + +• **path**: `string` + +path to directory to watch. + +• **onEvent** + +callback to call when an event in the directory occurs. + +• **opts?**: `WatchOpts` + +connection options. + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +###### Defined in + +sandbox/filesystem/index.ts:430 + +##### write() + +> **write**(`path`, `data`, `opts`?): `Promise`\<`EntryInfo`\> + +Write content to a file. + +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. + +###### Parameters + +• **path**: `string` + +path to file. + +• **data**: `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> + +data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### Defined in + +sandbox/filesystem/index.ts:224 + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +##### name + +> **name**: `string` + +Name of the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:33 + +##### path + +> **path**: `string` + +Path to the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:41 + +##### type? + +> `optional` **type**: `FileType` + +Type of the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:37 + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### user? + +> `optional` **user**: `Username` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +###### Defined in + +sandbox/filesystem/index.ts:76 + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +##### onExit()? + +> `optional` **onExit**: (`err`?) => `void` \| `Promise`\<`void`\> + +Callback to call when the watch operation stops. + +###### Parameters + +• **err?**: `Error` + +###### Returns + +`void` \| `Promise`\<`void`\> + +###### Defined in + +sandbox/filesystem/index.ts:93 + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### timeoutMs? + +> `optional` **timeoutMs**: `number` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +###### Defined in + +sandbox/filesystem/index.ts:89 + +##### user? + +> `optional` **user**: `Username` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +###### Defined in + +sandbox/filesystem/index.ts:76 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.0/sandbox/index.mdx new file mode 100644 index 0000000000..883aea6d33 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.0/sandbox/index.mdx @@ -0,0 +1,583 @@ +--- +title: Sandbox +--- + +## Classes + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +##### commands + +> `readonly` **commands**: `Commands` + +Module for running commands in the sandbox + +###### Defined in + +sandbox/index.ts:74 + +##### files + +> `readonly` **files**: `Filesystem` + +Module for interacting with the sandbox filesystem + +###### Defined in + +sandbox/index.ts:70 + +##### pty + +> `readonly` **pty**: `Pty` + +Module for interacting with the sandbox pseudo-terminals + +###### Defined in + +sandbox/index.ts:78 + +##### sandboxId + +> `readonly` **sandboxId**: `string` + +Unique identifier of the sandbox. + +###### Defined in + +sandbox/index.ts:83 + +#### Methods + +##### downloadUrl() + +> **downloadUrl**(`path`): `string` + +Get the URL to download a file from the sandbox. + +###### Parameters + +• **path**: `string` + +path to the file to download. + +###### Returns + +`string` + +URL for downloading file. + +###### Defined in + +sandbox/index.ts:339 + +##### getHost() + +> **getHost**(`port`): `string` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +• **port**: `number` + +number of the port in the sandbox. + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +`` + +###### Defined in + +sandbox/index.ts:237 + +##### isRunning() + +> **isRunning**(`opts`?): `Promise`\<`boolean`\> + +Check if the sandbox is running. + +###### Parameters + +• **opts?**: `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +###### Defined in + +sandbox/index.ts:259 + +##### kill() + +> **kill**(`opts`?): `Promise`\<`void`\> + +Kill the sandbox. + +###### Parameters + +• **opts?**: `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/index.ts:310 + +##### setTimeout() + +> **setTimeout**(`timeoutMs`, `opts`?): `Promise`\<`void`\> + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +• **timeoutMs**: `number` + +timeout in **milliseconds**. + +• **opts?**: `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/index.ts:290 + +##### uploadUrl() + +> **uploadUrl**(`path`?): `string` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +• **path?**: `string` + +the directory where to upload the file, defaults to user's home directory. + +###### Returns + +`string` + +URL for uploading file. + +###### Defined in + +sandbox/index.ts:328 + +##### connect() + +> `static` **connect**\<`S`\>(`this`, `sandboxId`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **sandboxId**: `string` + +sandbox ID. + +• **opts?**: `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +###### Defined in + +sandbox/index.ts:209 + +##### create() + +###### create(this, opts) + +> `static` **create**\<`S`\>(`this`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **opts?**: `SandboxOpts` + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### Defined in + +sandbox/index.ts:143 + +###### create(this, template, opts) + +> `static` **create**\<`S`\>(`this`, `template`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **template**: `string` + +sandbox template name or ID. + +• **opts?**: `SandboxOpts` + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +###### Defined in + +sandbox/index.ts:162 + +##### kill() + +> `static` **kill**(`sandboxId`, `opts`?): `Promise`\<`boolean`\> + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +• **sandboxId**: `string` + +sandbox ID. + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +###### Defined in + +sandbox/sandboxApi.ts:55 + +##### list() + +> `static` **list**(`opts`?): `Promise`\<`SandboxInfo`[]\> + +List all running sandboxes. + +###### Parameters + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +###### Defined in + +sandbox/sandboxApi.ts:90 + +##### setTimeout() + +> `static` **setTimeout**(`sandboxId`, `timeoutMs`, `opts`?): `Promise`\<`void`\> + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +• **sandboxId**: `string` + +sandbox ID. + +• **timeoutMs**: `number` + +timeout in **milliseconds**. + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/sandboxApi.ts:129 + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +##### accessToken? + +> `optional` **accessToken**: `string` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +###### Defined in + +connectionConfig.ts:24 + +##### apiKey? + +> `optional` **apiKey**: `string` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +###### Defined in + +connectionConfig.ts:18 + +##### debug? + +> `optional` **debug**: `boolean` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +###### Defined in + +connectionConfig.ts:36 + +##### domain? + +> `optional` **domain**: `string` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.dev` + +###### Defined in + +connectionConfig.ts:30 + +##### envs? + +> `optional` **envs**: `Record`\<`string`, `string`\> + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +###### Defined in + +sandbox/index.ts:32 + +##### logger? + +> `optional` **logger**: `Logger` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +###### Defined in + +connectionConfig.ts:46 + +##### metadata? + +> `optional` **metadata**: `Record`\<`string`, `string`\> + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +###### Defined in + +sandbox/index.ts:23 + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### timeoutMs? + +> `optional` **timeoutMs**: `number` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +###### Defined in + +sandbox/index.ts:39 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.1/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.1/errors/index.mdx new file mode 100644 index 0000000000..e2085f08de --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.1/errors/index.mdx @@ -0,0 +1,208 @@ +--- +title: Errors +--- + +## Classes + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +##### new AuthenticationError() + +> **new AuthenticationError**(`message`): `AuthenticationError` + +###### Parameters + +• **message**: `any` + +###### Returns + +`AuthenticationError` + +###### Defined in + +errors.ts:72 + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +##### new InvalidArgumentError() + +> **new InvalidArgumentError**(`message`): `InvalidArgumentError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`InvalidArgumentError` + +###### Defined in + +errors.ts:42 + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +##### new NotEnoughSpaceError() + +> **new NotEnoughSpaceError**(`message`): `NotEnoughSpaceError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`NotEnoughSpaceError` + +###### Defined in + +errors.ts:52 + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +##### new NotFoundError() + +> **new NotFoundError**(`message`): `NotFoundError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`NotFoundError` + +###### Defined in + +errors.ts:62 + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` + +#### Constructors + +##### new SandboxError() + +> **new SandboxError**(`message`): `SandboxError` + +###### Parameters + +• **message**: `any` + +###### Returns + +`SandboxError` + +###### Defined in + +errors.ts:14 + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +##### new TemplateError() + +> **new TemplateError**(`message`): `TemplateError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`TemplateError` + +###### Defined in + +errors.ts:82 + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +##### new TimeoutError() + +> **new TimeoutError**(`message`): `TimeoutError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`TimeoutError` + +###### Defined in + +errors.ts:32 + +## Functions + +### formatSandboxTimeoutError() + +> **formatSandboxTimeoutError**(`message`): `TimeoutError` + +#### Parameters + +• **message**: `string` + +#### Returns + +`TimeoutError` + +#### Defined in + +errors.ts:2 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.1/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.1/filesystem/index.mdx new file mode 100644 index 0000000000..88dd2dc55a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.1/filesystem/index.mdx @@ -0,0 +1,520 @@ +--- +title: Filesystem +--- + +## Enumerations + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +##### DIR + +> **DIR**: `"dir"` + +Filesystem object is a directory. + +###### Defined in + +sandbox/filesystem/index.ts:55 + +##### FILE + +> **FILE**: `"file"` + +Filesystem object is a file. + +###### Defined in + +sandbox/filesystem/index.ts:51 + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +##### new Filesystem() + +> **new Filesystem**(`transport`, `envdApi`, `connectionConfig`): `Filesystem` + +###### Parameters + +• **transport**: `Transport` + +• **envdApi**: `EnvdApiClient` + +• **connectionConfig**: `ConnectionConfig` + +###### Returns + +`Filesystem` + +###### Defined in + +sandbox/filesystem/index.ts:104 + +#### Methods + +##### exists() + +> **exists**(`path`, `opts`?): `Promise`\<`boolean`\> + +Check if a file or a directory exists. + +###### Parameters + +• **path**: `string` + +path to a file or a directory + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +###### Defined in + +sandbox/filesystem/index.ts:399 + +##### list() + +> **list**(`path`, `opts`?): `Promise`\<`EntryInfo`[]\> + +List entries in a directory. + +###### Parameters + +• **path**: `string` + +path to the directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +###### Defined in + +sandbox/filesystem/index.ts:270 + +##### makeDir() + +> **makeDir**(`path`, `opts`?): `Promise`\<`boolean`\> + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +• **path**: `string` + +path to a new directory. For example '/dirA/dirB' when creating 'dirB'. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +###### Defined in + +sandbox/filesystem/index.ts:308 + +##### read() + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`string`\> + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### Defined in + +sandbox/filesystem/index.ts:123 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`Uint8Array`\> + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### Defined in + +sandbox/filesystem/index.ts:138 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`Blob`\> + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### Defined in + +sandbox/filesystem/index.ts:153 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +###### Defined in + +sandbox/filesystem/index.ts:168 + +##### remove() + +> **remove**(`path`, `opts`?): `Promise`\<`void`\> + +Remove a file or directory. + +###### Parameters + +• **path**: `string` + +path to a file or directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/filesystem/index.ts:377 + +##### rename() + +> **rename**(`oldPath`, `newPath`, `opts`?): `Promise`\<`EntryInfo`\> + +Rename a file or directory. + +###### Parameters + +• **oldPath**: `string` + +path to the file or directory to rename. + +• **newPath**: `string` + +new path for the file or directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +###### Defined in + +sandbox/filesystem/index.ts:339 + +##### watchDir() + +> **watchDir**(`path`, `onEvent`, `opts`?): `Promise`\<`WatchHandle`\> + +Start watching a directory for filesystem events. + +###### Parameters + +• **path**: `string` + +path to directory to watch. + +• **onEvent** + +callback to call when an event in the directory occurs. + +• **opts?**: `WatchOpts` + +connection options. + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +###### Defined in + +sandbox/filesystem/index.ts:430 + +##### write() + +> **write**(`path`, `data`, `opts`?): `Promise`\<`EntryInfo`\> + +Write content to a file. + +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. + +###### Parameters + +• **path**: `string` + +path to file. + +• **data**: `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> + +data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### Defined in + +sandbox/filesystem/index.ts:224 + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +##### name + +> **name**: `string` + +Name of the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:33 + +##### path + +> **path**: `string` + +Path to the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:41 + +##### type? + +> `optional` **type**: `FileType` + +Type of the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:37 + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### user? + +> `optional` **user**: `Username` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +###### Defined in + +sandbox/filesystem/index.ts:76 + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +##### onExit()? + +> `optional` **onExit**: (`err`?) => `void` \| `Promise`\<`void`\> + +Callback to call when the watch operation stops. + +###### Parameters + +• **err?**: `Error` + +###### Returns + +`void` \| `Promise`\<`void`\> + +###### Defined in + +sandbox/filesystem/index.ts:93 + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### timeoutMs? + +> `optional` **timeoutMs**: `number` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +###### Defined in + +sandbox/filesystem/index.ts:89 + +##### user? + +> `optional` **user**: `Username` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +###### Defined in + +sandbox/filesystem/index.ts:76 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.1/sandbox/index.mdx new file mode 100644 index 0000000000..883aea6d33 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.1/sandbox/index.mdx @@ -0,0 +1,583 @@ +--- +title: Sandbox +--- + +## Classes + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +##### commands + +> `readonly` **commands**: `Commands` + +Module for running commands in the sandbox + +###### Defined in + +sandbox/index.ts:74 + +##### files + +> `readonly` **files**: `Filesystem` + +Module for interacting with the sandbox filesystem + +###### Defined in + +sandbox/index.ts:70 + +##### pty + +> `readonly` **pty**: `Pty` + +Module for interacting with the sandbox pseudo-terminals + +###### Defined in + +sandbox/index.ts:78 + +##### sandboxId + +> `readonly` **sandboxId**: `string` + +Unique identifier of the sandbox. + +###### Defined in + +sandbox/index.ts:83 + +#### Methods + +##### downloadUrl() + +> **downloadUrl**(`path`): `string` + +Get the URL to download a file from the sandbox. + +###### Parameters + +• **path**: `string` + +path to the file to download. + +###### Returns + +`string` + +URL for downloading file. + +###### Defined in + +sandbox/index.ts:339 + +##### getHost() + +> **getHost**(`port`): `string` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +• **port**: `number` + +number of the port in the sandbox. + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +`` + +###### Defined in + +sandbox/index.ts:237 + +##### isRunning() + +> **isRunning**(`opts`?): `Promise`\<`boolean`\> + +Check if the sandbox is running. + +###### Parameters + +• **opts?**: `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +###### Defined in + +sandbox/index.ts:259 + +##### kill() + +> **kill**(`opts`?): `Promise`\<`void`\> + +Kill the sandbox. + +###### Parameters + +• **opts?**: `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/index.ts:310 + +##### setTimeout() + +> **setTimeout**(`timeoutMs`, `opts`?): `Promise`\<`void`\> + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +• **timeoutMs**: `number` + +timeout in **milliseconds**. + +• **opts?**: `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/index.ts:290 + +##### uploadUrl() + +> **uploadUrl**(`path`?): `string` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +• **path?**: `string` + +the directory where to upload the file, defaults to user's home directory. + +###### Returns + +`string` + +URL for uploading file. + +###### Defined in + +sandbox/index.ts:328 + +##### connect() + +> `static` **connect**\<`S`\>(`this`, `sandboxId`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **sandboxId**: `string` + +sandbox ID. + +• **opts?**: `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +###### Defined in + +sandbox/index.ts:209 + +##### create() + +###### create(this, opts) + +> `static` **create**\<`S`\>(`this`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **opts?**: `SandboxOpts` + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### Defined in + +sandbox/index.ts:143 + +###### create(this, template, opts) + +> `static` **create**\<`S`\>(`this`, `template`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **template**: `string` + +sandbox template name or ID. + +• **opts?**: `SandboxOpts` + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +###### Defined in + +sandbox/index.ts:162 + +##### kill() + +> `static` **kill**(`sandboxId`, `opts`?): `Promise`\<`boolean`\> + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +• **sandboxId**: `string` + +sandbox ID. + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +###### Defined in + +sandbox/sandboxApi.ts:55 + +##### list() + +> `static` **list**(`opts`?): `Promise`\<`SandboxInfo`[]\> + +List all running sandboxes. + +###### Parameters + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +###### Defined in + +sandbox/sandboxApi.ts:90 + +##### setTimeout() + +> `static` **setTimeout**(`sandboxId`, `timeoutMs`, `opts`?): `Promise`\<`void`\> + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +• **sandboxId**: `string` + +sandbox ID. + +• **timeoutMs**: `number` + +timeout in **milliseconds**. + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/sandboxApi.ts:129 + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +##### accessToken? + +> `optional` **accessToken**: `string` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +###### Defined in + +connectionConfig.ts:24 + +##### apiKey? + +> `optional` **apiKey**: `string` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +###### Defined in + +connectionConfig.ts:18 + +##### debug? + +> `optional` **debug**: `boolean` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +###### Defined in + +connectionConfig.ts:36 + +##### domain? + +> `optional` **domain**: `string` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.dev` + +###### Defined in + +connectionConfig.ts:30 + +##### envs? + +> `optional` **envs**: `Record`\<`string`, `string`\> + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +###### Defined in + +sandbox/index.ts:32 + +##### logger? + +> `optional` **logger**: `Logger` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +###### Defined in + +connectionConfig.ts:46 + +##### metadata? + +> `optional` **metadata**: `Record`\<`string`, `string`\> + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +###### Defined in + +sandbox/index.ts:23 + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### timeoutMs? + +> `optional` **timeoutMs**: `number` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +###### Defined in + +sandbox/index.ts:39 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.2/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.2/errors/index.mdx new file mode 100644 index 0000000000..e2085f08de --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.2/errors/index.mdx @@ -0,0 +1,208 @@ +--- +title: Errors +--- + +## Classes + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +##### new AuthenticationError() + +> **new AuthenticationError**(`message`): `AuthenticationError` + +###### Parameters + +• **message**: `any` + +###### Returns + +`AuthenticationError` + +###### Defined in + +errors.ts:72 + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +##### new InvalidArgumentError() + +> **new InvalidArgumentError**(`message`): `InvalidArgumentError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`InvalidArgumentError` + +###### Defined in + +errors.ts:42 + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +##### new NotEnoughSpaceError() + +> **new NotEnoughSpaceError**(`message`): `NotEnoughSpaceError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`NotEnoughSpaceError` + +###### Defined in + +errors.ts:52 + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +##### new NotFoundError() + +> **new NotFoundError**(`message`): `NotFoundError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`NotFoundError` + +###### Defined in + +errors.ts:62 + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` + +#### Constructors + +##### new SandboxError() + +> **new SandboxError**(`message`): `SandboxError` + +###### Parameters + +• **message**: `any` + +###### Returns + +`SandboxError` + +###### Defined in + +errors.ts:14 + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +##### new TemplateError() + +> **new TemplateError**(`message`): `TemplateError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`TemplateError` + +###### Defined in + +errors.ts:82 + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +##### new TimeoutError() + +> **new TimeoutError**(`message`): `TimeoutError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`TimeoutError` + +###### Defined in + +errors.ts:32 + +## Functions + +### formatSandboxTimeoutError() + +> **formatSandboxTimeoutError**(`message`): `TimeoutError` + +#### Parameters + +• **message**: `string` + +#### Returns + +`TimeoutError` + +#### Defined in + +errors.ts:2 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.2/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.2/filesystem/index.mdx new file mode 100644 index 0000000000..88dd2dc55a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.2/filesystem/index.mdx @@ -0,0 +1,520 @@ +--- +title: Filesystem +--- + +## Enumerations + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +##### DIR + +> **DIR**: `"dir"` + +Filesystem object is a directory. + +###### Defined in + +sandbox/filesystem/index.ts:55 + +##### FILE + +> **FILE**: `"file"` + +Filesystem object is a file. + +###### Defined in + +sandbox/filesystem/index.ts:51 + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +##### new Filesystem() + +> **new Filesystem**(`transport`, `envdApi`, `connectionConfig`): `Filesystem` + +###### Parameters + +• **transport**: `Transport` + +• **envdApi**: `EnvdApiClient` + +• **connectionConfig**: `ConnectionConfig` + +###### Returns + +`Filesystem` + +###### Defined in + +sandbox/filesystem/index.ts:104 + +#### Methods + +##### exists() + +> **exists**(`path`, `opts`?): `Promise`\<`boolean`\> + +Check if a file or a directory exists. + +###### Parameters + +• **path**: `string` + +path to a file or a directory + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +###### Defined in + +sandbox/filesystem/index.ts:399 + +##### list() + +> **list**(`path`, `opts`?): `Promise`\<`EntryInfo`[]\> + +List entries in a directory. + +###### Parameters + +• **path**: `string` + +path to the directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +###### Defined in + +sandbox/filesystem/index.ts:270 + +##### makeDir() + +> **makeDir**(`path`, `opts`?): `Promise`\<`boolean`\> + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +• **path**: `string` + +path to a new directory. For example '/dirA/dirB' when creating 'dirB'. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +###### Defined in + +sandbox/filesystem/index.ts:308 + +##### read() + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`string`\> + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### Defined in + +sandbox/filesystem/index.ts:123 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`Uint8Array`\> + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### Defined in + +sandbox/filesystem/index.ts:138 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`Blob`\> + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### Defined in + +sandbox/filesystem/index.ts:153 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +###### Defined in + +sandbox/filesystem/index.ts:168 + +##### remove() + +> **remove**(`path`, `opts`?): `Promise`\<`void`\> + +Remove a file or directory. + +###### Parameters + +• **path**: `string` + +path to a file or directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/filesystem/index.ts:377 + +##### rename() + +> **rename**(`oldPath`, `newPath`, `opts`?): `Promise`\<`EntryInfo`\> + +Rename a file or directory. + +###### Parameters + +• **oldPath**: `string` + +path to the file or directory to rename. + +• **newPath**: `string` + +new path for the file or directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +###### Defined in + +sandbox/filesystem/index.ts:339 + +##### watchDir() + +> **watchDir**(`path`, `onEvent`, `opts`?): `Promise`\<`WatchHandle`\> + +Start watching a directory for filesystem events. + +###### Parameters + +• **path**: `string` + +path to directory to watch. + +• **onEvent** + +callback to call when an event in the directory occurs. + +• **opts?**: `WatchOpts` + +connection options. + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +###### Defined in + +sandbox/filesystem/index.ts:430 + +##### write() + +> **write**(`path`, `data`, `opts`?): `Promise`\<`EntryInfo`\> + +Write content to a file. + +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. + +###### Parameters + +• **path**: `string` + +path to file. + +• **data**: `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> + +data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### Defined in + +sandbox/filesystem/index.ts:224 + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +##### name + +> **name**: `string` + +Name of the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:33 + +##### path + +> **path**: `string` + +Path to the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:41 + +##### type? + +> `optional` **type**: `FileType` + +Type of the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:37 + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### user? + +> `optional` **user**: `Username` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +###### Defined in + +sandbox/filesystem/index.ts:76 + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +##### onExit()? + +> `optional` **onExit**: (`err`?) => `void` \| `Promise`\<`void`\> + +Callback to call when the watch operation stops. + +###### Parameters + +• **err?**: `Error` + +###### Returns + +`void` \| `Promise`\<`void`\> + +###### Defined in + +sandbox/filesystem/index.ts:93 + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### timeoutMs? + +> `optional` **timeoutMs**: `number` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +###### Defined in + +sandbox/filesystem/index.ts:89 + +##### user? + +> `optional` **user**: `Username` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +###### Defined in + +sandbox/filesystem/index.ts:76 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.2/sandbox/index.mdx new file mode 100644 index 0000000000..883aea6d33 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.2/sandbox/index.mdx @@ -0,0 +1,583 @@ +--- +title: Sandbox +--- + +## Classes + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +##### commands + +> `readonly` **commands**: `Commands` + +Module for running commands in the sandbox + +###### Defined in + +sandbox/index.ts:74 + +##### files + +> `readonly` **files**: `Filesystem` + +Module for interacting with the sandbox filesystem + +###### Defined in + +sandbox/index.ts:70 + +##### pty + +> `readonly` **pty**: `Pty` + +Module for interacting with the sandbox pseudo-terminals + +###### Defined in + +sandbox/index.ts:78 + +##### sandboxId + +> `readonly` **sandboxId**: `string` + +Unique identifier of the sandbox. + +###### Defined in + +sandbox/index.ts:83 + +#### Methods + +##### downloadUrl() + +> **downloadUrl**(`path`): `string` + +Get the URL to download a file from the sandbox. + +###### Parameters + +• **path**: `string` + +path to the file to download. + +###### Returns + +`string` + +URL for downloading file. + +###### Defined in + +sandbox/index.ts:339 + +##### getHost() + +> **getHost**(`port`): `string` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +• **port**: `number` + +number of the port in the sandbox. + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +`` + +###### Defined in + +sandbox/index.ts:237 + +##### isRunning() + +> **isRunning**(`opts`?): `Promise`\<`boolean`\> + +Check if the sandbox is running. + +###### Parameters + +• **opts?**: `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +###### Defined in + +sandbox/index.ts:259 + +##### kill() + +> **kill**(`opts`?): `Promise`\<`void`\> + +Kill the sandbox. + +###### Parameters + +• **opts?**: `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/index.ts:310 + +##### setTimeout() + +> **setTimeout**(`timeoutMs`, `opts`?): `Promise`\<`void`\> + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +• **timeoutMs**: `number` + +timeout in **milliseconds**. + +• **opts?**: `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/index.ts:290 + +##### uploadUrl() + +> **uploadUrl**(`path`?): `string` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +• **path?**: `string` + +the directory where to upload the file, defaults to user's home directory. + +###### Returns + +`string` + +URL for uploading file. + +###### Defined in + +sandbox/index.ts:328 + +##### connect() + +> `static` **connect**\<`S`\>(`this`, `sandboxId`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **sandboxId**: `string` + +sandbox ID. + +• **opts?**: `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +###### Defined in + +sandbox/index.ts:209 + +##### create() + +###### create(this, opts) + +> `static` **create**\<`S`\>(`this`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **opts?**: `SandboxOpts` + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### Defined in + +sandbox/index.ts:143 + +###### create(this, template, opts) + +> `static` **create**\<`S`\>(`this`, `template`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **template**: `string` + +sandbox template name or ID. + +• **opts?**: `SandboxOpts` + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +###### Defined in + +sandbox/index.ts:162 + +##### kill() + +> `static` **kill**(`sandboxId`, `opts`?): `Promise`\<`boolean`\> + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +• **sandboxId**: `string` + +sandbox ID. + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +###### Defined in + +sandbox/sandboxApi.ts:55 + +##### list() + +> `static` **list**(`opts`?): `Promise`\<`SandboxInfo`[]\> + +List all running sandboxes. + +###### Parameters + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +###### Defined in + +sandbox/sandboxApi.ts:90 + +##### setTimeout() + +> `static` **setTimeout**(`sandboxId`, `timeoutMs`, `opts`?): `Promise`\<`void`\> + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +• **sandboxId**: `string` + +sandbox ID. + +• **timeoutMs**: `number` + +timeout in **milliseconds**. + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/sandboxApi.ts:129 + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +##### accessToken? + +> `optional` **accessToken**: `string` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +###### Defined in + +connectionConfig.ts:24 + +##### apiKey? + +> `optional` **apiKey**: `string` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +###### Defined in + +connectionConfig.ts:18 + +##### debug? + +> `optional` **debug**: `boolean` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +###### Defined in + +connectionConfig.ts:36 + +##### domain? + +> `optional` **domain**: `string` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.dev` + +###### Defined in + +connectionConfig.ts:30 + +##### envs? + +> `optional` **envs**: `Record`\<`string`, `string`\> + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +###### Defined in + +sandbox/index.ts:32 + +##### logger? + +> `optional` **logger**: `Logger` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +###### Defined in + +connectionConfig.ts:46 + +##### metadata? + +> `optional` **metadata**: `Record`\<`string`, `string`\> + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +###### Defined in + +sandbox/index.ts:23 + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### timeoutMs? + +> `optional` **timeoutMs**: `number` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +###### Defined in + +sandbox/index.ts:39 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.3/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.3/errors/index.mdx new file mode 100644 index 0000000000..8ae3f12010 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.3/errors/index.mdx @@ -0,0 +1,233 @@ +--- +title: Errors +--- + +## Classes + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +##### new AuthenticationError() + +> **new AuthenticationError**(`message`): `AuthenticationError` + +###### Parameters + +• **message**: `any` + +###### Returns + +`AuthenticationError` + +###### Defined in + +errors.ts:72 + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +##### new InvalidArgumentError() + +> **new InvalidArgumentError**(`message`): `InvalidArgumentError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`InvalidArgumentError` + +###### Defined in + +errors.ts:42 + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +##### new NotEnoughSpaceError() + +> **new NotEnoughSpaceError**(`message`): `NotEnoughSpaceError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`NotEnoughSpaceError` + +###### Defined in + +errors.ts:52 + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +##### new NotFoundError() + +> **new NotFoundError**(`message`): `NotFoundError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`NotFoundError` + +###### Defined in + +errors.ts:62 + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +##### new RateLimitError() + +> **new RateLimitError**(`message`): `RateLimitError` + +###### Parameters + +• **message**: `any` + +###### Returns + +`RateLimitError` + +###### Defined in + +errors.ts:92 + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +##### new SandboxError() + +> **new SandboxError**(`message`): `SandboxError` + +###### Parameters + +• **message**: `any` + +###### Returns + +`SandboxError` + +###### Defined in + +errors.ts:14 + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +##### new TemplateError() + +> **new TemplateError**(`message`): `TemplateError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`TemplateError` + +###### Defined in + +errors.ts:82 + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +##### new TimeoutError() + +> **new TimeoutError**(`message`): `TimeoutError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`TimeoutError` + +###### Defined in + +errors.ts:32 + +## Functions + +### formatSandboxTimeoutError() + +> **formatSandboxTimeoutError**(`message`): `TimeoutError` + +#### Parameters + +• **message**: `string` + +#### Returns + +`TimeoutError` + +#### Defined in + +errors.ts:2 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.3/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.3/filesystem/index.mdx new file mode 100644 index 0000000000..88dd2dc55a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.3/filesystem/index.mdx @@ -0,0 +1,520 @@ +--- +title: Filesystem +--- + +## Enumerations + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +##### DIR + +> **DIR**: `"dir"` + +Filesystem object is a directory. + +###### Defined in + +sandbox/filesystem/index.ts:55 + +##### FILE + +> **FILE**: `"file"` + +Filesystem object is a file. + +###### Defined in + +sandbox/filesystem/index.ts:51 + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +##### new Filesystem() + +> **new Filesystem**(`transport`, `envdApi`, `connectionConfig`): `Filesystem` + +###### Parameters + +• **transport**: `Transport` + +• **envdApi**: `EnvdApiClient` + +• **connectionConfig**: `ConnectionConfig` + +###### Returns + +`Filesystem` + +###### Defined in + +sandbox/filesystem/index.ts:104 + +#### Methods + +##### exists() + +> **exists**(`path`, `opts`?): `Promise`\<`boolean`\> + +Check if a file or a directory exists. + +###### Parameters + +• **path**: `string` + +path to a file or a directory + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +###### Defined in + +sandbox/filesystem/index.ts:399 + +##### list() + +> **list**(`path`, `opts`?): `Promise`\<`EntryInfo`[]\> + +List entries in a directory. + +###### Parameters + +• **path**: `string` + +path to the directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +###### Defined in + +sandbox/filesystem/index.ts:270 + +##### makeDir() + +> **makeDir**(`path`, `opts`?): `Promise`\<`boolean`\> + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +• **path**: `string` + +path to a new directory. For example '/dirA/dirB' when creating 'dirB'. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +###### Defined in + +sandbox/filesystem/index.ts:308 + +##### read() + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`string`\> + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### Defined in + +sandbox/filesystem/index.ts:123 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`Uint8Array`\> + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### Defined in + +sandbox/filesystem/index.ts:138 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`Blob`\> + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### Defined in + +sandbox/filesystem/index.ts:153 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +###### Defined in + +sandbox/filesystem/index.ts:168 + +##### remove() + +> **remove**(`path`, `opts`?): `Promise`\<`void`\> + +Remove a file or directory. + +###### Parameters + +• **path**: `string` + +path to a file or directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/filesystem/index.ts:377 + +##### rename() + +> **rename**(`oldPath`, `newPath`, `opts`?): `Promise`\<`EntryInfo`\> + +Rename a file or directory. + +###### Parameters + +• **oldPath**: `string` + +path to the file or directory to rename. + +• **newPath**: `string` + +new path for the file or directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +###### Defined in + +sandbox/filesystem/index.ts:339 + +##### watchDir() + +> **watchDir**(`path`, `onEvent`, `opts`?): `Promise`\<`WatchHandle`\> + +Start watching a directory for filesystem events. + +###### Parameters + +• **path**: `string` + +path to directory to watch. + +• **onEvent** + +callback to call when an event in the directory occurs. + +• **opts?**: `WatchOpts` + +connection options. + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +###### Defined in + +sandbox/filesystem/index.ts:430 + +##### write() + +> **write**(`path`, `data`, `opts`?): `Promise`\<`EntryInfo`\> + +Write content to a file. + +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. + +###### Parameters + +• **path**: `string` + +path to file. + +• **data**: `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> + +data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### Defined in + +sandbox/filesystem/index.ts:224 + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +##### name + +> **name**: `string` + +Name of the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:33 + +##### path + +> **path**: `string` + +Path to the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:41 + +##### type? + +> `optional` **type**: `FileType` + +Type of the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:37 + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### user? + +> `optional` **user**: `Username` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +###### Defined in + +sandbox/filesystem/index.ts:76 + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +##### onExit()? + +> `optional` **onExit**: (`err`?) => `void` \| `Promise`\<`void`\> + +Callback to call when the watch operation stops. + +###### Parameters + +• **err?**: `Error` + +###### Returns + +`void` \| `Promise`\<`void`\> + +###### Defined in + +sandbox/filesystem/index.ts:93 + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### timeoutMs? + +> `optional` **timeoutMs**: `number` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +###### Defined in + +sandbox/filesystem/index.ts:89 + +##### user? + +> `optional` **user**: `Username` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +###### Defined in + +sandbox/filesystem/index.ts:76 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.3/sandbox/index.mdx new file mode 100644 index 0000000000..883aea6d33 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.3/sandbox/index.mdx @@ -0,0 +1,583 @@ +--- +title: Sandbox +--- + +## Classes + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +##### commands + +> `readonly` **commands**: `Commands` + +Module for running commands in the sandbox + +###### Defined in + +sandbox/index.ts:74 + +##### files + +> `readonly` **files**: `Filesystem` + +Module for interacting with the sandbox filesystem + +###### Defined in + +sandbox/index.ts:70 + +##### pty + +> `readonly` **pty**: `Pty` + +Module for interacting with the sandbox pseudo-terminals + +###### Defined in + +sandbox/index.ts:78 + +##### sandboxId + +> `readonly` **sandboxId**: `string` + +Unique identifier of the sandbox. + +###### Defined in + +sandbox/index.ts:83 + +#### Methods + +##### downloadUrl() + +> **downloadUrl**(`path`): `string` + +Get the URL to download a file from the sandbox. + +###### Parameters + +• **path**: `string` + +path to the file to download. + +###### Returns + +`string` + +URL for downloading file. + +###### Defined in + +sandbox/index.ts:339 + +##### getHost() + +> **getHost**(`port`): `string` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +• **port**: `number` + +number of the port in the sandbox. + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +`` + +###### Defined in + +sandbox/index.ts:237 + +##### isRunning() + +> **isRunning**(`opts`?): `Promise`\<`boolean`\> + +Check if the sandbox is running. + +###### Parameters + +• **opts?**: `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +###### Defined in + +sandbox/index.ts:259 + +##### kill() + +> **kill**(`opts`?): `Promise`\<`void`\> + +Kill the sandbox. + +###### Parameters + +• **opts?**: `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/index.ts:310 + +##### setTimeout() + +> **setTimeout**(`timeoutMs`, `opts`?): `Promise`\<`void`\> + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +• **timeoutMs**: `number` + +timeout in **milliseconds**. + +• **opts?**: `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/index.ts:290 + +##### uploadUrl() + +> **uploadUrl**(`path`?): `string` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +• **path?**: `string` + +the directory where to upload the file, defaults to user's home directory. + +###### Returns + +`string` + +URL for uploading file. + +###### Defined in + +sandbox/index.ts:328 + +##### connect() + +> `static` **connect**\<`S`\>(`this`, `sandboxId`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **sandboxId**: `string` + +sandbox ID. + +• **opts?**: `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +###### Defined in + +sandbox/index.ts:209 + +##### create() + +###### create(this, opts) + +> `static` **create**\<`S`\>(`this`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **opts?**: `SandboxOpts` + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### Defined in + +sandbox/index.ts:143 + +###### create(this, template, opts) + +> `static` **create**\<`S`\>(`this`, `template`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **template**: `string` + +sandbox template name or ID. + +• **opts?**: `SandboxOpts` + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +###### Defined in + +sandbox/index.ts:162 + +##### kill() + +> `static` **kill**(`sandboxId`, `opts`?): `Promise`\<`boolean`\> + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +• **sandboxId**: `string` + +sandbox ID. + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +###### Defined in + +sandbox/sandboxApi.ts:55 + +##### list() + +> `static` **list**(`opts`?): `Promise`\<`SandboxInfo`[]\> + +List all running sandboxes. + +###### Parameters + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +###### Defined in + +sandbox/sandboxApi.ts:90 + +##### setTimeout() + +> `static` **setTimeout**(`sandboxId`, `timeoutMs`, `opts`?): `Promise`\<`void`\> + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +• **sandboxId**: `string` + +sandbox ID. + +• **timeoutMs**: `number` + +timeout in **milliseconds**. + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/sandboxApi.ts:129 + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +##### accessToken? + +> `optional` **accessToken**: `string` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +###### Defined in + +connectionConfig.ts:24 + +##### apiKey? + +> `optional` **apiKey**: `string` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +###### Defined in + +connectionConfig.ts:18 + +##### debug? + +> `optional` **debug**: `boolean` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +###### Defined in + +connectionConfig.ts:36 + +##### domain? + +> `optional` **domain**: `string` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.dev` + +###### Defined in + +connectionConfig.ts:30 + +##### envs? + +> `optional` **envs**: `Record`\<`string`, `string`\> + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +###### Defined in + +sandbox/index.ts:32 + +##### logger? + +> `optional` **logger**: `Logger` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +###### Defined in + +connectionConfig.ts:46 + +##### metadata? + +> `optional` **metadata**: `Record`\<`string`, `string`\> + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +###### Defined in + +sandbox/index.ts:23 + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### timeoutMs? + +> `optional` **timeoutMs**: `number` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +###### Defined in + +sandbox/index.ts:39 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.4/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.4/errors/index.mdx new file mode 100644 index 0000000000..8ae3f12010 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.4/errors/index.mdx @@ -0,0 +1,233 @@ +--- +title: Errors +--- + +## Classes + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +##### new AuthenticationError() + +> **new AuthenticationError**(`message`): `AuthenticationError` + +###### Parameters + +• **message**: `any` + +###### Returns + +`AuthenticationError` + +###### Defined in + +errors.ts:72 + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +##### new InvalidArgumentError() + +> **new InvalidArgumentError**(`message`): `InvalidArgumentError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`InvalidArgumentError` + +###### Defined in + +errors.ts:42 + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +##### new NotEnoughSpaceError() + +> **new NotEnoughSpaceError**(`message`): `NotEnoughSpaceError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`NotEnoughSpaceError` + +###### Defined in + +errors.ts:52 + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +##### new NotFoundError() + +> **new NotFoundError**(`message`): `NotFoundError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`NotFoundError` + +###### Defined in + +errors.ts:62 + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +##### new RateLimitError() + +> **new RateLimitError**(`message`): `RateLimitError` + +###### Parameters + +• **message**: `any` + +###### Returns + +`RateLimitError` + +###### Defined in + +errors.ts:92 + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +##### new SandboxError() + +> **new SandboxError**(`message`): `SandboxError` + +###### Parameters + +• **message**: `any` + +###### Returns + +`SandboxError` + +###### Defined in + +errors.ts:14 + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +##### new TemplateError() + +> **new TemplateError**(`message`): `TemplateError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`TemplateError` + +###### Defined in + +errors.ts:82 + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +##### new TimeoutError() + +> **new TimeoutError**(`message`): `TimeoutError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`TimeoutError` + +###### Defined in + +errors.ts:32 + +## Functions + +### formatSandboxTimeoutError() + +> **formatSandboxTimeoutError**(`message`): `TimeoutError` + +#### Parameters + +• **message**: `string` + +#### Returns + +`TimeoutError` + +#### Defined in + +errors.ts:2 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.4/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.4/filesystem/index.mdx new file mode 100644 index 0000000000..729df1311d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.4/filesystem/index.mdx @@ -0,0 +1,520 @@ +--- +title: Filesystem +--- + +## Enumerations + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +##### DIR + +> **DIR**: `"dir"` + +Filesystem object is a directory. + +###### Defined in + +sandbox/filesystem/index.ts:55 + +##### FILE + +> **FILE**: `"file"` + +Filesystem object is a file. + +###### Defined in + +sandbox/filesystem/index.ts:51 + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +##### new Filesystem() + +> **new Filesystem**(`transport`, `envdApi`, `connectionConfig`): `Filesystem` + +###### Parameters + +• **transport**: `Transport` + +• **envdApi**: `EnvdApiClient` + +• **connectionConfig**: `ConnectionConfig` + +###### Returns + +`Filesystem` + +###### Defined in + +sandbox/filesystem/index.ts:104 + +#### Methods + +##### exists() + +> **exists**(`path`, `opts`?): `Promise`\<`boolean`\> + +Check if a file or a directory exists. + +###### Parameters + +• **path**: `string` + +path to a file or a directory + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +###### Defined in + +sandbox/filesystem/index.ts:402 + +##### list() + +> **list**(`path`, `opts`?): `Promise`\<`EntryInfo`[]\> + +List entries in a directory. + +###### Parameters + +• **path**: `string` + +path to the directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +###### Defined in + +sandbox/filesystem/index.ts:273 + +##### makeDir() + +> **makeDir**(`path`, `opts`?): `Promise`\<`boolean`\> + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +• **path**: `string` + +path to a new directory. For example '/dirA/dirB' when creating 'dirB'. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +###### Defined in + +sandbox/filesystem/index.ts:311 + +##### read() + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`string`\> + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### Defined in + +sandbox/filesystem/index.ts:123 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`Uint8Array`\> + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### Defined in + +sandbox/filesystem/index.ts:138 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`Blob`\> + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### Defined in + +sandbox/filesystem/index.ts:153 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +###### Defined in + +sandbox/filesystem/index.ts:168 + +##### remove() + +> **remove**(`path`, `opts`?): `Promise`\<`void`\> + +Remove a file or directory. + +###### Parameters + +• **path**: `string` + +path to a file or directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/filesystem/index.ts:380 + +##### rename() + +> **rename**(`oldPath`, `newPath`, `opts`?): `Promise`\<`EntryInfo`\> + +Rename a file or directory. + +###### Parameters + +• **oldPath**: `string` + +path to the file or directory to rename. + +• **newPath**: `string` + +new path for the file or directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +###### Defined in + +sandbox/filesystem/index.ts:342 + +##### watchDir() + +> **watchDir**(`path`, `onEvent`, `opts`?): `Promise`\<`WatchHandle`\> + +Start watching a directory for filesystem events. + +###### Parameters + +• **path**: `string` + +path to directory to watch. + +• **onEvent** + +callback to call when an event in the directory occurs. + +• **opts?**: `WatchOpts` + +connection options. + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +###### Defined in + +sandbox/filesystem/index.ts:433 + +##### write() + +> **write**(`path`, `data`, `opts`?): `Promise`\<`EntryInfo`\> + +Write content to a file. + +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. + +###### Parameters + +• **path**: `string` + +path to file. + +• **data**: `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> + +data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### Defined in + +sandbox/filesystem/index.ts:224 + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +##### name + +> **name**: `string` + +Name of the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:33 + +##### path + +> **path**: `string` + +Path to the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:41 + +##### type? + +> `optional` **type**: `FileType` + +Type of the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:37 + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### user? + +> `optional` **user**: `Username` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +###### Defined in + +sandbox/filesystem/index.ts:76 + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +##### onExit()? + +> `optional` **onExit**: (`err`?) => `void` \| `Promise`\<`void`\> + +Callback to call when the watch operation stops. + +###### Parameters + +• **err?**: `Error` + +###### Returns + +`void` \| `Promise`\<`void`\> + +###### Defined in + +sandbox/filesystem/index.ts:93 + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### timeoutMs? + +> `optional` **timeoutMs**: `number` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +###### Defined in + +sandbox/filesystem/index.ts:89 + +##### user? + +> `optional` **user**: `Username` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +###### Defined in + +sandbox/filesystem/index.ts:76 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.4/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.4/sandbox/index.mdx new file mode 100644 index 0000000000..883aea6d33 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.4/sandbox/index.mdx @@ -0,0 +1,583 @@ +--- +title: Sandbox +--- + +## Classes + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +##### commands + +> `readonly` **commands**: `Commands` + +Module for running commands in the sandbox + +###### Defined in + +sandbox/index.ts:74 + +##### files + +> `readonly` **files**: `Filesystem` + +Module for interacting with the sandbox filesystem + +###### Defined in + +sandbox/index.ts:70 + +##### pty + +> `readonly` **pty**: `Pty` + +Module for interacting with the sandbox pseudo-terminals + +###### Defined in + +sandbox/index.ts:78 + +##### sandboxId + +> `readonly` **sandboxId**: `string` + +Unique identifier of the sandbox. + +###### Defined in + +sandbox/index.ts:83 + +#### Methods + +##### downloadUrl() + +> **downloadUrl**(`path`): `string` + +Get the URL to download a file from the sandbox. + +###### Parameters + +• **path**: `string` + +path to the file to download. + +###### Returns + +`string` + +URL for downloading file. + +###### Defined in + +sandbox/index.ts:339 + +##### getHost() + +> **getHost**(`port`): `string` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +• **port**: `number` + +number of the port in the sandbox. + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +`` + +###### Defined in + +sandbox/index.ts:237 + +##### isRunning() + +> **isRunning**(`opts`?): `Promise`\<`boolean`\> + +Check if the sandbox is running. + +###### Parameters + +• **opts?**: `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +###### Defined in + +sandbox/index.ts:259 + +##### kill() + +> **kill**(`opts`?): `Promise`\<`void`\> + +Kill the sandbox. + +###### Parameters + +• **opts?**: `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/index.ts:310 + +##### setTimeout() + +> **setTimeout**(`timeoutMs`, `opts`?): `Promise`\<`void`\> + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +• **timeoutMs**: `number` + +timeout in **milliseconds**. + +• **opts?**: `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/index.ts:290 + +##### uploadUrl() + +> **uploadUrl**(`path`?): `string` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +• **path?**: `string` + +the directory where to upload the file, defaults to user's home directory. + +###### Returns + +`string` + +URL for uploading file. + +###### Defined in + +sandbox/index.ts:328 + +##### connect() + +> `static` **connect**\<`S`\>(`this`, `sandboxId`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **sandboxId**: `string` + +sandbox ID. + +• **opts?**: `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +###### Defined in + +sandbox/index.ts:209 + +##### create() + +###### create(this, opts) + +> `static` **create**\<`S`\>(`this`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **opts?**: `SandboxOpts` + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### Defined in + +sandbox/index.ts:143 + +###### create(this, template, opts) + +> `static` **create**\<`S`\>(`this`, `template`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **template**: `string` + +sandbox template name or ID. + +• **opts?**: `SandboxOpts` + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +###### Defined in + +sandbox/index.ts:162 + +##### kill() + +> `static` **kill**(`sandboxId`, `opts`?): `Promise`\<`boolean`\> + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +• **sandboxId**: `string` + +sandbox ID. + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +###### Defined in + +sandbox/sandboxApi.ts:55 + +##### list() + +> `static` **list**(`opts`?): `Promise`\<`SandboxInfo`[]\> + +List all running sandboxes. + +###### Parameters + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +###### Defined in + +sandbox/sandboxApi.ts:90 + +##### setTimeout() + +> `static` **setTimeout**(`sandboxId`, `timeoutMs`, `opts`?): `Promise`\<`void`\> + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +• **sandboxId**: `string` + +sandbox ID. + +• **timeoutMs**: `number` + +timeout in **milliseconds**. + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/sandboxApi.ts:129 + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +##### accessToken? + +> `optional` **accessToken**: `string` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +###### Defined in + +connectionConfig.ts:24 + +##### apiKey? + +> `optional` **apiKey**: `string` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +###### Defined in + +connectionConfig.ts:18 + +##### debug? + +> `optional` **debug**: `boolean` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +###### Defined in + +connectionConfig.ts:36 + +##### domain? + +> `optional` **domain**: `string` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.dev` + +###### Defined in + +connectionConfig.ts:30 + +##### envs? + +> `optional` **envs**: `Record`\<`string`, `string`\> + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +###### Defined in + +sandbox/index.ts:32 + +##### logger? + +> `optional` **logger**: `Logger` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +###### Defined in + +connectionConfig.ts:46 + +##### metadata? + +> `optional` **metadata**: `Record`\<`string`, `string`\> + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +###### Defined in + +sandbox/index.ts:23 + +##### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +##### timeoutMs? + +> `optional` **timeoutMs**: `number` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +###### Defined in + +sandbox/index.ts:39 diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.5/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.5/commands/index.mdx new file mode 100644 index 0000000000..30f7182120 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.5/commands/index.mdx @@ -0,0 +1,487 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.5/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.5/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.5/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.5/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.5/filesystem/index.mdx new file mode 100644 index 0000000000..6734d3093f --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.5/filesystem/index.mdx @@ -0,0 +1,431 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemRequestOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.5/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.5/sandbox/index.mdx new file mode 100644 index 0000000000..ca0430e90c --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.5/sandbox/index.mdx @@ -0,0 +1,502 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file to download. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | the directory where to upload the file, defaults to user's home directory. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxApiOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.dev` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.6/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.6/commands/index.mdx new file mode 100644 index 0000000000..30f7182120 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.6/commands/index.mdx @@ -0,0 +1,487 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.6/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.6/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.6/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.6/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.6/filesystem/index.mdx new file mode 100644 index 0000000000..ed5504b828 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.6/filesystem/index.mdx @@ -0,0 +1,439 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemRequestOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.6/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.6/sandbox/index.mdx new file mode 100644 index 0000000000..ca0430e90c --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.6/sandbox/index.mdx @@ -0,0 +1,502 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file to download. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | the directory where to upload the file, defaults to user's home directory. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxApiOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.dev` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.7/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.7/commands/index.mdx new file mode 100644 index 0000000000..30f7182120 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.7/commands/index.mdx @@ -0,0 +1,487 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.7/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.7/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.7/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.7/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.7/filesystem/index.mdx new file mode 100644 index 0000000000..ed5504b828 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.7/filesystem/index.mdx @@ -0,0 +1,439 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemRequestOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.7/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.7/sandbox/index.mdx new file mode 100644 index 0000000000..ca0430e90c --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.0.7/sandbox/index.mdx @@ -0,0 +1,502 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file to download. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | the directory where to upload the file, defaults to user's home directory. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxApiOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.dev` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.0/commands/index.mdx new file mode 100644 index 0000000000..30f7182120 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.0/commands/index.mdx @@ -0,0 +1,487 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.0/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.0/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.0/filesystem/index.mdx new file mode 100644 index 0000000000..6adf4a1c9e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.0/filesystem/index.mdx @@ -0,0 +1,473 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemRequestOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.0/sandbox/index.mdx new file mode 100644 index 0000000000..ca0430e90c --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.0/sandbox/index.mdx @@ -0,0 +1,502 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file to download. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | the directory where to upload the file, defaults to user's home directory. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxApiOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.dev` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.1/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.1/commands/index.mdx new file mode 100644 index 0000000000..30f7182120 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.1/commands/index.mdx @@ -0,0 +1,487 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.1/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.1/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.1/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.1/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.1/filesystem/index.mdx new file mode 100644 index 0000000000..6adf4a1c9e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.1/filesystem/index.mdx @@ -0,0 +1,473 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemRequestOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.1/sandbox/index.mdx new file mode 100644 index 0000000000..d5eec1582d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.1.1/sandbox/index.mdx @@ -0,0 +1,502 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file to download. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | the directory where to upload the file, defaults to user's home directory. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.dev` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.10.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.10.0/commands/index.mdx new file mode 100644 index 0000000000..2bd2884267 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.10.0/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.10.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.10.0/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.10.0/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.10.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.10.0/filesystem/index.mdx new file mode 100644 index 0000000000..b089f700b7 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.10.0/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.10.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.10.0/sandbox/index.mdx new file mode 100644 index 0000000000..56e82a4223 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.10.0/sandbox/index.mdx @@ -0,0 +1,608 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignature? + +```ts +optional useSignature: true; +``` + +Use signature for the URL. +This needs to be used in case of using secured envd in sandbox. + +###### Default + +```ts +false +``` + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.11.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.11.0/commands/index.mdx new file mode 100644 index 0000000000..2bd2884267 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.11.0/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.11.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.11.0/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.11.0/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.11.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.11.0/filesystem/index.mdx new file mode 100644 index 0000000000..b089f700b7 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.11.0/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.11.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.11.0/sandbox/index.mdx new file mode 100644 index 0000000000..36602dc94d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.11.0/sandbox/index.mdx @@ -0,0 +1,649 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMetrics() + +```ts +getMetrics(opts?: Pick): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxMetricsOpts`, `"start"` \| `"end"` \| `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignature? + +```ts +optional useSignature: true; +``` + +Use signature for the URL. +This needs to be used in case of using secured envd in sandbox. + +###### Default + +```ts +false +``` + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.12.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.12.0/commands/index.mdx new file mode 100644 index 0000000000..2bd2884267 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.12.0/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.12.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.12.0/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.12.0/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.12.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.12.0/filesystem/index.mdx new file mode 100644 index 0000000000..b089f700b7 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.12.0/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.12.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.12.0/sandbox/index.mdx new file mode 100644 index 0000000000..742b836722 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.12.0/sandbox/index.mdx @@ -0,0 +1,663 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMetrics() + +```ts +getMetrics(opts?: Pick): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxMetricsOpts`, `"start"` \| `"end"` \| `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### allowInternetAccess? + +```ts +optional allowInternetAccess: boolean; +``` + +Allow sandbox to access the internet + +###### Default + +```ts +true +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignature? + +```ts +optional useSignature: true; +``` + +Use signature for the URL. +This needs to be used in case of using secured envd in sandbox. + +###### Default + +```ts +false +``` + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.0/commands/index.mdx new file mode 100644 index 0000000000..92606279c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.0/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.0/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.0/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.0/filesystem/index.mdx new file mode 100644 index 0000000000..0586f2f1f9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.0/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.0/sandbox/index.mdx new file mode 100644 index 0000000000..5f1d13b35a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.0/sandbox/index.mdx @@ -0,0 +1,648 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMetrics() + +```ts +getMetrics(opts?: Pick): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxMetricsOpts`, `"start"` \| `"end"` \| `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### allowInternetAccess? + +```ts +optional allowInternetAccess: boolean; +``` + +Allow sandbox to access the internet + +###### Default + +```ts +true +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.1/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.1/commands/index.mdx new file mode 100644 index 0000000000..92606279c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.1/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.1/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.1/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.1/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.1/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.1/filesystem/index.mdx new file mode 100644 index 0000000000..0586f2f1f9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.1/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.1/sandbox/index.mdx new file mode 100644 index 0000000000..5f1d13b35a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.1/sandbox/index.mdx @@ -0,0 +1,648 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMetrics() + +```ts +getMetrics(opts?: Pick): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxMetricsOpts`, `"start"` \| `"end"` \| `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### allowInternetAccess? + +```ts +optional allowInternetAccess: boolean; +``` + +Allow sandbox to access the internet + +###### Default + +```ts +true +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.2/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.2/commands/index.mdx new file mode 100644 index 0000000000..92606279c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.2/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.2/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.2/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.2/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.2/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.2/filesystem/index.mdx new file mode 100644 index 0000000000..0586f2f1f9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.2/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.2/sandbox/index.mdx new file mode 100644 index 0000000000..5f1d13b35a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.13.2/sandbox/index.mdx @@ -0,0 +1,648 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMetrics() + +```ts +getMetrics(opts?: Pick): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxMetricsOpts`, `"start"` \| `"end"` \| `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### allowInternetAccess? + +```ts +optional allowInternetAccess: boolean; +``` + +Allow sandbox to access the internet + +###### Default + +```ts +true +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.0/commands/index.mdx new file mode 100644 index 0000000000..30f7182120 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.0/commands/index.mdx @@ -0,0 +1,487 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.0/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.0/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.0/filesystem/index.mdx new file mode 100644 index 0000000000..6adf4a1c9e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.0/filesystem/index.mdx @@ -0,0 +1,473 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemRequestOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.0/sandbox/index.mdx new file mode 100644 index 0000000000..88295fb71d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.0/sandbox/index.mdx @@ -0,0 +1,502 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file to download. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | the directory where to upload the file, defaults to user's home directory. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.1/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.1/commands/index.mdx new file mode 100644 index 0000000000..30f7182120 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.1/commands/index.mdx @@ -0,0 +1,487 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.1/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.1/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.1/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.1/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.1/filesystem/index.mdx new file mode 100644 index 0000000000..6adf4a1c9e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.1/filesystem/index.mdx @@ -0,0 +1,473 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemRequestOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.1/sandbox/index.mdx new file mode 100644 index 0000000000..8e82c30c01 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.1/sandbox/index.mdx @@ -0,0 +1,543 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file to download. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | the directory where to upload the file, defaults to user's home directory. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.2/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.2/commands/index.mdx new file mode 100644 index 0000000000..30f7182120 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.2/commands/index.mdx @@ -0,0 +1,487 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.2/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.2/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.2/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.2/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.2/filesystem/index.mdx new file mode 100644 index 0000000000..6adf4a1c9e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.2/filesystem/index.mdx @@ -0,0 +1,473 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemRequestOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.2/sandbox/index.mdx new file mode 100644 index 0000000000..89be96b5d9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.2/sandbox/index.mdx @@ -0,0 +1,551 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file to download. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | the directory where to upload the file, defaults to user's home directory. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.3/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.3/commands/index.mdx new file mode 100644 index 0000000000..30f7182120 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.3/commands/index.mdx @@ -0,0 +1,487 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.3/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.3/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.3/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.3/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.3/filesystem/index.mdx new file mode 100644 index 0000000000..6adf4a1c9e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.3/filesystem/index.mdx @@ -0,0 +1,473 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemRequestOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.3/sandbox/index.mdx new file mode 100644 index 0000000000..89be96b5d9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.3/sandbox/index.mdx @@ -0,0 +1,551 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file to download. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | the directory where to upload the file, defaults to user's home directory. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.4/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.4/commands/index.mdx new file mode 100644 index 0000000000..30f7182120 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.4/commands/index.mdx @@ -0,0 +1,487 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.4/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.4/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.4/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.4/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.4/filesystem/index.mdx new file mode 100644 index 0000000000..6adf4a1c9e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.4/filesystem/index.mdx @@ -0,0 +1,473 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemRequestOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.4/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.4/sandbox/index.mdx new file mode 100644 index 0000000000..89be96b5d9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.4/sandbox/index.mdx @@ -0,0 +1,551 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file to download. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | the directory where to upload the file, defaults to user's home directory. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.5/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.5/commands/index.mdx new file mode 100644 index 0000000000..30f7182120 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.5/commands/index.mdx @@ -0,0 +1,487 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.5/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.5/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.5/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.5/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.5/filesystem/index.mdx new file mode 100644 index 0000000000..6adf4a1c9e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.5/filesystem/index.mdx @@ -0,0 +1,473 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemRequestOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.5/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.5/sandbox/index.mdx new file mode 100644 index 0000000000..89be96b5d9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.2.5/sandbox/index.mdx @@ -0,0 +1,551 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file to download. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | the directory where to upload the file, defaults to user's home directory. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.3.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.3.0/commands/index.mdx new file mode 100644 index 0000000000..30f7182120 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.3.0/commands/index.mdx @@ -0,0 +1,487 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.3.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.3.0/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.3.0/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.3.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.3.0/filesystem/index.mdx new file mode 100644 index 0000000000..6adf4a1c9e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.3.0/filesystem/index.mdx @@ -0,0 +1,473 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemRequestOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.3.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.3.0/sandbox/index.mdx new file mode 100644 index 0000000000..89be96b5d9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.3.0/sandbox/index.mdx @@ -0,0 +1,551 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file to download. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | the directory where to upload the file, defaults to user's home directory. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.4.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.4.0/commands/index.mdx new file mode 100644 index 0000000000..30f7182120 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.4.0/commands/index.mdx @@ -0,0 +1,487 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.4.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.4.0/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.4.0/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.4.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.4.0/filesystem/index.mdx new file mode 100644 index 0000000000..899b6ff113 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.4.0/filesystem/index.mdx @@ -0,0 +1,513 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.4.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.4.0/sandbox/index.mdx new file mode 100644 index 0000000000..89be96b5d9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.4.0/sandbox/index.mdx @@ -0,0 +1,551 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file to download. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | the directory where to upload the file, defaults to user's home directory. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.0/commands/index.mdx new file mode 100644 index 0000000000..30f7182120 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.0/commands/index.mdx @@ -0,0 +1,487 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.0/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.0/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.0/filesystem/index.mdx new file mode 100644 index 0000000000..899b6ff113 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.0/filesystem/index.mdx @@ -0,0 +1,513 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.0/sandbox/index.mdx new file mode 100644 index 0000000000..5de844776d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.0/sandbox/index.mdx @@ -0,0 +1,599 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### useSignature? + +```ts +optional useSignature: true; +``` + +Use signature for the URL. +This needs to be used in case of using secured envd in sandbox. + +###### Default + +```ts +false +``` + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.1/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.1/commands/index.mdx new file mode 100644 index 0000000000..2bd2884267 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.1/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.1/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.1/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.1/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.1/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.1/filesystem/index.mdx new file mode 100644 index 0000000000..899b6ff113 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.1/filesystem/index.mdx @@ -0,0 +1,513 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.1/sandbox/index.mdx new file mode 100644 index 0000000000..5de844776d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.1/sandbox/index.mdx @@ -0,0 +1,599 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### useSignature? + +```ts +optional useSignature: true; +``` + +Use signature for the URL. +This needs to be used in case of using secured envd in sandbox. + +###### Default + +```ts +false +``` + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.2/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.2/commands/index.mdx new file mode 100644 index 0000000000..2bd2884267 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.2/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.2/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.2/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.2/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.2/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.2/filesystem/index.mdx new file mode 100644 index 0000000000..899b6ff113 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.2/filesystem/index.mdx @@ -0,0 +1,513 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.2/sandbox/index.mdx new file mode 100644 index 0000000000..5de844776d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.2/sandbox/index.mdx @@ -0,0 +1,599 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### useSignature? + +```ts +optional useSignature: true; +``` + +Use signature for the URL. +This needs to be used in case of using secured envd in sandbox. + +###### Default + +```ts +false +``` + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.3/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.3/commands/index.mdx new file mode 100644 index 0000000000..2bd2884267 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.3/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.3/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.3/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.3/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.3/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.3/filesystem/index.mdx new file mode 100644 index 0000000000..899b6ff113 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.3/filesystem/index.mdx @@ -0,0 +1,513 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.3/sandbox/index.mdx new file mode 100644 index 0000000000..5de844776d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.5.3/sandbox/index.mdx @@ -0,0 +1,599 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### useSignature? + +```ts +optional useSignature: true; +``` + +Use signature for the URL. +This needs to be used in case of using secured envd in sandbox. + +###### Default + +```ts +false +``` + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.6.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.6.0/commands/index.mdx new file mode 100644 index 0000000000..2bd2884267 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.6.0/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.6.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.6.0/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.6.0/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.6.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.6.0/filesystem/index.mdx new file mode 100644 index 0000000000..899b6ff113 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.6.0/filesystem/index.mdx @@ -0,0 +1,513 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.6.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.6.0/sandbox/index.mdx new file mode 100644 index 0000000000..df9a71aa02 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.6.0/sandbox/index.mdx @@ -0,0 +1,607 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): string +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`string` + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): string +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`string` + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignature? + +```ts +optional useSignature: true; +``` + +Use signature for the URL. +This needs to be used in case of using secured envd in sandbox. + +###### Default + +```ts +false +``` + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.0/commands/index.mdx new file mode 100644 index 0000000000..2bd2884267 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.0/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.0/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.0/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.0/filesystem/index.mdx new file mode 100644 index 0000000000..899b6ff113 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.0/filesystem/index.mdx @@ -0,0 +1,513 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.0/sandbox/index.mdx new file mode 100644 index 0000000000..5da6ea3158 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.0/sandbox/index.mdx @@ -0,0 +1,607 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignature? + +```ts +optional useSignature: true; +``` + +Use signature for the URL. +This needs to be used in case of using secured envd in sandbox. + +###### Default + +```ts +false +``` + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.1/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.1/commands/index.mdx new file mode 100644 index 0000000000..2bd2884267 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.1/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.1/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.1/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.1/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.1/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.1/filesystem/index.mdx new file mode 100644 index 0000000000..899b6ff113 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.1/filesystem/index.mdx @@ -0,0 +1,513 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.1/sandbox/index.mdx new file mode 100644 index 0000000000..5da6ea3158 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.7.1/sandbox/index.mdx @@ -0,0 +1,607 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignature? + +```ts +optional useSignature: true; +``` + +Use signature for the URL. +This needs to be used in case of using secured envd in sandbox. + +###### Default + +```ts +false +``` + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.8.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.8.0/commands/index.mdx new file mode 100644 index 0000000000..2bd2884267 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.8.0/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.8.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.8.0/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.8.0/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.8.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.8.0/filesystem/index.mdx new file mode 100644 index 0000000000..899b6ff113 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.8.0/filesystem/index.mdx @@ -0,0 +1,513 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.8.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.8.0/sandbox/index.mdx new file mode 100644 index 0000000000..5da6ea3158 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.8.0/sandbox/index.mdx @@ -0,0 +1,607 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignature? + +```ts +optional useSignature: true; +``` + +Use signature for the URL. +This needs to be used in case of using secured envd in sandbox. + +###### Default + +```ts +false +``` + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.0/commands/index.mdx new file mode 100644 index 0000000000..2bd2884267 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.0/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.0/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.0/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.0/filesystem/index.mdx new file mode 100644 index 0000000000..899b6ff113 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.0/filesystem/index.mdx @@ -0,0 +1,513 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.0/sandbox/index.mdx new file mode 100644 index 0000000000..56e82a4223 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.0/sandbox/index.mdx @@ -0,0 +1,608 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignature? + +```ts +optional useSignature: true; +``` + +Use signature for the URL. +This needs to be used in case of using secured envd in sandbox. + +###### Default + +```ts +false +``` + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.1/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.1/commands/index.mdx new file mode 100644 index 0000000000..2bd2884267 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.1/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.1/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.1/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.1/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.1/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.1/filesystem/index.mdx new file mode 100644 index 0000000000..899b6ff113 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.1/filesystem/index.mdx @@ -0,0 +1,513 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.1/sandbox/index.mdx new file mode 100644 index 0000000000..56e82a4223 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v1.9.1/sandbox/index.mdx @@ -0,0 +1,608 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: Omit): Promise> +``` + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): Promise +``` + +List all running sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`Promise`\<`ListedSandbox`[]\> + +list of running sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +```ts +optional accessToken: string; +``` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +### apiKey? + +```ts +optional apiKey: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +### debug? + +```ts +optional debug: boolean; +``` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +### headers? + +```ts +optional headers: Record; +``` + +Additional headers to send with the request. + +### logger? + +```ts +optional logger: Logger; +``` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +### metadata? + +```ts +optional metadata: Record; +``` + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### secure? + +```ts +optional secure: boolean; +``` + +Secure all traffic coming to the sandbox controller with auth token + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +*** + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignature? + +```ts +optional useSignature: true; +``` + +Use signature for the URL. +This needs to be used in case of using secured envd in sandbox. + +###### Default + +```ts +false +``` + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.0/commands/index.mdx new file mode 100644 index 0000000000..92606279c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.0/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.0/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.0/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.0/filesystem/index.mdx new file mode 100644 index 0000000000..0586f2f1f9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.0/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.0/sandbox/index.mdx new file mode 100644 index 0000000000..8bf01fc350 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.0/sandbox/index.mdx @@ -0,0 +1,682 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### betaPause() + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Pause a sandbox by its ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +sandbox ID that can be used to resume the sandbox. + +### connect() + +```ts +connect(opts?: SandboxBetaCreateOpts): Promise +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`Sandbox`\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.betaPause() + +// Connect to the same sandbox. +const sameSandbox = await sandbox.connect() +``` + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMetrics() + +```ts +getMetrics(opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxMetricsOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate('') +``` + +###### Constructs + +Sandbox + +### betaPause() + +```ts +static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Pause the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox got paused, `false` if the sandbox was already paused. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: SandboxConnectOpts): Promise> +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Default value | +| ------ | ------ | ------ | +| `cpuCount` | `number` | res.data.cpuCount | +| `endAt` | `Date` | - | +| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | +| `envdVersion` | `string` | res.data.envdVersion | +| `memoryMB` | `number` | res.data.memoryMB | +| `metadata` | `object` | - | +| `name`? | `string` | res.data.alias | +| `sandboxDomain` | `undefined` \| `string` | - | +| `sandboxId` | `string` | res.data.sandboxID | +| `startedAt` | `Date` | - | +| `state` | `"running"` \| `"paused"` | res.data.state | +| `templateId` | `string` | res.data.templateID | + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): SandboxPaginator +``` + +List all sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`SandboxPaginator` + +paginator for listing sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.1/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.1/commands/index.mdx new file mode 100644 index 0000000000..92606279c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.1/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.1/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.1/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.1/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.1/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.1/filesystem/index.mdx new file mode 100644 index 0000000000..0586f2f1f9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.1/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.1/sandbox/index.mdx new file mode 100644 index 0000000000..8bf01fc350 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.1/sandbox/index.mdx @@ -0,0 +1,682 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### betaPause() + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Pause a sandbox by its ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +sandbox ID that can be used to resume the sandbox. + +### connect() + +```ts +connect(opts?: SandboxBetaCreateOpts): Promise +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`Sandbox`\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.betaPause() + +// Connect to the same sandbox. +const sameSandbox = await sandbox.connect() +``` + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMetrics() + +```ts +getMetrics(opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxMetricsOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate('') +``` + +###### Constructs + +Sandbox + +### betaPause() + +```ts +static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Pause the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox got paused, `false` if the sandbox was already paused. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: SandboxConnectOpts): Promise> +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Default value | +| ------ | ------ | ------ | +| `cpuCount` | `number` | res.data.cpuCount | +| `endAt` | `Date` | - | +| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | +| `envdVersion` | `string` | res.data.envdVersion | +| `memoryMB` | `number` | res.data.memoryMB | +| `metadata` | `object` | - | +| `name`? | `string` | res.data.alias | +| `sandboxDomain` | `undefined` \| `string` | - | +| `sandboxId` | `string` | res.data.sandboxID | +| `startedAt` | `Date` | - | +| `state` | `"running"` \| `"paused"` | res.data.state | +| `templateId` | `string` | res.data.templateID | + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): SandboxPaginator +``` + +List all sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`SandboxPaginator` + +paginator for listing sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.2/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.2/commands/index.mdx new file mode 100644 index 0000000000..92606279c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.2/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.2/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.2/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.2/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.2/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.2/filesystem/index.mdx new file mode 100644 index 0000000000..0586f2f1f9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.2/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.2/sandbox/index.mdx new file mode 100644 index 0000000000..8bf01fc350 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.2/sandbox/index.mdx @@ -0,0 +1,682 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### betaPause() + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Pause a sandbox by its ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +sandbox ID that can be used to resume the sandbox. + +### connect() + +```ts +connect(opts?: SandboxBetaCreateOpts): Promise +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`Sandbox`\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.betaPause() + +// Connect to the same sandbox. +const sameSandbox = await sandbox.connect() +``` + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMetrics() + +```ts +getMetrics(opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxMetricsOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate('') +``` + +###### Constructs + +Sandbox + +### betaPause() + +```ts +static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Pause the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox got paused, `false` if the sandbox was already paused. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: SandboxConnectOpts): Promise> +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Default value | +| ------ | ------ | ------ | +| `cpuCount` | `number` | res.data.cpuCount | +| `endAt` | `Date` | - | +| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | +| `envdVersion` | `string` | res.data.envdVersion | +| `memoryMB` | `number` | res.data.memoryMB | +| `metadata` | `object` | - | +| `name`? | `string` | res.data.alias | +| `sandboxDomain` | `undefined` \| `string` | - | +| `sandboxId` | `string` | res.data.sandboxID | +| `startedAt` | `Date` | - | +| `state` | `"running"` \| `"paused"` | res.data.state | +| `templateId` | `string` | res.data.templateID | + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): SandboxPaginator +``` + +List all sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`SandboxPaginator` + +paginator for listing sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.3/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.3/commands/index.mdx new file mode 100644 index 0000000000..92606279c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.3/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.3/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.3/errors/index.mdx new file mode 100644 index 0000000000..4d630a8280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.3/errors/index.mdx @@ -0,0 +1,215 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.3/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.3/filesystem/index.mdx new file mode 100644 index 0000000000..0586f2f1f9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.3/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.3/sandbox/index.mdx new file mode 100644 index 0000000000..8bf01fc350 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.0.3/sandbox/index.mdx @@ -0,0 +1,682 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### betaPause() + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Pause a sandbox by its ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +sandbox ID that can be used to resume the sandbox. + +### connect() + +```ts +connect(opts?: SandboxBetaCreateOpts): Promise +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`Sandbox`\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.betaPause() + +// Connect to the same sandbox. +const sameSandbox = await sandbox.connect() +``` + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMetrics() + +```ts +getMetrics(opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxMetricsOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate('') +``` + +###### Constructs + +Sandbox + +### betaPause() + +```ts +static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Pause the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox got paused, `false` if the sandbox was already paused. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: SandboxConnectOpts): Promise> +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Default value | +| ------ | ------ | ------ | +| `cpuCount` | `number` | res.data.cpuCount | +| `endAt` | `Date` | - | +| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | +| `envdVersion` | `string` | res.data.envdVersion | +| `memoryMB` | `number` | res.data.memoryMB | +| `metadata` | `object` | - | +| `name`? | `string` | res.data.alias | +| `sandboxDomain` | `undefined` \| `string` | - | +| `sandboxId` | `string` | res.data.sandboxID | +| `startedAt` | `Date` | - | +| `state` | `"running"` \| `"paused"` | res.data.state | +| `templateId` | `string` | res.data.templateID | + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): SandboxPaginator +``` + +List all sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`SandboxPaginator` + +paginator for listing sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.0/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.0/commands/index.mdx new file mode 100644 index 0000000000..92606279c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.0/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.0/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.0/errors/index.mdx new file mode 100644 index 0000000000..22c2c21866 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.0/errors/index.mdx @@ -0,0 +1,214 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.0/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.0/filesystem/index.mdx new file mode 100644 index 0000000000..0586f2f1f9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.0/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.0/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.0/sandbox/index.mdx new file mode 100644 index 0000000000..8bf01fc350 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.0/sandbox/index.mdx @@ -0,0 +1,682 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### betaPause() + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Pause a sandbox by its ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +sandbox ID that can be used to resume the sandbox. + +### connect() + +```ts +connect(opts?: SandboxBetaCreateOpts): Promise +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`Sandbox`\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.betaPause() + +// Connect to the same sandbox. +const sameSandbox = await sandbox.connect() +``` + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMetrics() + +```ts +getMetrics(opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxMetricsOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate('') +``` + +###### Constructs + +Sandbox + +### betaPause() + +```ts +static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Pause the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox got paused, `false` if the sandbox was already paused. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: SandboxConnectOpts): Promise> +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Default value | +| ------ | ------ | ------ | +| `cpuCount` | `number` | res.data.cpuCount | +| `endAt` | `Date` | - | +| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | +| `envdVersion` | `string` | res.data.envdVersion | +| `memoryMB` | `number` | res.data.memoryMB | +| `metadata` | `object` | - | +| `name`? | `string` | res.data.alias | +| `sandboxDomain` | `undefined` \| `string` | - | +| `sandboxId` | `string` | res.data.sandboxID | +| `startedAt` | `Date` | - | +| `state` | `"running"` \| `"paused"` | res.data.state | +| `templateId` | `string` | res.data.templateID | + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): SandboxPaginator +``` + +List all sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`SandboxPaginator` + +paginator for listing sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.1/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.1/commands/index.mdx new file mode 100644 index 0000000000..92606279c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.1/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.1/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.1/errors/index.mdx new file mode 100644 index 0000000000..22c2c21866 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.1/errors/index.mdx @@ -0,0 +1,214 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.1/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.1/filesystem/index.mdx new file mode 100644 index 0000000000..0586f2f1f9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.1/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.1/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.1/sandbox/index.mdx new file mode 100644 index 0000000000..8bf01fc350 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.1/sandbox/index.mdx @@ -0,0 +1,682 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### betaPause() + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Pause a sandbox by its ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +sandbox ID that can be used to resume the sandbox. + +### connect() + +```ts +connect(opts?: SandboxBetaCreateOpts): Promise +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`Sandbox`\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.betaPause() + +// Connect to the same sandbox. +const sameSandbox = await sandbox.connect() +``` + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMetrics() + +```ts +getMetrics(opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxMetricsOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate('') +``` + +###### Constructs + +Sandbox + +### betaPause() + +```ts +static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Pause the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox got paused, `false` if the sandbox was already paused. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: SandboxConnectOpts): Promise> +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Default value | +| ------ | ------ | ------ | +| `cpuCount` | `number` | res.data.cpuCount | +| `endAt` | `Date` | - | +| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | +| `envdVersion` | `string` | res.data.envdVersion | +| `memoryMB` | `number` | res.data.memoryMB | +| `metadata` | `object` | - | +| `name`? | `string` | res.data.alias | +| `sandboxDomain` | `undefined` \| `string` | - | +| `sandboxId` | `string` | res.data.sandboxID | +| `startedAt` | `Date` | - | +| `state` | `"running"` \| `"paused"` | res.data.state | +| `templateId` | `string` | res.data.templateID | + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): SandboxPaginator +``` + +List all sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`SandboxPaginator` + +paginator for listing sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.2/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.2/commands/index.mdx new file mode 100644 index 0000000000..92606279c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.2/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.2/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.2/errors/index.mdx new file mode 100644 index 0000000000..22c2c21866 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.2/errors/index.mdx @@ -0,0 +1,214 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.2/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.2/filesystem/index.mdx new file mode 100644 index 0000000000..0586f2f1f9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.2/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.2/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.2/sandbox/index.mdx new file mode 100644 index 0000000000..8bf01fc350 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.2/sandbox/index.mdx @@ -0,0 +1,682 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### betaPause() + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Pause a sandbox by its ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +sandbox ID that can be used to resume the sandbox. + +### connect() + +```ts +connect(opts?: SandboxBetaCreateOpts): Promise +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`Sandbox`\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.betaPause() + +// Connect to the same sandbox. +const sameSandbox = await sandbox.connect() +``` + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMetrics() + +```ts +getMetrics(opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxMetricsOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate('') +``` + +###### Constructs + +Sandbox + +### betaPause() + +```ts +static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Pause the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox got paused, `false` if the sandbox was already paused. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: SandboxConnectOpts): Promise> +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Default value | +| ------ | ------ | ------ | +| `cpuCount` | `number` | res.data.cpuCount | +| `endAt` | `Date` | - | +| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | +| `envdVersion` | `string` | res.data.envdVersion | +| `memoryMB` | `number` | res.data.memoryMB | +| `metadata` | `object` | - | +| `name`? | `string` | res.data.alias | +| `sandboxDomain` | `undefined` \| `string` | - | +| `sandboxId` | `string` | res.data.sandboxID | +| `startedAt` | `Date` | - | +| `state` | `"running"` \| `"paused"` | res.data.state | +| `templateId` | `string` | res.data.templateID | + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): SandboxPaginator +``` + +List all sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`SandboxPaginator` + +paginator for listing sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.3/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.3/commands/index.mdx new file mode 100644 index 0000000000..92606279c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.3/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.3/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.3/errors/index.mdx new file mode 100644 index 0000000000..22c2c21866 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.3/errors/index.mdx @@ -0,0 +1,214 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: any): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: any): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message: any): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `any` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.3/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.3/filesystem/index.mdx new file mode 100644 index 0000000000..0586f2f1f9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.3/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.3/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.3/sandbox/index.mdx new file mode 100644 index 0000000000..8bf01fc350 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.3/sandbox/index.mdx @@ -0,0 +1,682 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### betaPause() + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Pause a sandbox by its ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +sandbox ID that can be used to resume the sandbox. + +### connect() + +```ts +connect(opts?: SandboxBetaCreateOpts): Promise +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`Sandbox`\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.betaPause() + +// Connect to the same sandbox. +const sameSandbox = await sandbox.connect() +``` + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMetrics() + +```ts +getMetrics(opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxMetricsOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate('') +``` + +###### Constructs + +Sandbox + +### betaPause() + +```ts +static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Pause the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox got paused, `false` if the sandbox was already paused. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: SandboxConnectOpts): Promise> +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Default value | +| ------ | ------ | ------ | +| `cpuCount` | `number` | res.data.cpuCount | +| `endAt` | `Date` | - | +| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | +| `envdVersion` | `string` | res.data.envdVersion | +| `memoryMB` | `number` | res.data.memoryMB | +| `metadata` | `object` | - | +| `name`? | `string` | res.data.alias | +| `sandboxDomain` | `undefined` \| `string` | - | +| `sandboxId` | `string` | res.data.sandboxID | +| `startedAt` | `Date` | - | +| `state` | `"running"` \| `"paused"` | res.data.state | +| `templateId` | `string` | res.data.templateID | + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): SandboxPaginator +``` + +List all sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`SandboxPaginator` + +paginator for listing sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.4/commands/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.4/commands/index.mdx new file mode 100644 index 0000000000..92606279c5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.4/commands/index.mdx @@ -0,0 +1,508 @@ +--- +title: Commands +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands(transport: Transport, connectionConfig: ConnectionConfig): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty(transport: Transport, connectionConfig: ConnectionConfig): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to run the command as. + +###### Default + +`user` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.4/errors/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.4/errors/index.mdx new file mode 100644 index 0000000000..cf7f477485 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.4/errors/index.mdx @@ -0,0 +1,220 @@ +--- +title: Errors +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: string): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`AuthenticationError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string, stackTrace?: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string, stackTrace?: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string, stackTrace?: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: string): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message?: string, stackTrace?: string): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message`? | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string, stackTrace?: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string, stackTrace?: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.4/filesystem/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.4/filesystem/index.mdx new file mode 100644 index 0000000000..0586f2f1f9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.4/filesystem/index.mdx @@ -0,0 +1,626 @@ +--- +title: Filesystem +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: Username; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.4/sandbox/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.4/sandbox/index.mdx new file mode 100644 index 0000000000..8bf01fc350 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/js-sdk/v2.1.4/sandbox/index.mdx @@ -0,0 +1,682 @@ +--- +title: Sandbox +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | + +#### Methods + +### betaPause() + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Pause a sandbox by its ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +sandbox ID that can be used to resume the sandbox. + +### connect() + +```ts +connect(opts?: SandboxBetaCreateOpts): Promise +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`Sandbox`\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.betaPause() + +// Connect to the same sandbox. +const sameSandbox = await sandbox.connect() +``` + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMetrics() + +```ts +getMetrics(opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxMetricsOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate('') +``` + +###### Constructs + +Sandbox + +### betaPause() + +```ts +static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Pause the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox got paused, `false` if the sandbox was already paused. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: SandboxConnectOpts): Promise> +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Default value | +| ------ | ------ | ------ | +| `cpuCount` | `number` | res.data.cpuCount | +| `endAt` | `Date` | - | +| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | +| `envdVersion` | `string` | res.data.envdVersion | +| `memoryMB` | `number` | res.data.memoryMB | +| `metadata` | `object` | - | +| `name`? | `string` | res.data.alias | +| `sandboxDomain` | `undefined` \| `string` | - | +| `sandboxId` | `string` | res.data.sandboxID | +| `startedAt` | `Date` | - | +| `state` | `"running"` \| `"paused"` | res.data.state | +| `templateId` | `string` | res.data.templateID | + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): SandboxPaginator +``` + +List all sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`SandboxPaginator` + +paginator for listing sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: Username; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.0/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.0/exceptions/index.mdx new file mode 100644 index 0000000000..e0e6ab4c81 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.0/exceptions/index.mdx @@ -0,0 +1,79 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The [unavailable] exception type is caused by sandbox timeout. + +The [canceled] exception type is caused by exceeding request timeout. + +The [deadline_exceeded] exception type is caused by exceeding the timeout for process, watch, etc. + +The [unknown] exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.0/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.0/sandbox_async/index.mdx new file mode 100644 index 0000000000..a7065fad74 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.0/sandbox_async/index.mdx @@ -0,0 +1,928 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +#### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +#### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +#### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +#### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +#### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +#### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +#### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +#### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +#### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +#### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +#### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +#### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +#### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +#### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +#### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +#### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +#### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +#### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +#### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +#### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +#### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +#### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +#### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +#### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +#### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +#### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +#### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +#### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +#### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +#### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +#### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +#### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +#### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +#### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +#### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +#### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +#### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +#### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +#### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +#### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.0/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.0/sandbox_sync/index.mdx new file mode 100644 index 0000000000..72fa0c3a66 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.0/sandbox_sync/index.mdx @@ -0,0 +1,905 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +#### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox info + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +#### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +#### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +#### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +#### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +#### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +#### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +#### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) + + +#### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +#### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +#### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +#### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +#### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +#### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +#### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +#### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +#### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +#### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +#### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +#### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +#### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +#### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +#### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +#### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +#### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +#### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +#### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +#### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +#### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +#### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +#### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +#### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +#### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +#### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +#### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +#### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +#### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.1/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.1/exceptions/index.mdx new file mode 100644 index 0000000000..e0e6ab4c81 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.1/exceptions/index.mdx @@ -0,0 +1,79 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The [unavailable] exception type is caused by sandbox timeout. + +The [canceled] exception type is caused by exceeding request timeout. + +The [deadline_exceeded] exception type is caused by exceeding the timeout for process, watch, etc. + +The [unknown] exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.1/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.1/sandbox_async/index.mdx new file mode 100644 index 0000000000..10f756e7c2 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.1/sandbox_async/index.mdx @@ -0,0 +1,928 @@ +--- +title: Sandbox Async +--- + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +#### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +#### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +#### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +#### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +#### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +#### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +#### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +#### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +#### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +#### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +#### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +#### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +#### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +#### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +#### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +#### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +#### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +#### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +#### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +#### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +#### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +#### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +#### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +#### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +#### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +#### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +#### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +#### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +#### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +#### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +#### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +#### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +#### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +#### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +#### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +#### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +#### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +#### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +#### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +#### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.1/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.1/sandbox_sync/index.mdx new file mode 100644 index 0000000000..b421c18108 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.1/sandbox_sync/index.mdx @@ -0,0 +1,905 @@ +--- +title: Sandbox Sync +--- + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +#### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +#### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +#### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +#### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +#### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +#### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +#### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +#### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +#### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +#### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +#### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +#### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +#### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +#### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +#### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +#### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox info + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +#### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +#### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +#### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +#### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +#### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +#### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +#### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) + + +#### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +#### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +#### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +#### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +#### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +#### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +#### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +#### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +#### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +#### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +#### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +#### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +#### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +#### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.2/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.2/exceptions/index.mdx new file mode 100644 index 0000000000..b5d3bc754e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.2/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The [unavailable] exception type is caused by sandbox timeout. + +The [canceled] exception type is caused by exceeding request timeout. + +The [deadline_exceeded] exception type is caused by exceeding the timeout for process, watch, etc. + +The [unknown] exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.2/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.2/sandbox_async/index.mdx new file mode 100644 index 0000000000..10f756e7c2 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.2/sandbox_async/index.mdx @@ -0,0 +1,928 @@ +--- +title: Sandbox Async +--- + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +#### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +#### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +#### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +#### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +#### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +#### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +#### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +#### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +#### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +#### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +#### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +#### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +#### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +#### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +#### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +#### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +#### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +#### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +#### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +#### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +#### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +#### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +#### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +#### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +#### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +#### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +#### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +#### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +#### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +#### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +#### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +#### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +#### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +#### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +#### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +#### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +#### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +#### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +#### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +#### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.2/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.2/sandbox_sync/index.mdx new file mode 100644 index 0000000000..b421c18108 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.2/sandbox_sync/index.mdx @@ -0,0 +1,905 @@ +--- +title: Sandbox Sync +--- + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +#### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +#### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +#### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +#### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +#### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +#### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +#### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +#### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +#### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +#### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +#### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +#### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +#### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +#### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +#### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +#### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox info + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +#### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +#### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +#### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +#### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +#### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +#### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +#### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) + + +#### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +#### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +#### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +#### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +#### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +#### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +#### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +#### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +#### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +#### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +#### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +#### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +#### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +#### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +#### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.3/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.3/exceptions/index.mdx new file mode 100644 index 0000000000..b5d3bc754e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.3/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The [unavailable] exception type is caused by sandbox timeout. + +The [canceled] exception type is caused by exceeding request timeout. + +The [deadline_exceeded] exception type is caused by exceeding the timeout for process, watch, etc. + +The [unknown] exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.3/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.3/sandbox_async/index.mdx new file mode 100644 index 0000000000..356a88d280 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.3/sandbox_async/index.mdx @@ -0,0 +1,928 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.3/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.3/sandbox_sync/index.mdx new file mode 100644 index 0000000000..8568d95dda --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.3/sandbox_sync/index.mdx @@ -0,0 +1,905 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox info + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.4/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.4/exceptions/index.mdx new file mode 100644 index 0000000000..b5d3bc754e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.4/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The [unavailable] exception type is caused by sandbox timeout. + +The [canceled] exception type is caused by exceeding request timeout. + +The [deadline_exceeded] exception type is caused by exceeding the timeout for process, watch, etc. + +The [unknown] exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.4/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.4/sandbox_async/index.mdx new file mode 100644 index 0000000000..cd126dcca2 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.4/sandbox_async/index.mdx @@ -0,0 +1,928 @@ +--- +title: Sandbox Async +--- + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.4/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.4/sandbox_sync/index.mdx new file mode 100644 index 0000000000..c00adba277 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.4/sandbox_sync/index.mdx @@ -0,0 +1,905 @@ +--- +title: Sandbox Sync +--- + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.5/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.5/exceptions/index.mdx new file mode 100644 index 0000000000..b5d3bc754e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.5/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The [unavailable] exception type is caused by sandbox timeout. + +The [canceled] exception type is caused by exceeding request timeout. + +The [deadline_exceeded] exception type is caused by exceeding the timeout for process, watch, etc. + +The [unknown] exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.5/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.5/sandbox_async/index.mdx new file mode 100644 index 0000000000..cd126dcca2 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.5/sandbox_async/index.mdx @@ -0,0 +1,928 @@ +--- +title: Sandbox Async +--- + + + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.5/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.5/sandbox_sync/index.mdx new file mode 100644 index 0000000000..c00adba277 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.5/sandbox_sync/index.mdx @@ -0,0 +1,905 @@ +--- +title: Sandbox Sync +--- + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.6/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.6/exceptions/index.mdx new file mode 100644 index 0000000000..b5d3bc754e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.6/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The [unavailable] exception type is caused by sandbox timeout. + +The [canceled] exception type is caused by exceeding request timeout. + +The [deadline_exceeded] exception type is caused by exceeding the timeout for process, watch, etc. + +The [unknown] exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.6/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.6/sandbox_async/index.mdx new file mode 100644 index 0000000000..983c056f9c --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.6/sandbox_async/index.mdx @@ -0,0 +1,930 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.6/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.6/sandbox_sync/index.mdx new file mode 100644 index 0000000000..09aaeaa622 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.0.6/sandbox_sync/index.mdx @@ -0,0 +1,908 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox info + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.1.0/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.1.0/exceptions/index.mdx new file mode 100644 index 0000000000..b5d3bc754e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.1.0/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The [unavailable] exception type is caused by sandbox timeout. + +The [canceled] exception type is caused by exceeding request timeout. + +The [deadline_exceeded] exception type is caused by exceeding the timeout for process, watch, etc. + +The [unknown] exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.1.0/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.1.0/sandbox_async/index.mdx new file mode 100644 index 0000000000..f2aa5c3b9b --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.1.0/sandbox_async/index.mdx @@ -0,0 +1,930 @@ +--- +title: Sandbox Async +--- + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.1.0/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.1.0/sandbox_sync/index.mdx new file mode 100644 index 0000000000..6331f9d7a4 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.1.0/sandbox_sync/index.mdx @@ -0,0 +1,908 @@ +--- +title: Sandbox Sync +--- + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.10.0/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.10.0/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.10.0/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.10.0/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.10.0/sandbox_async/index.mdx new file mode 100644 index 0000000000..d750de79dd --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.10.0/sandbox_async/index.mdx @@ -0,0 +1,1166 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +async def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### sandbox\_domain + +```python Python +@property +def sandbox_domain() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None, + allow_internet_access: Optional[bool] = True) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +async def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +async def get_metrics( + sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +async def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.10.0/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.10.0/sandbox_sync/index.mdx new file mode 100644 index 0000000000..84f759f2e5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.10.0/sandbox_sync/index.mdx @@ -0,0 +1,1130 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### sandbox\_domain + +```python Python +@property +def sandbox_domain() -> str +``` + +Domain where the sandbox is hosted. + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + allow_internet_access: Optional[bool] = True) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True` + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +def get_metrics( + sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.0/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.0/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.0/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.0/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.0/sandbox_async/index.mdx new file mode 100644 index 0000000000..d750de79dd --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.0/sandbox_async/index.mdx @@ -0,0 +1,1166 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +async def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### sandbox\_domain + +```python Python +@property +def sandbox_domain() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None, + allow_internet_access: Optional[bool] = True) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +async def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +async def get_metrics( + sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +async def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.0/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.0/sandbox_sync/index.mdx new file mode 100644 index 0000000000..84f759f2e5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.0/sandbox_sync/index.mdx @@ -0,0 +1,1130 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### sandbox\_domain + +```python Python +@property +def sandbox_domain() -> str +``` + +Domain where the sandbox is hosted. + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + allow_internet_access: Optional[bool] = True) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True` + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +def get_metrics( + sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.1/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.1/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.1/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.1/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.1/sandbox_async/index.mdx new file mode 100644 index 0000000000..d750de79dd --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.1/sandbox_async/index.mdx @@ -0,0 +1,1166 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +async def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### sandbox\_domain + +```python Python +@property +def sandbox_domain() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None, + allow_internet_access: Optional[bool] = True) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +async def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +async def get_metrics( + sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +async def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.1/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.1/sandbox_sync/index.mdx new file mode 100644 index 0000000000..84f759f2e5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.11.1/sandbox_sync/index.mdx @@ -0,0 +1,1130 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### sandbox\_domain + +```python Python +@property +def sandbox_domain() -> str +``` + +Domain where the sandbox is hosted. + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + allow_internet_access: Optional[bool] = True) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True` + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +def get_metrics( + sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.0/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.0/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.0/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.0/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.0/sandbox_async/index.mdx new file mode 100644 index 0000000000..6fd2717e3a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.0/sandbox_async/index.mdx @@ -0,0 +1,970 @@ +--- +title: Sandbox Async +--- + + + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.0/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.0/sandbox_sync/index.mdx new file mode 100644 index 0000000000..346828958a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.0/sandbox_sync/index.mdx @@ -0,0 +1,935 @@ +--- +title: Sandbox Sync +--- + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox info + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.1/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.1/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.1/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.1/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.1/sandbox_async/index.mdx new file mode 100644 index 0000000000..b08d565571 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.1/sandbox_async/index.mdx @@ -0,0 +1,974 @@ +--- +title: Sandbox Async +--- + + + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.1/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.1/sandbox_sync/index.mdx new file mode 100644 index 0000000000..1453d2a6b1 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.2.1/sandbox_sync/index.mdx @@ -0,0 +1,939 @@ +--- +title: Sandbox Sync +--- + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.0/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.0/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.0/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.0/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.0/sandbox_async/index.mdx new file mode 100644 index 0000000000..b08d565571 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.0/sandbox_async/index.mdx @@ -0,0 +1,974 @@ +--- +title: Sandbox Async +--- + + + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.0/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.0/sandbox_sync/index.mdx new file mode 100644 index 0000000000..1453d2a6b1 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.0/sandbox_sync/index.mdx @@ -0,0 +1,939 @@ +--- +title: Sandbox Sync +--- + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.1/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.1/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.1/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.1/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.1/sandbox_async/index.mdx new file mode 100644 index 0000000000..f0ae20f7b3 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.1/sandbox_async/index.mdx @@ -0,0 +1,1018 @@ +--- +title: Sandbox Async +--- + + + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +async def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### get\_info + +```python Python +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox id, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.1/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.1/sandbox_sync/index.mdx new file mode 100644 index 0000000000..17dc87035e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.1/sandbox_sync/index.mdx @@ -0,0 +1,983 @@ +--- +title: Sandbox Sync +--- + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + + +### get\_info + +```python Python +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox id, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.2/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.2/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.2/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.2/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.2/sandbox_async/index.mdx new file mode 100644 index 0000000000..bc053c7f82 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.2/sandbox_async/index.mdx @@ -0,0 +1,1018 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +async def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### get\_info + +```python Python +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.2/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.2/sandbox_sync/index.mdx new file mode 100644 index 0000000000..1a6f21c83a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.2/sandbox_sync/index.mdx @@ -0,0 +1,983 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + + +### get\_info + +```python Python +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.3/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.3/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.3/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.3/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.3/sandbox_async/index.mdx new file mode 100644 index 0000000000..b55f963323 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.3/sandbox_async/index.mdx @@ -0,0 +1,1022 @@ +--- +title: Sandbox Async +--- + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### get\_info + +```python Python +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +async def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +Sandbox info + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.3/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.3/sandbox_sync/index.mdx new file mode 100644 index 0000000000..4fe42aee4e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.3/sandbox_sync/index.mdx @@ -0,0 +1,987 @@ +--- +title: Sandbox Sync +--- + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + + +### get\_info + +```python Python +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.4/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.4/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.4/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.4/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.4/sandbox_async/index.mdx new file mode 100644 index 0000000000..b55f963323 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.4/sandbox_async/index.mdx @@ -0,0 +1,1022 @@ +--- +title: Sandbox Async +--- + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### get\_info + +```python Python +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +async def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +Sandbox info + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.4/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.4/sandbox_sync/index.mdx new file mode 100644 index 0000000000..4fe42aee4e --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.4/sandbox_sync/index.mdx @@ -0,0 +1,987 @@ +--- +title: Sandbox Sync +--- + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + + +### get\_info + +```python Python +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.5/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.5/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.5/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.5/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.5/sandbox_async/index.mdx new file mode 100644 index 0000000000..5ea4e635c9 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.5/sandbox_async/index.mdx @@ -0,0 +1,1034 @@ +--- +title: Sandbox Async +--- + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +async def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.5/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.5/sandbox_sync/index.mdx new file mode 100644 index 0000000000..5cf297379d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.3.5/sandbox_sync/index.mdx @@ -0,0 +1,998 @@ +--- +title: Sandbox Sync +--- + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.4.0/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.4.0/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.4.0/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.4.0/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.4.0/sandbox_async/index.mdx new file mode 100644 index 0000000000..925e96e626 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.4.0/sandbox_async/index.mdx @@ -0,0 +1,1036 @@ +--- +title: Sandbox Async +--- + + + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +async def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.4.0/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.4.0/sandbox_sync/index.mdx new file mode 100644 index 0000000000..55718907ad --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.4.0/sandbox_sync/index.mdx @@ -0,0 +1,1000 @@ +--- +title: Sandbox Sync +--- + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.0/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.0/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.0/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.0/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.0/sandbox_async/index.mdx new file mode 100644 index 0000000000..a075e1f15a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.0/sandbox_async/index.mdx @@ -0,0 +1,1038 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +async def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.0/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.0/sandbox_sync/index.mdx new file mode 100644 index 0000000000..f628a5eb5a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.0/sandbox_sync/index.mdx @@ -0,0 +1,1001 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +Sandbox info + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.1/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.1/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.1/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.1/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.1/sandbox_async/index.mdx new file mode 100644 index 0000000000..a075e1f15a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.1/sandbox_async/index.mdx @@ -0,0 +1,1038 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +async def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.1/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.1/sandbox_sync/index.mdx new file mode 100644 index 0000000000..f628a5eb5a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.1/sandbox_sync/index.mdx @@ -0,0 +1,1001 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +Sandbox info + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.2/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.2/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.2/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.2/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.2/sandbox_async/index.mdx new file mode 100644 index 0000000000..ed86274b64 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.2/sandbox_async/index.mdx @@ -0,0 +1,1038 @@ +--- +title: Sandbox Async +--- + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +async def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.2/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.2/sandbox_sync/index.mdx new file mode 100644 index 0000000000..1d93d98353 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.2/sandbox_sync/index.mdx @@ -0,0 +1,1001 @@ +--- +title: Sandbox Sync +--- + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +Sandbox info + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.3/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.3/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.3/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.3/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.3/sandbox_async/index.mdx new file mode 100644 index 0000000000..ed86274b64 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.3/sandbox_async/index.mdx @@ -0,0 +1,1038 @@ +--- +title: Sandbox Async +--- + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +async def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.3/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.3/sandbox_sync/index.mdx new file mode 100644 index 0000000000..1d93d98353 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.3/sandbox_sync/index.mdx @@ -0,0 +1,1001 @@ +--- +title: Sandbox Sync +--- + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +Sandbox info + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.4/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.4/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.4/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.4/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.4/sandbox_async/index.mdx new file mode 100644 index 0000000000..3cd9c5c035 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.4/sandbox_async/index.mdx @@ -0,0 +1,1038 @@ +--- +title: Sandbox Async +--- + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +async def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.4/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.4/sandbox_sync/index.mdx new file mode 100644 index 0000000000..9569be05c4 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.4/sandbox_sync/index.mdx @@ -0,0 +1,1001 @@ +--- +title: Sandbox Sync +--- + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +Sandbox info + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.5/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.5/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.5/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.5/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.5/sandbox_async/index.mdx new file mode 100644 index 0000000000..3cd9c5c035 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.5/sandbox_async/index.mdx @@ -0,0 +1,1038 @@ +--- +title: Sandbox Async +--- + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +async def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.5/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.5/sandbox_sync/index.mdx new file mode 100644 index 0000000000..9569be05c4 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.5/sandbox_sync/index.mdx @@ -0,0 +1,1001 @@ +--- +title: Sandbox Sync +--- + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + +### get\_info + +```python Python +@classmethod +def get_info(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get the sandbox info. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: Domain to use for the request, defaults to `E2B_DOMAIN` environment variable +- `debug`: Debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request + +**Returns**: + +Sandbox info + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.6/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.6/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.6/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.6/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.6/sandbox_async/index.mdx new file mode 100644 index 0000000000..74ff26ff12 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.6/sandbox_async/index.mdx @@ -0,0 +1,1057 @@ +--- +title: Sandbox Async +--- + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.6/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.6/sandbox_sync/index.mdx new file mode 100644 index 0000000000..a9c4da5a39 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.5.6/sandbox_sync/index.mdx @@ -0,0 +1,1021 @@ +--- +title: Sandbox Sync +--- + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.6.0/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.6.0/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.6.0/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.6.0/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.6.0/sandbox_async/index.mdx new file mode 100644 index 0000000000..74ff26ff12 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.6.0/sandbox_async/index.mdx @@ -0,0 +1,1057 @@ +--- +title: Sandbox Async +--- + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.6.0/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.6.0/sandbox_sync/index.mdx new file mode 100644 index 0000000000..a9c4da5a39 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.6.0/sandbox_sync/index.mdx @@ -0,0 +1,1021 @@ +--- +title: Sandbox Sync +--- + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.0/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.0/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.0/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.0/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.0/sandbox_async/index.mdx new file mode 100644 index 0000000000..3d7e6c0f0b --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.0/sandbox_async/index.mdx @@ -0,0 +1,1067 @@ +--- +title: Sandbox Async +--- + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### sandbox\_domain + +```python Python +@property +def sandbox_domain() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.0/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.0/sandbox_sync/index.mdx new file mode 100644 index 0000000000..c0a05858b1 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.0/sandbox_sync/index.mdx @@ -0,0 +1,1031 @@ +--- +title: Sandbox Sync +--- + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### sandbox\_domain + +```python Python +@property +def sandbox_domain() -> str +``` + +Domain where the sandbox is hosted. + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.1/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.1/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.1/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.1/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.1/sandbox_async/index.mdx new file mode 100644 index 0000000000..62cbc6ee26 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.1/sandbox_async/index.mdx @@ -0,0 +1,1067 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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[EntryInfo, List[EntryInfo]] +``` + +Writes content to a file on the path. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### sandbox\_domain + +```python Python +@property +def sandbox_domain() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.1/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.1/sandbox_sync/index.mdx new file mode 100644 index 0000000000..153766b4dc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.7.1/sandbox_sync/index.mdx @@ -0,0 +1,1031 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### sandbox\_domain + +```python Python +@property +def sandbox_domain() -> str +``` + +Domain where the sandbox is hosted. + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.8.0/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.8.0/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.8.0/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.8.0/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.8.0/sandbox_async/index.mdx new file mode 100644 index 0000000000..7b500ae42f --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.8.0/sandbox_async/index.mdx @@ -0,0 +1,1088 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +async def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### sandbox\_domain + +```python Python +@property +def sandbox_domain() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.8.0/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.8.0/sandbox_sync/index.mdx new file mode 100644 index 0000000000..e34af333cc --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.8.0/sandbox_sync/index.mdx @@ -0,0 +1,1052 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### sandbox\_domain + +```python Python +@property +def sandbox_domain() -> str +``` + +Domain where the sandbox is hosted. + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.9.0/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.9.0/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.9.0/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.9.0/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.9.0/sandbox_async/index.mdx new file mode 100644 index 0000000000..32b093ac04 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.9.0/sandbox_async/index.mdx @@ -0,0 +1,1164 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +@overload +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +async def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### write + +```python Python +async def write( + 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. +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. + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +async def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### sandbox\_domain + +```python Python +@property +def sandbox_domain() -> str +``` + +Unique identifier of the sandbox. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None, + secure: Optional[bool] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** +- `secure`: Envd is secured with access token and cannot be used without it + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + +### kill + +```python Python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +async def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +async def get_metrics( + sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +async def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.9.0/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.9.0/sandbox_sync/index.mdx new file mode 100644 index 0000000000..cdb8e953da --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v1.9.0/sandbox_sync/index.mdx @@ -0,0 +1,1128 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxApiBase) +``` + + +### list + +```python Python +@classmethod +def list(cls, + api_key: Optional[str] = None, + query: Optional[SandboxQuery] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> List[ListedSandbox] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `query`: Filter the list of sandboxes, e.g. by metadata `SandboxQuery(metadata={"key": "value"})`, if there are multiple filters they are combined with AND. +- `domain`: Domain to use for the request, only relevant for self-hosted environments +- `debug`: Enable debug mode, all requested are then sent to localhost +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Additional headers to send with the request +- `proxy`: Proxy to use for the request + +**Returns**: + +List of running sandboxes + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +@overload +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write + +```python Python +@overload +def write(files: List[WriteEntry], + user: Optional[Username] = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Sandbox + +```python Python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### sandbox\_id + +```python Python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + +### sandbox\_domain + +```python Python +@property +def sandbox_domain() -> str +``` + +Domain where the sandbox is hosted. + + +### \_\_init\_\_ + +```python Python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. 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 +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the new sandbox + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### connect + +```python Python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + proxy: Optional[ProxyTypes] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `proxy`: Proxy to use for the request and for the **requests made to the returned sandbox** + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python Python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) +``` + + +### kill + +```python Python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + proxy: Optional[ProxyTypes] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `proxy`: Proxy to use for the request + + +### get\_info + +```python Python +@overload +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + proxy: Optional[ProxyTypes] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `domain`: E2B domain to use for authentication, defaults to `E2B_DOMAIN` environment variable +- `debug`: Whether to use debug mode, defaults to `E2B_DEBUG` environment variable +- `request_timeout`: Timeout for the request in **seconds** +- `headers`: Custom headers to use for the request +- `proxy`: Proxy to use for the request + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(request_timeout: Optional[float] = None) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +def get_metrics( + sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +def get_metrics( + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + request_timeout: Optional[float] = None) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to current time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.0/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.0/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.0/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.0/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.0/sandbox_async/index.mdx new file mode 100644 index 0000000000..a78a154345 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.0/sandbox_async/index.mdx @@ -0,0 +1,1285 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxBase) +``` + + +### list + +```python Python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write\_files + +```python Python +async def write_files( + files: List[WriteEntry], + user: Username = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +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. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +async def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncSandboxPaginator + +```python Python +class AsyncSandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python Python +paginator = AsyncSandbox.list() + +while paginator.has_next: + sandboxes = await paginator.next_items() + print(sandboxes) +``` + + +### next\_items + +```python Python +async def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@overload +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + +### connect + +```python Python +@overload +@classmethod +async def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await AsyncSandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) +``` + + +### connect + +```python Python +@class_method_variant("_cls_connect") +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + +### kill + +```python Python +@overload +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@class_method_variant("_cls_set_timeout") +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### get\_info + +```python Python +@overload +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +async def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### beta\_create + +```python Python +@classmethod +async def beta_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: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_pause + +```python Python +@overload +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + +### beta\_pause + +```python Python +@overload +@staticmethod +async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + +### beta\_pause + +```python Python +@class_method_variant("_cls_pause") +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.0/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.0/sandbox_sync/index.mdx new file mode 100644 index 0000000000..486cabaea5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.0/sandbox_sync/index.mdx @@ -0,0 +1,1244 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxBase) +``` + + +### list + +```python Python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write\_files + +```python Python +def write_files(files: List[WriteEntry], + user: Username = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## SandboxPaginator + +```python Python +class SandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python Python +paginator = Sandbox.list() + +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) +``` + + +### next\_items + +```python Python +def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + +## Sandbox + +```python Python +class Sandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +:deprecated: This constructor is deprecated + +Use `Sandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox.create() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@overload +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() + + +### connect + +```python Python +@overload +@classmethod +def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +Sandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + +### connect + +```python Python +@class_method_variant("_cls_connect") +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() +``` + + +### kill + +```python Python +@overload +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@class_method_variant("_cls_set_timeout") +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### get\_info + +```python Python +@overload +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### beta\_create + +```python Python +@classmethod +def beta_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: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_pause + +```python Python +@overload +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + + +### beta\_pause + +```python Python +@overload +@classmethod +def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + + +### beta\_pause + +```python Python +@class_method_variant("_cls_pause") +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.1/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.1/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.1/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.1/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.1/sandbox_async/index.mdx new file mode 100644 index 0000000000..a78a154345 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.1/sandbox_async/index.mdx @@ -0,0 +1,1285 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxBase) +``` + + +### list + +```python Python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write\_files + +```python Python +async def write_files( + files: List[WriteEntry], + user: Username = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +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. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +async def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncSandboxPaginator + +```python Python +class AsyncSandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python Python +paginator = AsyncSandbox.list() + +while paginator.has_next: + sandboxes = await paginator.next_items() + print(sandboxes) +``` + + +### next\_items + +```python Python +async def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@overload +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + +### connect + +```python Python +@overload +@classmethod +async def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await AsyncSandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) +``` + + +### connect + +```python Python +@class_method_variant("_cls_connect") +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + +### kill + +```python Python +@overload +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@class_method_variant("_cls_set_timeout") +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### get\_info + +```python Python +@overload +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +async def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### beta\_create + +```python Python +@classmethod +async def beta_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: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_pause + +```python Python +@overload +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + +### beta\_pause + +```python Python +@overload +@staticmethod +async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + +### beta\_pause + +```python Python +@class_method_variant("_cls_pause") +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.1/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.1/sandbox_sync/index.mdx new file mode 100644 index 0000000000..486cabaea5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.1/sandbox_sync/index.mdx @@ -0,0 +1,1244 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxBase) +``` + + +### list + +```python Python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write\_files + +```python Python +def write_files(files: List[WriteEntry], + user: Username = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## SandboxPaginator + +```python Python +class SandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python Python +paginator = Sandbox.list() + +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) +``` + + +### next\_items + +```python Python +def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + +## Sandbox + +```python Python +class Sandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +:deprecated: This constructor is deprecated + +Use `Sandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox.create() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@overload +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() + + +### connect + +```python Python +@overload +@classmethod +def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +Sandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + +### connect + +```python Python +@class_method_variant("_cls_connect") +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() +``` + + +### kill + +```python Python +@overload +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@class_method_variant("_cls_set_timeout") +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### get\_info + +```python Python +@overload +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### beta\_create + +```python Python +@classmethod +def beta_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: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_pause + +```python Python +@overload +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + + +### beta\_pause + +```python Python +@overload +@classmethod +def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + + +### beta\_pause + +```python Python +@class_method_variant("_cls_pause") +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.2/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.2/exceptions/index.mdx new file mode 100644 index 0000000000..6b5220bd78 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.2/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.2/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.2/sandbox_async/index.mdx new file mode 100644 index 0000000000..a78a154345 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.2/sandbox_async/index.mdx @@ -0,0 +1,1285 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxBase) +``` + + +### list + +```python Python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write\_files + +```python Python +async def write_files( + files: List[WriteEntry], + user: Username = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +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. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +async def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncSandboxPaginator + +```python Python +class AsyncSandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python Python +paginator = AsyncSandbox.list() + +while paginator.has_next: + sandboxes = await paginator.next_items() + print(sandboxes) +``` + + +### next\_items + +```python Python +async def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@overload +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + +### connect + +```python Python +@overload +@classmethod +async def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await AsyncSandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) +``` + + +### connect + +```python Python +@class_method_variant("_cls_connect") +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + +### kill + +```python Python +@overload +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@class_method_variant("_cls_set_timeout") +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### get\_info + +```python Python +@overload +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +async def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### beta\_create + +```python Python +@classmethod +async def beta_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: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_pause + +```python Python +@overload +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + +### beta\_pause + +```python Python +@overload +@staticmethod +async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + +### beta\_pause + +```python Python +@class_method_variant("_cls_pause") +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.2/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.2/sandbox_sync/index.mdx new file mode 100644 index 0000000000..486cabaea5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.0.2/sandbox_sync/index.mdx @@ -0,0 +1,1244 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxBase) +``` + + +### list + +```python Python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write\_files + +```python Python +def write_files(files: List[WriteEntry], + user: Username = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## SandboxPaginator + +```python Python +class SandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python Python +paginator = Sandbox.list() + +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) +``` + + +### next\_items + +```python Python +def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + +## Sandbox + +```python Python +class Sandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +:deprecated: This constructor is deprecated + +Use `Sandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox.create() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@overload +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() + + +### connect + +```python Python +@overload +@classmethod +def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +Sandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + +### connect + +```python Python +@class_method_variant("_cls_connect") +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() +``` + + +### kill + +```python Python +@overload +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@class_method_variant("_cls_set_timeout") +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### get\_info + +```python Python +@overload +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### beta\_create + +```python Python +@classmethod +def beta_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: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_pause + +```python Python +@overload +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + + +### beta\_pause + +```python Python +@overload +@classmethod +def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + + +### beta\_pause + +```python Python +@class_method_variant("_cls_pause") +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.0/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.0/exceptions/index.mdx new file mode 100644 index 0000000000..e02a276a10 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.0/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(Exception) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.0/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.0/sandbox_async/index.mdx new file mode 100644 index 0000000000..a78a154345 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.0/sandbox_async/index.mdx @@ -0,0 +1,1285 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxBase) +``` + + +### list + +```python Python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write\_files + +```python Python +async def write_files( + files: List[WriteEntry], + user: Username = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +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. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +async def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncSandboxPaginator + +```python Python +class AsyncSandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python Python +paginator = AsyncSandbox.list() + +while paginator.has_next: + sandboxes = await paginator.next_items() + print(sandboxes) +``` + + +### next\_items + +```python Python +async def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@overload +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + +### connect + +```python Python +@overload +@classmethod +async def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await AsyncSandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) +``` + + +### connect + +```python Python +@class_method_variant("_cls_connect") +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + +### kill + +```python Python +@overload +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@class_method_variant("_cls_set_timeout") +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### get\_info + +```python Python +@overload +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +async def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### beta\_create + +```python Python +@classmethod +async def beta_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: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_pause + +```python Python +@overload +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + +### beta\_pause + +```python Python +@overload +@staticmethod +async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + +### beta\_pause + +```python Python +@class_method_variant("_cls_pause") +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.0/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.0/sandbox_sync/index.mdx new file mode 100644 index 0000000000..486cabaea5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.0/sandbox_sync/index.mdx @@ -0,0 +1,1244 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxBase) +``` + + +### list + +```python Python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write\_files + +```python Python +def write_files(files: List[WriteEntry], + user: Username = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## SandboxPaginator + +```python Python +class SandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python Python +paginator = Sandbox.list() + +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) +``` + + +### next\_items + +```python Python +def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + +## Sandbox + +```python Python +class Sandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +:deprecated: This constructor is deprecated + +Use `Sandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox.create() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@overload +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() + + +### connect + +```python Python +@overload +@classmethod +def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +Sandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + +### connect + +```python Python +@class_method_variant("_cls_connect") +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() +``` + + +### kill + +```python Python +@overload +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@class_method_variant("_cls_set_timeout") +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### get\_info + +```python Python +@overload +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### beta\_create + +```python Python +@classmethod +def beta_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: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_pause + +```python Python +@overload +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + + +### beta\_pause + +```python Python +@overload +@classmethod +def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + + +### beta\_pause + +```python Python +@class_method_variant("_cls_pause") +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.1/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.1/exceptions/index.mdx new file mode 100644 index 0000000000..e02a276a10 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.1/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(Exception) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.1/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.1/sandbox_async/index.mdx new file mode 100644 index 0000000000..a78a154345 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.1/sandbox_async/index.mdx @@ -0,0 +1,1285 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxBase) +``` + + +### list + +```python Python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write\_files + +```python Python +async def write_files( + files: List[WriteEntry], + user: Username = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +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. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +async def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncSandboxPaginator + +```python Python +class AsyncSandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python Python +paginator = AsyncSandbox.list() + +while paginator.has_next: + sandboxes = await paginator.next_items() + print(sandboxes) +``` + + +### next\_items + +```python Python +async def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@overload +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + +### connect + +```python Python +@overload +@classmethod +async def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await AsyncSandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) +``` + + +### connect + +```python Python +@class_method_variant("_cls_connect") +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + +### kill + +```python Python +@overload +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@class_method_variant("_cls_set_timeout") +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### get\_info + +```python Python +@overload +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +async def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### beta\_create + +```python Python +@classmethod +async def beta_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: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_pause + +```python Python +@overload +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + +### beta\_pause + +```python Python +@overload +@staticmethod +async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + +### beta\_pause + +```python Python +@class_method_variant("_cls_pause") +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.1/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.1/sandbox_sync/index.mdx new file mode 100644 index 0000000000..486cabaea5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.1/sandbox_sync/index.mdx @@ -0,0 +1,1244 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxBase) +``` + + +### list + +```python Python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write\_files + +```python Python +def write_files(files: List[WriteEntry], + user: Username = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## SandboxPaginator + +```python Python +class SandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python Python +paginator = Sandbox.list() + +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) +``` + + +### next\_items + +```python Python +def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + +## Sandbox + +```python Python +class Sandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +:deprecated: This constructor is deprecated + +Use `Sandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox.create() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@overload +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() + + +### connect + +```python Python +@overload +@classmethod +def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +Sandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + +### connect + +```python Python +@class_method_variant("_cls_connect") +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() +``` + + +### kill + +```python Python +@overload +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@class_method_variant("_cls_set_timeout") +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### get\_info + +```python Python +@overload +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### beta\_create + +```python Python +@classmethod +def beta_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: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_pause + +```python Python +@overload +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + + +### beta\_pause + +```python Python +@overload +@classmethod +def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + + +### beta\_pause + +```python Python +@class_method_variant("_cls_pause") +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.2/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.2/exceptions/index.mdx new file mode 100644 index 0000000000..e02a276a10 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.2/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(Exception) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.2/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.2/sandbox_async/index.mdx new file mode 100644 index 0000000000..a78a154345 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.2/sandbox_async/index.mdx @@ -0,0 +1,1285 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxBase) +``` + + +### list + +```python Python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write\_files + +```python Python +async def write_files( + files: List[WriteEntry], + user: Username = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +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. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +async def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncSandboxPaginator + +```python Python +class AsyncSandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python Python +paginator = AsyncSandbox.list() + +while paginator.has_next: + sandboxes = await paginator.next_items() + print(sandboxes) +``` + + +### next\_items + +```python Python +async def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@overload +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + +### connect + +```python Python +@overload +@classmethod +async def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await AsyncSandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) +``` + + +### connect + +```python Python +@class_method_variant("_cls_connect") +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + +### kill + +```python Python +@overload +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@class_method_variant("_cls_set_timeout") +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### get\_info + +```python Python +@overload +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +async def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### beta\_create + +```python Python +@classmethod +async def beta_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: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_pause + +```python Python +@overload +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + +### beta\_pause + +```python Python +@overload +@staticmethod +async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + +### beta\_pause + +```python Python +@class_method_variant("_cls_pause") +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.2/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.2/sandbox_sync/index.mdx new file mode 100644 index 0000000000..486cabaea5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.2/sandbox_sync/index.mdx @@ -0,0 +1,1244 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxBase) +``` + + +### list + +```python Python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write\_files + +```python Python +def write_files(files: List[WriteEntry], + user: Username = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## SandboxPaginator + +```python Python +class SandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python Python +paginator = Sandbox.list() + +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) +``` + + +### next\_items + +```python Python +def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + +## Sandbox + +```python Python +class Sandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +:deprecated: This constructor is deprecated + +Use `Sandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox.create() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@overload +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() + + +### connect + +```python Python +@overload +@classmethod +def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +Sandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + +### connect + +```python Python +@class_method_variant("_cls_connect") +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() +``` + + +### kill + +```python Python +@overload +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@class_method_variant("_cls_set_timeout") +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### get\_info + +```python Python +@overload +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### beta\_create + +```python Python +@classmethod +def beta_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: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_pause + +```python Python +@overload +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + + +### beta\_pause + +```python Python +@overload +@classmethod +def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + + +### beta\_pause + +```python Python +@class_method_variant("_cls_pause") +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.3/exceptions/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.3/exceptions/index.mdx new file mode 100644 index 0000000000..e02a276a10 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.3/exceptions/index.mdx @@ -0,0 +1,88 @@ +--- +title: Exceptions +--- + + + + +## SandboxException + +```python Python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + +## TimeoutException + +```python Python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + +## InvalidArgumentException + +```python Python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + +## NotEnoughSpaceException + +```python Python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + +## NotFoundException + +```python Python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + +## AuthenticationException + +```python Python +class AuthenticationException(Exception) +``` + +Raised when authentication fails. + + +## TemplateException + +```python Python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + +## RateLimitException + +```python Python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.3/sandbox_async/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.3/sandbox_async/index.mdx new file mode 100644 index 0000000000..a78a154345 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.3/sandbox_async/index.mdx @@ -0,0 +1,1285 @@ +--- +title: Sandbox Async +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxBase) +``` + + +### list + +```python Python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + +### connect + +```python Python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + +## AsyncCommandHandle + +```python Python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### stdout + +```python Python +@property +def stdout() +``` + +Command stdout output. + + +### stderr + +```python Python +@property +def stderr() +``` + +Command stderr output. + + +### error + +```python Python +@property +def error() +``` + +Command execution error message. + + +### exit\_code + +```python Python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + +### disconnect + +```python Python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + +## AsyncWatchHandle + +```python Python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +async def stop() +``` + +Stop watching the directory. + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + +### write + +```python Python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write\_files + +```python Python +async def write_files( + files: List[WriteEntry], + user: Username = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +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. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +async def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +async def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + +## AsyncSandboxPaginator + +```python Python +class AsyncSandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python Python +paginator = AsyncSandbox.list() + +while paginator.has_next: + sandboxes = await paginator.next_items() + print(sandboxes) +``` + + +### next\_items + +```python Python +async def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + +## AsyncSandbox + +```python Python +class AsyncSandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: Optional[bool] = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@overload +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + +### connect + +```python Python +@overload +@classmethod +async def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await AsyncSandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) +``` + + +### connect + +```python Python +@class_method_variant("_cls_connect") +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + +### kill + +```python Python +@overload +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@class_method_variant("_cls_set_timeout") +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### get\_info + +```python Python +@overload +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +async def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### beta\_create + +```python Python +@classmethod +async def beta_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: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_pause + +```python Python +@overload +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + +### beta\_pause + +```python Python +@overload +@staticmethod +async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + +### beta\_pause + +```python Python +@class_method_variant("_cls_pause") +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.3/sandbox_sync/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.3/sandbox_sync/index.mdx new file mode 100644 index 0000000000..486cabaea5 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk-reference/python-sdk/v2.1.3/sandbox_sync/index.mdx @@ -0,0 +1,1244 @@ +--- +title: Sandbox Sync +--- + + + + +## SandboxApi + +```python Python +class SandboxApi(SandboxBase) +``` + + +### list + +```python Python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + +## Commands + +```python Python +class Commands() +``` + +Module for executing commands in the sandbox. + + +### list + +```python Python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + +### run + +```python Python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + +### run + +```python Python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + +### connect + +```python Python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + +## CommandHandle + +```python Python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + +### pid + +```python Python +@property +def pid() +``` + +Command process ID. + + +### \_\_iter\_\_ + +```python Python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + +### disconnect + +```python Python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + +### wait + +```python Python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + +### kill + +```python Python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + +## Pty + +```python Python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + +### kill + +```python Python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + +### send\_stdin + +```python Python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + +### create + +```python Python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + +### resize + +```python Python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + +## WatchHandle + +```python Python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + +### stop + +```python Python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + +### get\_new\_events + +```python Python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + +## Filesystem + +```python Python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + +### read + +```python Python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + +### write + +```python Python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> 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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + +### write\_files + +```python Python +def write_files(files: List[WriteEntry], + user: Username = "user", + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +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. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + +### list + +```python Python +def list(path: str, + depth: Optional[int] = 1, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + +### exists + +```python Python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + +### get\_info + +```python Python +def get_info(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + +### remove + +```python Python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + +### rename + +```python Python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + +### make\_dir + +```python Python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + +### watch\_dir + +```python Python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + +## SandboxPaginator + +```python Python +class SandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python Python +paginator = Sandbox.list() + +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) +``` + + +### next\_items + +```python Python +def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + +## Sandbox + +```python Python +class Sandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](/). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python Python +from e2b import Sandbox + +sandbox = Sandbox.create() +``` + + +### files + +```python Python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + +### commands + +```python Python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + +### pty + +```python Python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + +### \_\_init\_\_ + +```python Python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +:deprecated: This constructor is deprecated + +Use `Sandbox.create()` to create a new sandbox instead. + + +### is\_running + +```python Python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python Python +sandbox = Sandbox.create() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + +### create + +```python Python +@classmethod +def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### connect + +```python Python +@overload +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() + + +### connect + +```python Python +@overload +@classmethod +def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +Sandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + +### connect + +```python Python +@class_method_variant("_cls_connect") +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + +**Returns**: + +A running sandbox instance +@example +```python Python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() +``` + + +### kill + +```python Python +@overload +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@overload +@staticmethod +def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### kill + +```python Python +@class_method_variant("_cls_kill") +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + +### set\_timeout + +```python Python +@overload +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@overload +@staticmethod +def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + +### set\_timeout + +```python Python +@class_method_variant("_cls_set_timeout") +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +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. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + +### get\_info + +```python Python +@overload +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@overload +@staticmethod +def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + +### get\_info + +```python Python +@class_method_variant("_cls_get_info") +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + +### get\_metrics + +```python Python +@overload +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@overload +@staticmethod +def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### get\_metrics + +```python Python +@class_method_variant("_cls_get_metrics") +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + +### beta\_create + +```python Python +@classmethod +def beta_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: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `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. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + +### beta\_pause + +```python Python +@overload +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + + +### beta\_pause + +```python Python +@overload +@classmethod +def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + + +### beta\_pause + +```python Python +@class_method_variant("_cls_pause") +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + diff --git a/apps/web/src/app/(docs)/mintlify-docs/sdk_navigation.json b/apps/web/src/app/(docs)/mintlify-docs/sdk_navigation.json new file mode 100644 index 0000000000..94c094999d --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/sdk_navigation.json @@ -0,0 +1,2398 @@ +[ + { + "dropdown": "CLI", + "icon": "terminal", + "versions": [ + { + "version": "v2.2.0@latest", + "groups": [ + { + "group": "CLI v2.2.0", + "pages": [ + "sdk-reference/cli/v2.2.0/auth/index", + "sdk-reference/cli/v2.2.0/sandbox/index", + "sdk-reference/cli/v2.2.0/template/index" + ] + } + ] + }, + { + "version": "v2.1.0", + "groups": [ + { + "group": "CLI v2.1.0", + "pages": [ + "sdk-reference/cli/v2.1.0/auth/index", + "sdk-reference/cli/v2.1.0/sandbox/index", + "sdk-reference/cli/v2.1.0/template/index" + ] + } + ] + }, + { + "version": "v2.0.3", + "groups": [ + { + "group": "CLI v2.0.3", + "pages": [ + "sdk-reference/cli/v2.0.3/auth/index", + "sdk-reference/cli/v2.0.3/sandbox/index", + "sdk-reference/cli/v2.0.3/template/index" + ] + } + ] + }, + { + "version": "v2.0.2", + "groups": [ + { + "group": "CLI v2.0.2", + "pages": [ + "sdk-reference/cli/v2.0.2/auth/index", + "sdk-reference/cli/v2.0.2/sandbox/index", + "sdk-reference/cli/v2.0.2/template/index" + ] + } + ] + }, + { + "version": "v2.0.1", + "groups": [ + { + "group": "CLI v2.0.1", + "pages": [ + "sdk-reference/cli/v2.0.1/auth/index", + "sdk-reference/cli/v2.0.1/sandbox/index", + "sdk-reference/cli/v2.0.1/template/index" + ] + } + ] + }, + { + "version": "v2.0.0", + "groups": [ + { + "group": "CLI v2.0.0", + "pages": [ + "sdk-reference/cli/v2.0.0/auth/index", + "sdk-reference/cli/v2.0.0/sandbox/index", + "sdk-reference/cli/v2.0.0/template/index" + ] + } + ] + }, + { + "version": "v1.9.2", + "groups": [ + { + "group": "CLI v1.9.2", + "pages": [ + "sdk-reference/cli/v1.9.2/auth/index", + "sdk-reference/cli/v1.9.2/sandbox/index", + "sdk-reference/cli/v1.9.2/template/index" + ] + } + ] + }, + { + "version": "v1.9.1", + "groups": [ + { + "group": "CLI v1.9.1", + "pages": [ + "sdk-reference/cli/v1.9.1/auth/index", + "sdk-reference/cli/v1.9.1/sandbox/index", + "sdk-reference/cli/v1.9.1/template/index" + ] + } + ] + }, + { + "version": "v1.9.0", + "groups": [ + { + "group": "CLI v1.9.0", + "pages": [ + "sdk-reference/cli/v1.9.0/auth/index", + "sdk-reference/cli/v1.9.0/sandbox/index", + "sdk-reference/cli/v1.9.0/template/index" + ] + } + ] + }, + { + "version": "v1.8.0", + "groups": [ + { + "group": "CLI v1.8.0", + "pages": [ + "sdk-reference/cli/v1.8.0/auth/index", + "sdk-reference/cli/v1.8.0/sandbox/index", + "sdk-reference/cli/v1.8.0/template/index" + ] + } + ] + }, + { + "version": "v1.7.0", + "groups": [ + { + "group": "CLI v1.7.0", + "pages": [ + "sdk-reference/cli/v1.7.0/auth/index", + "sdk-reference/cli/v1.7.0/sandbox/index", + "sdk-reference/cli/v1.7.0/template/index" + ] + } + ] + }, + { + "version": "v1.6.0", + "groups": [ + { + "group": "CLI v1.6.0", + "pages": [ + "sdk-reference/cli/v1.6.0/auth/index", + "sdk-reference/cli/v1.6.0/sandbox/index", + "sdk-reference/cli/v1.6.0/template/index" + ] + } + ] + }, + { + "version": "v1.5.2", + "groups": [ + { + "group": "CLI v1.5.2", + "pages": [ + "sdk-reference/cli/v1.5.2/auth/index", + "sdk-reference/cli/v1.5.2/sandbox/index", + "sdk-reference/cli/v1.5.2/template/index" + ] + } + ] + }, + { + "version": "v1.5.1", + "groups": [ + { + "group": "CLI v1.5.1", + "pages": [ + "sdk-reference/cli/v1.5.1/auth/index", + "sdk-reference/cli/v1.5.1/sandbox/index", + "sdk-reference/cli/v1.5.1/template/index" + ] + } + ] + }, + { + "version": "v1.5.0", + "groups": [ + { + "group": "CLI v1.5.0", + "pages": [ + "sdk-reference/cli/v1.5.0/auth/index", + "sdk-reference/cli/v1.5.0/sandbox/index", + "sdk-reference/cli/v1.5.0/template/index" + ] + } + ] + }, + { + "version": "v1.4.3", + "groups": [ + { + "group": "CLI v1.4.3", + "pages": [ + "sdk-reference/cli/v1.4.3/auth/index", + "sdk-reference/cli/v1.4.3/sandbox/index", + "sdk-reference/cli/v1.4.3/template/index" + ] + } + ] + }, + { + "version": "v1.4.2", + "groups": [ + { + "group": "CLI v1.4.2", + "pages": [ + "sdk-reference/cli/v1.4.2/auth/index", + "sdk-reference/cli/v1.4.2/sandbox/index", + "sdk-reference/cli/v1.4.2/template/index" + ] + } + ] + }, + { + "version": "v1.4.1", + "groups": [ + { + "group": "CLI v1.4.1", + "pages": [ + "sdk-reference/cli/v1.4.1/auth/index", + "sdk-reference/cli/v1.4.1/sandbox/index", + "sdk-reference/cli/v1.4.1/template/index" + ] + } + ] + }, + { + "version": "v1.4.0", + "groups": [ + { + "group": "CLI v1.4.0", + "pages": [ + "sdk-reference/cli/v1.4.0/auth/index", + "sdk-reference/cli/v1.4.0/sandbox/index", + "sdk-reference/cli/v1.4.0/template/index" + ] + } + ] + }, + { + "version": "v1.3.4", + "groups": [ + { + "group": "CLI v1.3.4", + "pages": [ + "sdk-reference/cli/v1.3.4/auth/index", + "sdk-reference/cli/v1.3.4/sandbox/index", + "sdk-reference/cli/v1.3.4/template/index" + ] + } + ] + }, + { + "version": "v1.3.3", + "groups": [ + { + "group": "CLI v1.3.3", + "pages": [ + "sdk-reference/cli/v1.3.3/auth/index", + "sdk-reference/cli/v1.3.3/sandbox/index", + "sdk-reference/cli/v1.3.3/template/index" + ] + } + ] + }, + { + "version": "v1.3.2", + "groups": [ + { + "group": "CLI v1.3.2", + "pages": [ + "sdk-reference/cli/v1.3.2/auth/index", + "sdk-reference/cli/v1.3.2/sandbox/index", + "sdk-reference/cli/v1.3.2/template/index" + ] + } + ] + }, + { + "version": "v1.3.1", + "groups": [ + { + "group": "CLI v1.3.1", + "pages": [ + "sdk-reference/cli/v1.3.1/auth/index", + "sdk-reference/cli/v1.3.1/sandbox/index", + "sdk-reference/cli/v1.3.1/template/index" + ] + } + ] + }, + { + "version": "v1.3.0", + "groups": [ + { + "group": "CLI v1.3.0", + "pages": [ + "sdk-reference/cli/v1.3.0/auth/index", + "sdk-reference/cli/v1.3.0/sandbox/index", + "sdk-reference/cli/v1.3.0/template/index" + ] + } + ] + }, + { + "version": "v1.2.3", + "groups": [ + { + "group": "CLI v1.2.3", + "pages": [ + "sdk-reference/cli/v1.2.3/auth/index", + "sdk-reference/cli/v1.2.3/sandbox/index", + "sdk-reference/cli/v1.2.3/template/index" + ] + } + ] + }, + { + "version": "v1.2.2", + "groups": [ + { + "group": "CLI v1.2.2", + "pages": [ + "sdk-reference/cli/v1.2.2/auth/index", + "sdk-reference/cli/v1.2.2/sandbox/index", + "sdk-reference/cli/v1.2.2/template/index" + ] + } + ] + }, + { + "version": "v1.2.1", + "groups": [ + { + "group": "CLI v1.2.1", + "pages": [ + "sdk-reference/cli/v1.2.1/auth/index", + "sdk-reference/cli/v1.2.1/sandbox/index", + "sdk-reference/cli/v1.2.1/template/index" + ] + } + ] + }, + { + "version": "v1.2.0", + "groups": [ + { + "group": "CLI v1.2.0", + "pages": [ + "sdk-reference/cli/v1.2.0/auth/index", + "sdk-reference/cli/v1.2.0/sandbox/index", + "sdk-reference/cli/v1.2.0/template/index" + ] + } + ] + }, + { + "version": "v1.0.10", + "groups": [ + { + "group": "CLI v1.0.10", + "pages": [ + "sdk-reference/cli/v1.0.10/auth/index", + "sdk-reference/cli/v1.0.10/sandbox/index", + "sdk-reference/cli/v1.0.10/template/index" + ] + } + ] + }, + { + "version": "v1.0.9", + "groups": [ + { + "group": "CLI v1.0.9", + "pages": [ + "sdk-reference/cli/v1.0.9/auth/index", + "sdk-reference/cli/v1.0.9/sandbox/index", + "sdk-reference/cli/v1.0.9/template/index" + ] + } + ] + }, + { + "version": "v1.0.8", + "groups": [ + { + "group": "CLI v1.0.8", + "pages": [ + "sdk-reference/cli/v1.0.8/auth/index", + "sdk-reference/cli/v1.0.8/sandbox/index", + "sdk-reference/cli/v1.0.8/template/index" + ] + } + ] + }, + { + "version": "v1.0.7", + "groups": [ + { + "group": "CLI v1.0.7", + "pages": [ + "sdk-reference/cli/v1.0.7/auth/index", + "sdk-reference/cli/v1.0.7/sandbox/index", + "sdk-reference/cli/v1.0.7/template/index" + ] + } + ] + }, + { + "version": "v1.0.6", + "groups": [ + { + "group": "CLI v1.0.6", + "pages": [ + "sdk-reference/cli/v1.0.6/auth/index", + "sdk-reference/cli/v1.0.6/sandbox/index", + "sdk-reference/cli/v1.0.6/template/index" + ] + } + ] + }, + { + "version": "v1.0.5", + "groups": [ + { + "group": "CLI v1.0.5", + "pages": [ + "sdk-reference/cli/v1.0.5/auth/index", + "sdk-reference/cli/v1.0.5/sandbox/index", + "sdk-reference/cli/v1.0.5/template/index" + ] + } + ] + }, + { + "version": "v1.0.4", + "groups": [ + { + "group": "CLI v1.0.4", + "pages": [ + "sdk-reference/cli/v1.0.4/auth/index", + "sdk-reference/cli/v1.0.4/sandbox/index", + "sdk-reference/cli/v1.0.4/template/index" + ] + } + ] + }, + { + "version": "v1.0.3", + "groups": [ + { + "group": "CLI v1.0.3", + "pages": [ + "sdk-reference/cli/v1.0.3/auth/index", + "sdk-reference/cli/v1.0.3/sandbox/index", + "sdk-reference/cli/v1.0.3/template/index" + ] + } + ] + }, + { + "version": "v1.0.2", + "groups": [ + { + "group": "CLI v1.0.2", + "pages": [ + "sdk-reference/cli/v1.0.2/auth/index", + "sdk-reference/cli/v1.0.2/sandbox/index", + "sdk-reference/cli/v1.0.2/template/index" + ] + } + ] + }, + { + "version": "v1.0.1", + "groups": [ + { + "group": "CLI v1.0.1", + "pages": [ + "sdk-reference/cli/v1.0.1/auth/index", + "sdk-reference/cli/v1.0.1/sandbox/index", + "sdk-reference/cli/v1.0.1/template/index" + ] + } + ] + }, + { + "version": "v1.0.0", + "groups": [ + { + "group": "CLI v1.0.0", + "pages": [ + "sdk-reference/cli/v1.0.0/auth/index", + "sdk-reference/cli/v1.0.0/sandbox/index", + "sdk-reference/cli/v1.0.0/template/index" + ] + } + ] + } + ] + }, + { + "dropdown": "JavaScript SDK", + "icon": "square-js", + "versions": [ + { + "version": "v2.1.4@latest", + "groups": [ + { + "group": "JavaScript SDK v2.1.4", + "pages": [ + "sdk-reference/js-sdk/v2.1.4/commands/index", + "sdk-reference/js-sdk/v2.1.4/errors/index", + "sdk-reference/js-sdk/v2.1.4/filesystem/index", + "sdk-reference/js-sdk/v2.1.4/sandbox/index" + ] + } + ] + }, + { + "version": "v2.1.3", + "groups": [ + { + "group": "JavaScript SDK v2.1.3", + "pages": [ + "sdk-reference/js-sdk/v2.1.3/commands/index", + "sdk-reference/js-sdk/v2.1.3/errors/index", + "sdk-reference/js-sdk/v2.1.3/filesystem/index", + "sdk-reference/js-sdk/v2.1.3/sandbox/index" + ] + } + ] + }, + { + "version": "v2.1.2", + "groups": [ + { + "group": "JavaScript SDK v2.1.2", + "pages": [ + "sdk-reference/js-sdk/v2.1.2/commands/index", + "sdk-reference/js-sdk/v2.1.2/errors/index", + "sdk-reference/js-sdk/v2.1.2/filesystem/index", + "sdk-reference/js-sdk/v2.1.2/sandbox/index" + ] + } + ] + }, + { + "version": "v2.1.1", + "groups": [ + { + "group": "JavaScript SDK v2.1.1", + "pages": [ + "sdk-reference/js-sdk/v2.1.1/commands/index", + "sdk-reference/js-sdk/v2.1.1/errors/index", + "sdk-reference/js-sdk/v2.1.1/filesystem/index", + "sdk-reference/js-sdk/v2.1.1/sandbox/index" + ] + } + ] + }, + { + "version": "v2.1.0", + "groups": [ + { + "group": "JavaScript SDK v2.1.0", + "pages": [ + "sdk-reference/js-sdk/v2.1.0/commands/index", + "sdk-reference/js-sdk/v2.1.0/errors/index", + "sdk-reference/js-sdk/v2.1.0/filesystem/index", + "sdk-reference/js-sdk/v2.1.0/sandbox/index" + ] + } + ] + }, + { + "version": "v2.0.3", + "groups": [ + { + "group": "JavaScript SDK v2.0.3", + "pages": [ + "sdk-reference/js-sdk/v2.0.3/commands/index", + "sdk-reference/js-sdk/v2.0.3/errors/index", + "sdk-reference/js-sdk/v2.0.3/filesystem/index", + "sdk-reference/js-sdk/v2.0.3/sandbox/index" + ] + } + ] + }, + { + "version": "v2.0.2", + "groups": [ + { + "group": "JavaScript SDK v2.0.2", + "pages": [ + "sdk-reference/js-sdk/v2.0.2/commands/index", + "sdk-reference/js-sdk/v2.0.2/errors/index", + "sdk-reference/js-sdk/v2.0.2/filesystem/index", + "sdk-reference/js-sdk/v2.0.2/sandbox/index" + ] + } + ] + }, + { + "version": "v2.0.1", + "groups": [ + { + "group": "JavaScript SDK v2.0.1", + "pages": [ + "sdk-reference/js-sdk/v2.0.1/commands/index", + "sdk-reference/js-sdk/v2.0.1/errors/index", + "sdk-reference/js-sdk/v2.0.1/filesystem/index", + "sdk-reference/js-sdk/v2.0.1/sandbox/index" + ] + } + ] + }, + { + "version": "v2.0.0", + "groups": [ + { + "group": "JavaScript SDK v2.0.0", + "pages": [ + "sdk-reference/js-sdk/v2.0.0/commands/index", + "sdk-reference/js-sdk/v2.0.0/errors/index", + "sdk-reference/js-sdk/v2.0.0/filesystem/index", + "sdk-reference/js-sdk/v2.0.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.13.2", + "groups": [ + { + "group": "JavaScript SDK v1.13.2", + "pages": [ + "sdk-reference/js-sdk/v1.13.2/commands/index", + "sdk-reference/js-sdk/v1.13.2/errors/index", + "sdk-reference/js-sdk/v1.13.2/filesystem/index", + "sdk-reference/js-sdk/v1.13.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.13.1", + "groups": [ + { + "group": "JavaScript SDK v1.13.1", + "pages": [ + "sdk-reference/js-sdk/v1.13.1/commands/index", + "sdk-reference/js-sdk/v1.13.1/errors/index", + "sdk-reference/js-sdk/v1.13.1/filesystem/index", + "sdk-reference/js-sdk/v1.13.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.13.0", + "groups": [ + { + "group": "JavaScript SDK v1.13.0", + "pages": [ + "sdk-reference/js-sdk/v1.13.0/commands/index", + "sdk-reference/js-sdk/v1.13.0/errors/index", + "sdk-reference/js-sdk/v1.13.0/filesystem/index", + "sdk-reference/js-sdk/v1.13.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.12.0", + "groups": [ + { + "group": "JavaScript SDK v1.12.0", + "pages": [ + "sdk-reference/js-sdk/v1.12.0/commands/index", + "sdk-reference/js-sdk/v1.12.0/errors/index", + "sdk-reference/js-sdk/v1.12.0/filesystem/index", + "sdk-reference/js-sdk/v1.12.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.11.0", + "groups": [ + { + "group": "JavaScript SDK v1.11.0", + "pages": [ + "sdk-reference/js-sdk/v1.11.0/commands/index", + "sdk-reference/js-sdk/v1.11.0/errors/index", + "sdk-reference/js-sdk/v1.11.0/filesystem/index", + "sdk-reference/js-sdk/v1.11.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.10.0", + "groups": [ + { + "group": "JavaScript SDK v1.10.0", + "pages": [ + "sdk-reference/js-sdk/v1.10.0/commands/index", + "sdk-reference/js-sdk/v1.10.0/errors/index", + "sdk-reference/js-sdk/v1.10.0/filesystem/index", + "sdk-reference/js-sdk/v1.10.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.9.1", + "groups": [ + { + "group": "JavaScript SDK v1.9.1", + "pages": [ + "sdk-reference/js-sdk/v1.9.1/commands/index", + "sdk-reference/js-sdk/v1.9.1/errors/index", + "sdk-reference/js-sdk/v1.9.1/filesystem/index", + "sdk-reference/js-sdk/v1.9.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.9.0", + "groups": [ + { + "group": "JavaScript SDK v1.9.0", + "pages": [ + "sdk-reference/js-sdk/v1.9.0/commands/index", + "sdk-reference/js-sdk/v1.9.0/errors/index", + "sdk-reference/js-sdk/v1.9.0/filesystem/index", + "sdk-reference/js-sdk/v1.9.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.8.0", + "groups": [ + { + "group": "JavaScript SDK v1.8.0", + "pages": [ + "sdk-reference/js-sdk/v1.8.0/commands/index", + "sdk-reference/js-sdk/v1.8.0/errors/index", + "sdk-reference/js-sdk/v1.8.0/filesystem/index", + "sdk-reference/js-sdk/v1.8.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.1", + "groups": [ + { + "group": "JavaScript SDK v1.7.1", + "pages": [ + "sdk-reference/js-sdk/v1.7.1/commands/index", + "sdk-reference/js-sdk/v1.7.1/errors/index", + "sdk-reference/js-sdk/v1.7.1/filesystem/index", + "sdk-reference/js-sdk/v1.7.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.0", + "groups": [ + { + "group": "JavaScript SDK v1.7.0", + "pages": [ + "sdk-reference/js-sdk/v1.7.0/commands/index", + "sdk-reference/js-sdk/v1.7.0/errors/index", + "sdk-reference/js-sdk/v1.7.0/filesystem/index", + "sdk-reference/js-sdk/v1.7.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.0", + "groups": [ + { + "group": "JavaScript SDK v1.6.0", + "pages": [ + "sdk-reference/js-sdk/v1.6.0/commands/index", + "sdk-reference/js-sdk/v1.6.0/errors/index", + "sdk-reference/js-sdk/v1.6.0/filesystem/index", + "sdk-reference/js-sdk/v1.6.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.3", + "groups": [ + { + "group": "JavaScript SDK v1.5.3", + "pages": [ + "sdk-reference/js-sdk/v1.5.3/commands/index", + "sdk-reference/js-sdk/v1.5.3/errors/index", + "sdk-reference/js-sdk/v1.5.3/filesystem/index", + "sdk-reference/js-sdk/v1.5.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.2", + "groups": [ + { + "group": "JavaScript SDK v1.5.2", + "pages": [ + "sdk-reference/js-sdk/v1.5.2/commands/index", + "sdk-reference/js-sdk/v1.5.2/errors/index", + "sdk-reference/js-sdk/v1.5.2/filesystem/index", + "sdk-reference/js-sdk/v1.5.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.1", + "groups": [ + { + "group": "JavaScript SDK v1.5.1", + "pages": [ + "sdk-reference/js-sdk/v1.5.1/commands/index", + "sdk-reference/js-sdk/v1.5.1/errors/index", + "sdk-reference/js-sdk/v1.5.1/filesystem/index", + "sdk-reference/js-sdk/v1.5.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.0", + "groups": [ + { + "group": "JavaScript SDK v1.5.0", + "pages": [ + "sdk-reference/js-sdk/v1.5.0/commands/index", + "sdk-reference/js-sdk/v1.5.0/errors/index", + "sdk-reference/js-sdk/v1.5.0/filesystem/index", + "sdk-reference/js-sdk/v1.5.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.4.0", + "groups": [ + { + "group": "JavaScript SDK v1.4.0", + "pages": [ + "sdk-reference/js-sdk/v1.4.0/commands/index", + "sdk-reference/js-sdk/v1.4.0/errors/index", + "sdk-reference/js-sdk/v1.4.0/filesystem/index", + "sdk-reference/js-sdk/v1.4.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.3.0", + "groups": [ + { + "group": "JavaScript SDK v1.3.0", + "pages": [ + "sdk-reference/js-sdk/v1.3.0/commands/index", + "sdk-reference/js-sdk/v1.3.0/errors/index", + "sdk-reference/js-sdk/v1.3.0/filesystem/index", + "sdk-reference/js-sdk/v1.3.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.5", + "groups": [ + { + "group": "JavaScript SDK v1.2.5", + "pages": [ + "sdk-reference/js-sdk/v1.2.5/commands/index", + "sdk-reference/js-sdk/v1.2.5/errors/index", + "sdk-reference/js-sdk/v1.2.5/filesystem/index", + "sdk-reference/js-sdk/v1.2.5/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.4", + "groups": [ + { + "group": "JavaScript SDK v1.2.4", + "pages": [ + "sdk-reference/js-sdk/v1.2.4/commands/index", + "sdk-reference/js-sdk/v1.2.4/errors/index", + "sdk-reference/js-sdk/v1.2.4/filesystem/index", + "sdk-reference/js-sdk/v1.2.4/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.3", + "groups": [ + { + "group": "JavaScript SDK v1.2.3", + "pages": [ + "sdk-reference/js-sdk/v1.2.3/commands/index", + "sdk-reference/js-sdk/v1.2.3/errors/index", + "sdk-reference/js-sdk/v1.2.3/filesystem/index", + "sdk-reference/js-sdk/v1.2.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.2", + "groups": [ + { + "group": "JavaScript SDK v1.2.2", + "pages": [ + "sdk-reference/js-sdk/v1.2.2/commands/index", + "sdk-reference/js-sdk/v1.2.2/errors/index", + "sdk-reference/js-sdk/v1.2.2/filesystem/index", + "sdk-reference/js-sdk/v1.2.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.1", + "groups": [ + { + "group": "JavaScript SDK v1.2.1", + "pages": [ + "sdk-reference/js-sdk/v1.2.1/commands/index", + "sdk-reference/js-sdk/v1.2.1/errors/index", + "sdk-reference/js-sdk/v1.2.1/filesystem/index", + "sdk-reference/js-sdk/v1.2.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.0", + "groups": [ + { + "group": "JavaScript SDK v1.2.0", + "pages": [ + "sdk-reference/js-sdk/v1.2.0/commands/index", + "sdk-reference/js-sdk/v1.2.0/errors/index", + "sdk-reference/js-sdk/v1.2.0/filesystem/index", + "sdk-reference/js-sdk/v1.2.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.1", + "groups": [ + { + "group": "JavaScript SDK v1.1.1", + "pages": [ + "sdk-reference/js-sdk/v1.1.1/commands/index", + "sdk-reference/js-sdk/v1.1.1/errors/index", + "sdk-reference/js-sdk/v1.1.1/filesystem/index", + "sdk-reference/js-sdk/v1.1.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.0", + "groups": [ + { + "group": "JavaScript SDK v1.1.0", + "pages": [ + "sdk-reference/js-sdk/v1.1.0/commands/index", + "sdk-reference/js-sdk/v1.1.0/errors/index", + "sdk-reference/js-sdk/v1.1.0/filesystem/index", + "sdk-reference/js-sdk/v1.1.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.7", + "groups": [ + { + "group": "JavaScript SDK v1.0.7", + "pages": [ + "sdk-reference/js-sdk/v1.0.7/commands/index", + "sdk-reference/js-sdk/v1.0.7/errors/index", + "sdk-reference/js-sdk/v1.0.7/filesystem/index", + "sdk-reference/js-sdk/v1.0.7/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.6", + "groups": [ + { + "group": "JavaScript SDK v1.0.6", + "pages": [ + "sdk-reference/js-sdk/v1.0.6/commands/index", + "sdk-reference/js-sdk/v1.0.6/errors/index", + "sdk-reference/js-sdk/v1.0.6/filesystem/index", + "sdk-reference/js-sdk/v1.0.6/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.5", + "groups": [ + { + "group": "JavaScript SDK v1.0.5", + "pages": [ + "sdk-reference/js-sdk/v1.0.5/commands/index", + "sdk-reference/js-sdk/v1.0.5/errors/index", + "sdk-reference/js-sdk/v1.0.5/filesystem/index", + "sdk-reference/js-sdk/v1.0.5/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.4", + "groups": [ + { + "group": "JavaScript SDK v1.0.4", + "pages": [ + "sdk-reference/js-sdk/v1.0.4/errors/index", + "sdk-reference/js-sdk/v1.0.4/filesystem/index", + "sdk-reference/js-sdk/v1.0.4/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.3", + "groups": [ + { + "group": "JavaScript SDK v1.0.3", + "pages": [ + "sdk-reference/js-sdk/v1.0.3/errors/index", + "sdk-reference/js-sdk/v1.0.3/filesystem/index", + "sdk-reference/js-sdk/v1.0.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.2", + "groups": [ + { + "group": "JavaScript SDK v1.0.2", + "pages": [ + "sdk-reference/js-sdk/v1.0.2/errors/index", + "sdk-reference/js-sdk/v1.0.2/filesystem/index", + "sdk-reference/js-sdk/v1.0.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.1", + "groups": [ + { + "group": "JavaScript SDK v1.0.1", + "pages": [ + "sdk-reference/js-sdk/v1.0.1/errors/index", + "sdk-reference/js-sdk/v1.0.1/filesystem/index", + "sdk-reference/js-sdk/v1.0.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.0", + "groups": [ + { + "group": "JavaScript SDK v1.0.0", + "pages": [ + "sdk-reference/js-sdk/v1.0.0/errors/index", + "sdk-reference/js-sdk/v1.0.0/filesystem/index", + "sdk-reference/js-sdk/v1.0.0/sandbox/index" + ] + } + ] + } + ] + }, + { + "dropdown": "Python SDK", + "icon": "python", + "versions": [ + { + "version": "v2.1.3@latest", + "groups": [ + { + "group": "Python SDK v2.1.3", + "pages": [ + "sdk-reference/python-sdk/v2.1.3/exceptions/index", + "sdk-reference/python-sdk/v2.1.3/sandbox_async/index", + "sdk-reference/python-sdk/v2.1.3/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v2.1.2", + "groups": [ + { + "group": "Python SDK v2.1.2", + "pages": [ + "sdk-reference/python-sdk/v2.1.2/exceptions/index", + "sdk-reference/python-sdk/v2.1.2/sandbox_async/index", + "sdk-reference/python-sdk/v2.1.2/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v2.1.1", + "groups": [ + { + "group": "Python SDK v2.1.1", + "pages": [ + "sdk-reference/python-sdk/v2.1.1/exceptions/index", + "sdk-reference/python-sdk/v2.1.1/sandbox_async/index", + "sdk-reference/python-sdk/v2.1.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v2.1.0", + "groups": [ + { + "group": "Python SDK v2.1.0", + "pages": [ + "sdk-reference/python-sdk/v2.1.0/exceptions/index", + "sdk-reference/python-sdk/v2.1.0/sandbox_async/index", + "sdk-reference/python-sdk/v2.1.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v2.0.2", + "groups": [ + { + "group": "Python SDK v2.0.2", + "pages": [ + "sdk-reference/python-sdk/v2.0.2/exceptions/index", + "sdk-reference/python-sdk/v2.0.2/sandbox_async/index", + "sdk-reference/python-sdk/v2.0.2/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v2.0.1", + "groups": [ + { + "group": "Python SDK v2.0.1", + "pages": [ + "sdk-reference/python-sdk/v2.0.1/exceptions/index", + "sdk-reference/python-sdk/v2.0.1/sandbox_async/index", + "sdk-reference/python-sdk/v2.0.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v2.0.0", + "groups": [ + { + "group": "Python SDK v2.0.0", + "pages": [ + "sdk-reference/python-sdk/v2.0.0/exceptions/index", + "sdk-reference/python-sdk/v2.0.0/sandbox_async/index", + "sdk-reference/python-sdk/v2.0.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.11.1", + "groups": [ + { + "group": "Python SDK v1.11.1", + "pages": [ + "sdk-reference/python-sdk/v1.11.1/exceptions/index", + "sdk-reference/python-sdk/v1.11.1/sandbox_async/index", + "sdk-reference/python-sdk/v1.11.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.11.0", + "groups": [ + { + "group": "Python SDK v1.11.0", + "pages": [ + "sdk-reference/python-sdk/v1.11.0/exceptions/index", + "sdk-reference/python-sdk/v1.11.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.11.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.10.0", + "groups": [ + { + "group": "Python SDK v1.10.0", + "pages": [ + "sdk-reference/python-sdk/v1.10.0/exceptions/index", + "sdk-reference/python-sdk/v1.10.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.10.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.9.0", + "groups": [ + { + "group": "Python SDK v1.9.0", + "pages": [ + "sdk-reference/python-sdk/v1.9.0/exceptions/index", + "sdk-reference/python-sdk/v1.9.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.9.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.8.0", + "groups": [ + { + "group": "Python SDK v1.8.0", + "pages": [ + "sdk-reference/python-sdk/v1.8.0/exceptions/index", + "sdk-reference/python-sdk/v1.8.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.8.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.7.1", + "groups": [ + { + "group": "Python SDK v1.7.1", + "pages": [ + "sdk-reference/python-sdk/v1.7.1/exceptions/index", + "sdk-reference/python-sdk/v1.7.1/sandbox_async/index", + "sdk-reference/python-sdk/v1.7.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.7.0", + "groups": [ + { + "group": "Python SDK v1.7.0", + "pages": [ + "sdk-reference/python-sdk/v1.7.0/exceptions/index", + "sdk-reference/python-sdk/v1.7.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.7.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.6.0", + "groups": [ + { + "group": "Python SDK v1.6.0", + "pages": [ + "sdk-reference/python-sdk/v1.6.0/exceptions/index", + "sdk-reference/python-sdk/v1.6.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.6.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.5.6", + "groups": [ + { + "group": "Python SDK v1.5.6", + "pages": [ + "sdk-reference/python-sdk/v1.5.6/exceptions/index", + "sdk-reference/python-sdk/v1.5.6/sandbox_async/index", + "sdk-reference/python-sdk/v1.5.6/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.5.5", + "groups": [ + { + "group": "Python SDK v1.5.5", + "pages": [ + "sdk-reference/python-sdk/v1.5.5/exceptions/index", + "sdk-reference/python-sdk/v1.5.5/sandbox_async/index", + "sdk-reference/python-sdk/v1.5.5/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.5.4", + "groups": [ + { + "group": "Python SDK v1.5.4", + "pages": [ + "sdk-reference/python-sdk/v1.5.4/exceptions/index", + "sdk-reference/python-sdk/v1.5.4/sandbox_async/index", + "sdk-reference/python-sdk/v1.5.4/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.5.3", + "groups": [ + { + "group": "Python SDK v1.5.3", + "pages": [ + "sdk-reference/python-sdk/v1.5.3/exceptions/index", + "sdk-reference/python-sdk/v1.5.3/sandbox_async/index", + "sdk-reference/python-sdk/v1.5.3/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.5.2", + "groups": [ + { + "group": "Python SDK v1.5.2", + "pages": [ + "sdk-reference/python-sdk/v1.5.2/exceptions/index", + "sdk-reference/python-sdk/v1.5.2/sandbox_async/index", + "sdk-reference/python-sdk/v1.5.2/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.5.1", + "groups": [ + { + "group": "Python SDK v1.5.1", + "pages": [ + "sdk-reference/python-sdk/v1.5.1/exceptions/index", + "sdk-reference/python-sdk/v1.5.1/sandbox_async/index", + "sdk-reference/python-sdk/v1.5.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.5.0", + "groups": [ + { + "group": "Python SDK v1.5.0", + "pages": [ + "sdk-reference/python-sdk/v1.5.0/exceptions/index", + "sdk-reference/python-sdk/v1.5.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.5.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.4.0", + "groups": [ + { + "group": "Python SDK v1.4.0", + "pages": [ + "sdk-reference/python-sdk/v1.4.0/exceptions/index", + "sdk-reference/python-sdk/v1.4.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.4.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.3.5", + "groups": [ + { + "group": "Python SDK v1.3.5", + "pages": [ + "sdk-reference/python-sdk/v1.3.5/exceptions/index", + "sdk-reference/python-sdk/v1.3.5/sandbox_async/index", + "sdk-reference/python-sdk/v1.3.5/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.3.4", + "groups": [ + { + "group": "Python SDK v1.3.4", + "pages": [ + "sdk-reference/python-sdk/v1.3.4/exceptions/index", + "sdk-reference/python-sdk/v1.3.4/sandbox_async/index", + "sdk-reference/python-sdk/v1.3.4/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.3.3", + "groups": [ + { + "group": "Python SDK v1.3.3", + "pages": [ + "sdk-reference/python-sdk/v1.3.3/exceptions/index", + "sdk-reference/python-sdk/v1.3.3/sandbox_async/index", + "sdk-reference/python-sdk/v1.3.3/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.3.2", + "groups": [ + { + "group": "Python SDK v1.3.2", + "pages": [ + "sdk-reference/python-sdk/v1.3.2/exceptions/index", + "sdk-reference/python-sdk/v1.3.2/sandbox_async/index", + "sdk-reference/python-sdk/v1.3.2/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.3.1", + "groups": [ + { + "group": "Python SDK v1.3.1", + "pages": [ + "sdk-reference/python-sdk/v1.3.1/exceptions/index", + "sdk-reference/python-sdk/v1.3.1/sandbox_async/index", + "sdk-reference/python-sdk/v1.3.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.3.0", + "groups": [ + { + "group": "Python SDK v1.3.0", + "pages": [ + "sdk-reference/python-sdk/v1.3.0/exceptions/index", + "sdk-reference/python-sdk/v1.3.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.3.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.2.1", + "groups": [ + { + "group": "Python SDK v1.2.1", + "pages": [ + "sdk-reference/python-sdk/v1.2.1/exceptions/index", + "sdk-reference/python-sdk/v1.2.1/sandbox_async/index", + "sdk-reference/python-sdk/v1.2.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.2.0", + "groups": [ + { + "group": "Python SDK v1.2.0", + "pages": [ + "sdk-reference/python-sdk/v1.2.0/exceptions/index", + "sdk-reference/python-sdk/v1.2.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.2.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.1.0", + "groups": [ + { + "group": "Python SDK v1.1.0", + "pages": [ + "sdk-reference/python-sdk/v1.1.0/exceptions/index", + "sdk-reference/python-sdk/v1.1.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.1.0/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.0.6", + "groups": [ + { + "group": "Python SDK v1.0.6", + "pages": [ + "sdk-reference/python-sdk/v1.0.6/exceptions/index", + "sdk-reference/python-sdk/v1.0.6/sandbox_async/index", + "sdk-reference/python-sdk/v1.0.6/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.0.5", + "groups": [ + { + "group": "Python SDK v1.0.5", + "pages": [ + "sdk-reference/python-sdk/v1.0.5/exceptions/index", + "sdk-reference/python-sdk/v1.0.5/sandbox_async/index", + "sdk-reference/python-sdk/v1.0.5/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.0.4", + "groups": [ + { + "group": "Python SDK v1.0.4", + "pages": [ + "sdk-reference/python-sdk/v1.0.4/exceptions/index", + "sdk-reference/python-sdk/v1.0.4/sandbox_async/index", + "sdk-reference/python-sdk/v1.0.4/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.0.3", + "groups": [ + { + "group": "Python SDK v1.0.3", + "pages": [ + "sdk-reference/python-sdk/v1.0.3/exceptions/index", + "sdk-reference/python-sdk/v1.0.3/sandbox_async/index", + "sdk-reference/python-sdk/v1.0.3/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.0.2", + "groups": [ + { + "group": "Python SDK v1.0.2", + "pages": [ + "sdk-reference/python-sdk/v1.0.2/exceptions/index", + "sdk-reference/python-sdk/v1.0.2/sandbox_async/index", + "sdk-reference/python-sdk/v1.0.2/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.0.1", + "groups": [ + { + "group": "Python SDK v1.0.1", + "pages": [ + "sdk-reference/python-sdk/v1.0.1/exceptions/index", + "sdk-reference/python-sdk/v1.0.1/sandbox_async/index", + "sdk-reference/python-sdk/v1.0.1/sandbox_sync/index" + ] + } + ] + }, + { + "version": "v1.0.0", + "groups": [ + { + "group": "Python SDK v1.0.0", + "pages": [ + "sdk-reference/python-sdk/v1.0.0/exceptions/index", + "sdk-reference/python-sdk/v1.0.0/sandbox_async/index", + "sdk-reference/python-sdk/v1.0.0/sandbox_sync/index" + ] + } + ] + } + ] + }, + { + "dropdown": "Code Interpreter JavaScript SDK", + "icon": "square-js", + "versions": [ + { + "version": "v2.0.0@latest", + "groups": [ + { + "group": "Code Interpreter JavaScript SDK v2.0.0", + "pages": [ + "sdk-reference/code-interpreter-js-sdk/v2.0.0/charts/index", + "sdk-reference/code-interpreter-js-sdk/v2.0.0/consts/index", + "sdk-reference/code-interpreter-js-sdk/v2.0.0/index/index", + "sdk-reference/code-interpreter-js-sdk/v2.0.0/messaging/index", + "sdk-reference/code-interpreter-js-sdk/v2.0.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.1", + "groups": [ + { + "group": "Code Interpreter JavaScript SDK v1.5.1", + "pages": [ + "sdk-reference/code-interpreter-js-sdk/v1.5.1/charts/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.1/consts/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.1/index/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.1/messaging/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.0", + "groups": [ + { + "group": "Code Interpreter JavaScript SDK v1.5.0", + "pages": [ + "sdk-reference/code-interpreter-js-sdk/v1.5.0/charts/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.0/consts/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.0/index/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.0/messaging/index", + "sdk-reference/code-interpreter-js-sdk/v1.5.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.0", + "groups": [ + { + "group": "Code Interpreter JavaScript SDK v1.2.0", + "pages": [ + "sdk-reference/code-interpreter-js-sdk/v1.2.0/charts/index", + "sdk-reference/code-interpreter-js-sdk/v1.2.0/consts/index", + "sdk-reference/code-interpreter-js-sdk/v1.2.0/index/index", + "sdk-reference/code-interpreter-js-sdk/v1.2.0/messaging/index", + "sdk-reference/code-interpreter-js-sdk/v1.2.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.1", + "groups": [ + { + "group": "Code Interpreter JavaScript SDK v1.1.1", + "pages": [ + "sdk-reference/code-interpreter-js-sdk/v1.1.1/charts/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.1/consts/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.1/index/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.1/messaging/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.0", + "groups": [ + { + "group": "Code Interpreter JavaScript SDK v1.1.0", + "pages": [ + "sdk-reference/code-interpreter-js-sdk/v1.1.0/charts/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.0/consts/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.0/index/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.0/messaging/index", + "sdk-reference/code-interpreter-js-sdk/v1.1.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.4", + "groups": [ + { + "group": "Code Interpreter JavaScript SDK v1.0.4", + "pages": [ + "sdk-reference/code-interpreter-js-sdk/v1.0.4/charts/index", + "sdk-reference/code-interpreter-js-sdk/v1.0.4/consts/index", + "sdk-reference/code-interpreter-js-sdk/v1.0.4/index/index", + "sdk-reference/code-interpreter-js-sdk/v1.0.4/messaging/index", + "sdk-reference/code-interpreter-js-sdk/v1.0.4/sandbox/index" + ] + } + ] + } + ] + }, + { + "dropdown": "Code Interpreter Python SDK", + "icon": "python", + "versions": [ + { + "version": "v2.0.0@latest", + "groups": [ + { + "group": "Code Interpreter Python SDK v2.0.0", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v2.0.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.2", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.5.2", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.5.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.1", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.5.1", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.5.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.0", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.5.0", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.5.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.1", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.2.1", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.2.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.0", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.2.0", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.2.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.1", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.1.1", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.1.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.0", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.1.0", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.1.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.5", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.0.5", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.0.5/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.4", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.0.4", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.0.4/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.3", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.0.3", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.0.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.2", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.0.2", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.0.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.1", + "groups": [ + { + "group": "Code Interpreter Python SDK v1.0.1", + "pages": [ + "sdk-reference/code-interpreter-python-sdk/v1.0.1/sandbox/index" + ] + } + ] + } + ] + }, + { + "dropdown": "Desktop JavaScript SDK", + "icon": "square-js", + "versions": [ + { + "version": "v2.0.1@latest", + "groups": [ + { + "group": "Desktop JavaScript SDK v2.0.1", + "pages": [ + "sdk-reference/desktop-js-sdk/v2.0.1/sandbox/index" + ] + } + ] + }, + { + "version": "v2.0.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v2.0.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v2.0.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.9.2", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.9.2", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.9.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.9.1", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.9.1", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.9.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.9.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.9.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.9.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.8.1", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.8.1", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.8.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.8.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.8.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.8.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.3", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.7.3", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.7.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.2", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.7.2", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.7.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.1", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.7.1", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.7.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.7.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.7.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.2", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.6.2", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.6.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.1", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.6.1", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.6.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.6.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.6.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.5.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.5.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.4.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.4.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.4.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.3.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.3.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.3.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.0", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.2.0", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.2.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.1", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.1.1", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.1.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.3", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.0.3", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.0.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.2", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.0.2", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.0.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.1", + "groups": [ + { + "group": "Desktop JavaScript SDK v1.0.1", + "pages": [ + "sdk-reference/desktop-js-sdk/v1.0.1/sandbox/index" + ] + } + ] + } + ] + }, + { + "dropdown": "Desktop Python SDK", + "icon": "python", + "versions": [ + { + "version": "v2.0.1@latest", + "groups": [ + { + "group": "Desktop Python SDK v2.0.1", + "pages": [ + "sdk-reference/desktop-python-sdk/v2.0.1/sandbox/index" + ] + } + ] + }, + { + "version": "v2.0.0", + "groups": [ + { + "group": "Desktop Python SDK v2.0.0", + "pages": [ + "sdk-reference/desktop-python-sdk/v2.0.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.4", + "groups": [ + { + "group": "Desktop Python SDK v1.7.4", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.7.4/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.3", + "groups": [ + { + "group": "Desktop Python SDK v1.7.3", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.7.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.2", + "groups": [ + { + "group": "Desktop Python SDK v1.7.2", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.7.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.1", + "groups": [ + { + "group": "Desktop Python SDK v1.7.1", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.7.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.7.0", + "groups": [ + { + "group": "Desktop Python SDK v1.7.0", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.7.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.5", + "groups": [ + { + "group": "Desktop Python SDK v1.6.5", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.6.5/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.4", + "groups": [ + { + "group": "Desktop Python SDK v1.6.4", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.6.4/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.3", + "groups": [ + { + "group": "Desktop Python SDK v1.6.3", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.6.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.2", + "groups": [ + { + "group": "Desktop Python SDK v1.6.2", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.6.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.1", + "groups": [ + { + "group": "Desktop Python SDK v1.6.1", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.6.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.6.0", + "groups": [ + { + "group": "Desktop Python SDK v1.6.0", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.6.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.2", + "groups": [ + { + "group": "Desktop Python SDK v1.5.2", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.5.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.1", + "groups": [ + { + "group": "Desktop Python SDK v1.5.1", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.5.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.5.0", + "groups": [ + { + "group": "Desktop Python SDK v1.5.0", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.5.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.4.0", + "groups": [ + { + "group": "Desktop Python SDK v1.4.0", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.4.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.3.0", + "groups": [ + { + "group": "Desktop Python SDK v1.3.0", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.3.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.2.0", + "groups": [ + { + "group": "Desktop Python SDK v1.2.0", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.2.0/sandbox/index" + ] + } + ] + }, + { + "version": "v1.1.1", + "groups": [ + { + "group": "Desktop Python SDK v1.1.1", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.1.1/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.3", + "groups": [ + { + "group": "Desktop Python SDK v1.0.3", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.0.3/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.2", + "groups": [ + { + "group": "Desktop Python SDK v1.0.2", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.0.2/sandbox/index" + ] + } + ] + }, + { + "version": "v1.0.1", + "groups": [ + { + "group": "Desktop Python SDK v1.0.1", + "pages": [ + "sdk-reference/desktop-python-sdk/v1.0.1/sandbox/index" + ] + } + ] + } + ] + } +] \ No newline at end of file diff --git a/apps/web/src/app/(docs)/mintlify-docs/snippets/CodeInterpreting.jsx b/apps/web/src/app/(docs)/mintlify-docs/snippets/CodeInterpreting.jsx new file mode 100644 index 0000000000..2ab1571d73 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/snippets/CodeInterpreting.jsx @@ -0,0 +1,37 @@ +export const CodeInterpreting = () => { + const items = [ + { + href: "/code-interpreting/analyze-data-with-ai", + title: "Analyze data with AI", + description: "Learn how to use E2B run AI-generated code to analyze yourdata.", + icon: "file-circle-question", + }, + { + href: "/code-interpreting/create-charts-visualizations", + title: "Create charts & visualizations", + description: "Create interactive charts by running Python code in E2B.", + icon: "chart-waterfall", + }, + // { + // href: '/code-interpreting/connect-your-data', + // title: 'Connect your data', + // description: 'TODO: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ut purus eget sapien. Sed ut purus eget sapien.', + // icon: , + // }, + // { + // href: '/code-interpreting/todo', + // title: 'Parsing code execution results', + // description: 'TODO: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ut purus eget sapien. Sed ut purus eget sapien.', + // icon: , + // }, + ]; + return ( + + {items.map((i) => ( + + {i.description} + + ))} + + ); +}; diff --git a/apps/web/src/app/(docs)/mintlify-docs/snippets/Concepts.jsx b/apps/web/src/app/(docs)/mintlify-docs/snippets/Concepts.jsx new file mode 100644 index 0000000000..daf838363a --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/snippets/Concepts.jsx @@ -0,0 +1,43 @@ +export const Concepts = () => { + const concepts = [ + { + href: "/sandbox", + title: "Sandbox lifecycle", + description: "Learn about how to start the sandbox, manage its lifecycle, and interact with it.", + icon: "hourglass", + }, + { + href: "/sandbox/persistence", + title: "Sandbox persistence", + description: "Learn how to achieve data persistence by pausing and resuming sandboxes.", + icon: "rotate-reverse", + }, + // { + // href: '/code-execution', + // title: 'AI code execution', + // description: 'E2B Sandboxex offer built-in support for running AI-generated Python, JS, TS, and R. You can customize sandbox to run almost any language.', + // icon: , + // }, + { + href: "/filesystem", + title: "Filesystem", + description: "Sandbox has an isolated filesystem that you can use to create, read, write, and delete files.", + icon: "folder-tree", + }, + { + href: "/commands", + title: "Commands", + description: "Run terminal commands inside the Sandbox and start any process inside the Sandbox.", + icon: "terminal", + }, + ]; + return ( + + {concepts.map((i) => ( + + {i.description} + + ))} + + ); +}; diff --git a/apps/web/src/app/(docs)/mintlify-docs/snippets/Quickstart.jsx b/apps/web/src/app/(docs)/mintlify-docs/snippets/Quickstart.jsx new file mode 100644 index 0000000000..dd1a7208de --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/snippets/Quickstart.jsx @@ -0,0 +1,37 @@ +export const Quickstart = () => { + const items = [ + { + href: "/quickstart", + title: "Running your first Sandbox", + description: "Learn how to start your first E2B Sandbox with our Python or JavaScript SDK.", + icon: "circle-play", + }, + { + href: "/quickstart/connect-llms", + title: "Connecting LLMs to E2B", + description: "Connect your favorite LLM to E2B to run AI-generated code inside the Sandbox.", + icon: "brain-circuit", + }, + { + href: "/quickstart/upload-download-files", + title: "Uploading & downloading files", + description: "A quick guide on how to upload and download files to and from the Sandbox.", + icon: "cloud-arrow-up", + }, + { + href: "/quickstart/install-custom-packages", + title: "Install custom packages", + description: "Customize your Sandbox with third-party packages.", + icon: "box-open-full", + }, + ]; + return ( + + {items.map((i) => ( + + {i.description} + + ))} + + ); +}; diff --git a/apps/web/src/app/(docs)/mintlify-docs/snippets/SandboxSpec.mdx b/apps/web/src/app/(docs)/mintlify-docs/snippets/SandboxSpec.mdx new file mode 100644 index 0000000000..1cd59fbec2 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/snippets/SandboxSpec.mdx @@ -0,0 +1,125 @@ +### CPU + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
vCPUsPlanCosts
1Pro$0.000014/s
+ 2 [default] + Hobby / Pro$0.000028/s
3Pro$0.000042/s
4Pro$0.000056/s
5Pro$0.000070/s
6Pro$0.000084/s
7Pro$0.000098/s
8Pro$0.000112/s
+
+ +### RAM + +
+ + + + + + + + + + + + + + + + + + + + + + +
RAMPlanCosts
+ 512 MiB [default] + Hobby / Pro$0.0000045/GiB/s
+ even value between 128 MiB and 8,192 MiB + Pro$0.0000045/GiB/s
+
+ +### Storage + +
+ + + + + + + + + + + + + + + + + + + + + + +
StoragePlanCosts
1 GiBHobbyFree
5 GiBProFree
+
diff --git a/apps/web/src/app/(docs)/mintlify-docs/style.css b/apps/web/src/app/(docs)/mintlify-docs/style.css new file mode 100644 index 0000000000..13432b0235 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/style.css @@ -0,0 +1,34 @@ +@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600;1,700&display=swap'); + +#topbar-links { + background-color: var(--background-white); +} + +/* Add styles specifically for the Sign In link */ +a[href*='auth/sign-in'].whitespace-nowrap.font-medium { + background-color: black; + color: white !important; + padding: 0.5rem 1rem; + border-radius: 4px; + transition: background-color 0.2s ease; +} + +a[href*='auth/sign-in'].whitespace-nowrap.font-medium:hover { + background-color: #333; + color: white !important; +} + +/* Dark mode styles */ +.dark a[href*='auth/sign-in'].whitespace-nowrap.font-medium { + background-color: white; + color: black !important; +} + +.dark a[href*='auth/sign-in'].whitespace-nowrap.font-medium:hover { + background-color: #f3f3f3; + color: black !important; +} + +code { + font-family: 'IBM Plex Mono'; +} diff --git a/apps/web/src/app/(docs)/mintlify-docs/support/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/support/index.mdx new file mode 100644 index 0000000000..3a10aa1d77 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/support/index.mdx @@ -0,0 +1,24 @@ +--- +title: "Need help?" +icon: "messages" +--- + +Join our Discord community, open GitHub issues, or send us an email if you have any questions or request. + + + + + + diff --git a/apps/web/src/app/(docs)/mintlify-docs/troubleshooting/sdks/workers-edge-runtime/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/troubleshooting/sdks/workers-edge-runtime/index.mdx new file mode 100644 index 0000000000..57a4516b63 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/troubleshooting/sdks/workers-edge-runtime/index.mdx @@ -0,0 +1,5 @@ +--- +title: "Vercel Edge Runtime and Cloudflare Workers" +--- + +The E2B JavaScript SDK currently lacks support for Vercel Edge Runtime and Cloudflare Workers due to transport layer package incompatibility used for Sandbox communication. We recommend using supported runtimes like Node, Bun, or Deno instead. diff --git a/apps/web/src/app/(docs)/mintlify-docs/troubleshooting/templates/build-authentication-error/index.mdx b/apps/web/src/app/(docs)/mintlify-docs/troubleshooting/templates/build-authentication-error/index.mdx new file mode 100644 index 0000000000..2457276a55 --- /dev/null +++ b/apps/web/src/app/(docs)/mintlify-docs/troubleshooting/templates/build-authentication-error/index.mdx @@ -0,0 +1,73 @@ +--- +title: "Docker push authentication error" +sidebarTitle: Build authentication error +--- + +When the CLI tries to push a Docker image to the registry, you might encounter an authentication error. This error sometimes occurs for users when Docker doesn't send any credentials to the registry. +To resolve this issue, you can use the following steps: + +## MacOS + +1. Open Docker Desktop. +2. Go to Settings. +3. Go to Docker Engine. +4. Add the following line to the json configuration: + +```json +{ + "insecure-registries": ["host.docker.internal:49984"] +} +``` + +It may look like this: + +```json +{ + "builder": { + "gc": { + "defaultKeepStorage": "20GB", + "enabled": true + } + }, + "features": { + "buildkit": true + }, + "insecure-registries": [ + "host.docker.internal:49984" + ] +} +``` +This allows Docker to send requests to local proxy, which handles the authentication. + +5. Click Apply & Restart. + + +## Linux + +1. Edit the Docker configuration file (usually `/etc/docker/daemon.json`) and add the following line, if the file doesn't exist, create it: +```json +{ + "insecure-registries": ["localhost:49984"] +} +``` + +2. Restart Docker: + +```bash +sudo systemctl restart docker +``` + +## Windows + +1. Open Docker Desktop. +2. Go to Settings. +3. Go to Docker Engine. +4. Add the following line to the json configuration: + +```json +{ + "insecure-registries": ["host.docker.internal:49984"] +} +``` +5. Click Apply & Restart. +