diff --git a/docs.json b/docs.json index 34728932..914a39bb 100644 --- a/docs.json +++ b/docs.json @@ -240,8 +240,48 @@ "icon": "square-js", "versions": [ { - "version": "v2.14.1", + "version": "v2.18.0", "default": true, + "pages": [ + "docs/sdk-reference/js-sdk/v2.18.0/errors", + "docs/sdk-reference/js-sdk/v2.18.0/sandbox", + "docs/sdk-reference/js-sdk/v2.18.0/sandbox-commands", + "docs/sdk-reference/js-sdk/v2.18.0/sandbox-filesystem", + "docs/sdk-reference/js-sdk/v2.18.0/template", + "docs/sdk-reference/js-sdk/v2.18.0/template-logger", + "docs/sdk-reference/js-sdk/v2.18.0/template-readycmd", + "docs/sdk-reference/js-sdk/v2.18.0/volume" + ] + }, + { + "version": "v2.17.0", + "default": false, + "pages": [ + "docs/sdk-reference/js-sdk/v2.17.0/errors", + "docs/sdk-reference/js-sdk/v2.17.0/sandbox", + "docs/sdk-reference/js-sdk/v2.17.0/sandbox-commands", + "docs/sdk-reference/js-sdk/v2.17.0/sandbox-filesystem", + "docs/sdk-reference/js-sdk/v2.17.0/template", + "docs/sdk-reference/js-sdk/v2.17.0/template-logger", + "docs/sdk-reference/js-sdk/v2.17.0/template-readycmd" + ] + }, + { + "version": "v2.16.0", + "default": false, + "pages": [ + "docs/sdk-reference/js-sdk/v2.16.0/errors", + "docs/sdk-reference/js-sdk/v2.16.0/sandbox", + "docs/sdk-reference/js-sdk/v2.16.0/sandbox-commands", + "docs/sdk-reference/js-sdk/v2.16.0/sandbox-filesystem", + "docs/sdk-reference/js-sdk/v2.16.0/template", + "docs/sdk-reference/js-sdk/v2.16.0/template-logger", + "docs/sdk-reference/js-sdk/v2.16.0/template-readycmd" + ] + }, + { + "version": "v2.14.1", + "default": false, "pages": [ "docs/sdk-reference/js-sdk/v2.14.1/errors", "docs/sdk-reference/js-sdk/v2.14.1/sandbox", @@ -1311,8 +1351,52 @@ "icon": "python", "versions": [ { - "version": "v2.15.2", + "version": "v2.19.0", "default": true, + "pages": [ + "docs/sdk-reference/python-sdk/v2.19.0/exceptions", + "docs/sdk-reference/python-sdk/v2.19.0/logger", + "docs/sdk-reference/python-sdk/v2.19.0/readycmd", + "docs/sdk-reference/python-sdk/v2.19.0/sandbox_async", + "docs/sdk-reference/python-sdk/v2.19.0/sandbox_sync", + "docs/sdk-reference/python-sdk/v2.19.0/template", + "docs/sdk-reference/python-sdk/v2.19.0/template_async", + "docs/sdk-reference/python-sdk/v2.19.0/template_sync", + "docs/sdk-reference/python-sdk/v2.19.0/volume_async", + "docs/sdk-reference/python-sdk/v2.19.0/volume_sync" + ] + }, + { + "version": "v2.18.0", + "default": false, + "pages": [ + "docs/sdk-reference/python-sdk/v2.18.0/exceptions", + "docs/sdk-reference/python-sdk/v2.18.0/logger", + "docs/sdk-reference/python-sdk/v2.18.0/readycmd", + "docs/sdk-reference/python-sdk/v2.18.0/sandbox_async", + "docs/sdk-reference/python-sdk/v2.18.0/sandbox_sync", + "docs/sdk-reference/python-sdk/v2.18.0/template", + "docs/sdk-reference/python-sdk/v2.18.0/template_async", + "docs/sdk-reference/python-sdk/v2.18.0/template_sync" + ] + }, + { + "version": "v2.17.0", + "default": false, + "pages": [ + "docs/sdk-reference/python-sdk/v2.17.0/exceptions", + "docs/sdk-reference/python-sdk/v2.17.0/logger", + "docs/sdk-reference/python-sdk/v2.17.0/readycmd", + "docs/sdk-reference/python-sdk/v2.17.0/sandbox_async", + "docs/sdk-reference/python-sdk/v2.17.0/sandbox_sync", + "docs/sdk-reference/python-sdk/v2.17.0/template", + "docs/sdk-reference/python-sdk/v2.17.0/template_async", + "docs/sdk-reference/python-sdk/v2.17.0/template_sync" + ] + }, + { + "version": "v2.15.2", + "default": false, "pages": [ "docs/sdk-reference/python-sdk/v2.15.2/exceptions", "docs/sdk-reference/python-sdk/v2.15.2/logger", @@ -2345,8 +2429,18 @@ "icon": "square-js", "versions": [ { - "version": "v2.3.3", + "version": "v2.4.0", "default": true, + "pages": [ + "docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/charts", + "docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/consts", + "docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/messaging", + "docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/sandbox" + ] + }, + { + "version": "v2.3.3", + "default": false, "pages": [ "docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/charts", "docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/consts", @@ -2491,8 +2585,15 @@ "icon": "python", "versions": [ { - "version": "v2.5.0", + "version": "v2.6.0", "default": true, + "pages": [ + "docs/sdk-reference/code-interpreter-python-sdk/v2.6.0/code_interpreter" + ] + }, + { + "version": "v2.5.0", + "default": false, "pages": [ "docs/sdk-reference/code-interpreter-python-sdk/v2.5.0/code_interpreter" ] @@ -3027,8 +3128,26 @@ "icon": "terminal", "versions": [ { - "version": "v2.8.1", + "version": "v2.9.0", "default": true, + "pages": [ + "docs/sdk-reference/cli/v2.9.0/auth", + "docs/sdk-reference/cli/v2.9.0/sandbox", + "docs/sdk-reference/cli/v2.9.0/template" + ] + }, + { + "version": "v2.8.2", + "default": false, + "pages": [ + "docs/sdk-reference/cli/v2.8.2/auth", + "docs/sdk-reference/cli/v2.8.2/sandbox", + "docs/sdk-reference/cli/v2.8.2/template" + ] + }, + { + "version": "v2.8.1", + "default": false, "pages": [ "docs/sdk-reference/cli/v2.8.1/auth", "docs/sdk-reference/cli/v2.8.1/sandbox", diff --git a/docs/sdk-reference/cli/v2.8.2/auth.mdx b/docs/sdk-reference/cli/v2.8.2/auth.mdx new file mode 100644 index 00000000..d7ee29c5 --- /dev/null +++ b/docs/sdk-reference/cli/v2.8.2/auth.mdx @@ -0,0 +1,62 @@ +--- +sidebarTitle: "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/docs/sdk-reference/cli/v2.8.2/sandbox.mdx b/docs/sdk-reference/cli/v2.8.2/sandbox.mdx new file mode 100644 index 00000000..b5d03644 --- /dev/null +++ b/docs/sdk-reference/cli/v2.8.2/sandbox.mdx @@ -0,0 +1,185 @@ +--- +sidebarTitle: "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 (default: 1000, 0 for no limit) ` + - `-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 pause + + +pause sandbox + +### Usage + +```bash +e2b sandbox pause [options] +``` + + +## e2b sandbox resume + + +resume paused sandbox + +### Usage + +```bash +e2b sandbox resume [options] +``` + + +## 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. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files. ` + - `-d, --detach: create sandbox without connecting terminal to it ` + + +## 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. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files. ` + - `-d, --detach: create sandbox without connecting terminal to it ` + + +## 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]` + + +## e2b sandbox exec + + +execute a command in a running sandbox + +### Usage + +```bash +e2b sandbox exec [options] +``` + +### Options + + + - `-b, --background: run in background and return immediately ` + - `-c, --cwd : working directory ` + - `-u, --user : run as specified user ` + - `-e, --env : set environment variable (repeatable) [default: [object Object]]` + + diff --git a/docs/sdk-reference/cli/v2.8.2/template.mdx b/docs/sdk-reference/cli/v2.8.2/template.mdx new file mode 100644 index 00000000..fbba4a5f --- /dev/null +++ b/docs/sdk-reference/cli/v2.8.2/template.mdx @@ -0,0 +1,184 @@ +--- +sidebarTitle: "Template" +--- + +## e2b template + + +manage sandbox templates + +### Usage + +```bash +e2b template [options] [command] +``` +## e2b template create + + +build Dockerfile as a Sandbox template. This command reads a Dockerfile and builds it directly. + +### Usage + +```bash +e2b template create [options] +``` + +### 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. ` + - `-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. ` + - `--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. ` + - `--no-cache: skip cache when building the template. ` + + +## 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. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files. ` + - `--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 + + +initialize a new sandbox template using the SDK + +### Usage + +```bash +e2b template init [options] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-n, --name : template name ` + - `-l, --language : target language: typescript, python-sync, python-async ` + + +## 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. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files. ` + - `-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. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files. ` + - `-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. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files. ` + - `-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 ` + + +## e2b template migrate + + +migrate e2b.Dockerfile and e2b.toml to new Template SDK format + +### Usage + +```bash +e2b template migrate [options] +``` + +### Options + + + - `-d, --dockerfile : specify path to Dockerfile. Defaults to e2b.Dockerfile ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files. ` + - `-l, --language : specify target language: typescript, python-sync, python-async ` + - `-p, --path : change root directory where command is executed to  directory ` + + diff --git a/docs/sdk-reference/cli/v2.9.0/auth.mdx b/docs/sdk-reference/cli/v2.9.0/auth.mdx new file mode 100644 index 00000000..d7ee29c5 --- /dev/null +++ b/docs/sdk-reference/cli/v2.9.0/auth.mdx @@ -0,0 +1,62 @@ +--- +sidebarTitle: "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/docs/sdk-reference/cli/v2.9.0/sandbox.mdx b/docs/sdk-reference/cli/v2.9.0/sandbox.mdx new file mode 100644 index 00000000..cc14272f --- /dev/null +++ b/docs/sdk-reference/cli/v2.9.0/sandbox.mdx @@ -0,0 +1,202 @@ +--- +sidebarTitle: "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 info + + +show information for a sandbox + +### Usage + +```bash +e2b sandbox info [options] +``` + +### Options + + + - `-f, --format : output format, eg. json, pretty ` + + +## 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 (default: 1000, 0 for no limit) ` + - `-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 pause + + +pause sandbox + +### Usage + +```bash +e2b sandbox pause [options] +``` + + +## e2b sandbox resume + + +resume paused sandbox + +### Usage + +```bash +e2b sandbox resume [options] +``` + + +## 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. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files. ` + - `-d, --detach: create sandbox without connecting terminal to it ` + + +## 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. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files. ` + - `-d, --detach: create sandbox without connecting terminal to it ` + + +## 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]` + + +## e2b sandbox exec + + +execute a command in a running sandbox + +### Usage + +```bash +e2b sandbox exec [options] +``` + +### Options + + + - `-b, --background: run in background and return immediately ` + - `-c, --cwd : working directory ` + - `-u, --user : run as specified user ` + - `-e, --env : set environment variable (repeatable) [default: [object Object]]` + + diff --git a/docs/sdk-reference/cli/v2.9.0/template.mdx b/docs/sdk-reference/cli/v2.9.0/template.mdx new file mode 100644 index 00000000..fbba4a5f --- /dev/null +++ b/docs/sdk-reference/cli/v2.9.0/template.mdx @@ -0,0 +1,184 @@ +--- +sidebarTitle: "Template" +--- + +## e2b template + + +manage sandbox templates + +### Usage + +```bash +e2b template [options] [command] +``` +## e2b template create + + +build Dockerfile as a Sandbox template. This command reads a Dockerfile and builds it directly. + +### Usage + +```bash +e2b template create [options] +``` + +### 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. ` + - `-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. ` + - `--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. ` + - `--no-cache: skip cache when building the template. ` + + +## 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. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files. ` + - `--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 + + +initialize a new sandbox template using the SDK + +### Usage + +```bash +e2b template init [options] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-n, --name : template name ` + - `-l, --language : target language: typescript, python-sync, python-async ` + + +## 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. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files. ` + - `-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. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files. ` + - `-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. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files. ` + - `-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 ` + + +## e2b template migrate + + +migrate e2b.Dockerfile and e2b.toml to new Template SDK format + +### Usage + +```bash +e2b template migrate [options] +``` + +### Options + + + - `-d, --dockerfile : specify path to Dockerfile. Defaults to e2b.Dockerfile ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. We recommend using the new build system (https://e2b.dev/docs/template/defining-template) that does not use config files. ` + - `-l, --language : specify target language: typescript, python-sync, python-async ` + - `-p, --path : change root directory where command is executed to  directory ` + + diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/charts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/charts.mdx new file mode 100644 index 00000000..2390eaa1 --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/charts.mdx @@ -0,0 +1,244 @@ +--- +sidebarTitle: "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` | `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` | `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` | `LINE` | + +*** + +### PieChart + +```ts +type PieChart = Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `PieData`[] | +| `type` | `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` | `SCATTER` | + +*** + +### SuperChart + +```ts +type SuperChart = Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `Chart`[] | +| `type` | `SUPERCHART` | + +## Functions + +### deserializeChart() + +```ts +function deserializeChart(data: any): Chart +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `any` | + +#### Returns + +`Chart` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/consts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/consts.mdx new file mode 100644 index 00000000..391e3b34 --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/consts.mdx @@ -0,0 +1,17 @@ +--- +sidebarTitle: "Consts" +--- + +### DEFAULT\_TIMEOUT\_MS + +```ts +const DEFAULT_TIMEOUT_MS: 60000 = 60_000; +``` + +*** + +### JUPYTER\_PORT + +```ts +const JUPYTER_PORT: 49999 = 49999; +``` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/messaging.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/messaging.mdx new file mode 100644 index 00000000..7994bfdb --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/messaging.mdx @@ -0,0 +1,332 @@ +--- +sidebarTitle: "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 + +###### Get Signature + +```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/docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/sandbox.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/sandbox.mdx new file mode 100644 index 00000000..f1c56656 --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.4.0/sandbox.mdx @@ -0,0 +1,370 @@ +--- +sidebarTitle: "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. + +### listCodeContexts() + +```ts +listCodeContexts(): Promise +``` + +List all contexts. + +###### Returns + +`Promise`\<`Context`[]\> + +list of contexts. + +### removeCodeContext() + +```ts +removeCodeContext(context: string | Context): Promise +``` + +Removes a context. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `context` | `string` \| `Context` | context to remove. | + +###### Returns + +`Promise`\<`void`\> + +void. + +### restartCodeContext() + +```ts +restartCodeContext(context: string | Context): Promise +``` + +Restart a context. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `context` | `string` \| `Context` | context to restart. | + +###### Returns + +`Promise`\<`void`\> + +void. + +### runCode() + +###### Call Signature + +```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. + +###### Call Signature + +```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. + +###### Call Signature + +```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/docs/sdk-reference/code-interpreter-python-sdk/v2.6.0/code_interpreter.mdx b/docs/sdk-reference/code-interpreter-python-sdk/v2.6.0/code_interpreter.mdx new file mode 100644 index 00000000..2177c739 --- /dev/null +++ b/docs/sdk-reference/code-interpreter-python-sdk/v2.6.0/code_interpreter.mdx @@ -0,0 +1,888 @@ +--- +sidebarTitle: "Code Interpreter" +--- + + + + + + + + + +## Sandbox + +```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](https://e2b.dev/docs). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() +``` + + + +### run\_code + +```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 +@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 +@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 +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 + + + +### remove\_code\_context + +```python +def remove_code_context(context: Union[Context, str]) -> None +``` + +Removes a context. + +**Arguments**: + +- `context`: Context to remove. Can be a Context object or a context ID string. + +**Returns**: + +None + + + +### list\_code\_contexts + +```python +def list_code_contexts() -> List[Context] +``` + +List all contexts. + +**Returns**: + +List of contexts. + + + +### restart\_code\_context + +```python +def restart_code_context(context: Union[Context, str]) -> None +``` + +Restart a context. + +**Arguments**: + +- `context`: Context to restart. Can be a Context object or a context ID string. + +**Returns**: + +None + + + + + + + + + +## AsyncSandbox + +```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](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + + +### run\_code + +```python +@overload +async def run_code( + code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[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 +@overload +async def run_code( + code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[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 +@overload +async def run_code( + code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[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 +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 + + + +### remove\_code\_context + +```python +async def remove_code_context(context: Union[Context, str]) -> None +``` + +Removes a context. + +**Arguments**: + +- `context`: Context to remove. Can be a Context object or a context ID string. + +**Returns**: + +None + + + +### list\_code\_contexts + +```python +async def list_code_contexts() -> List[Context] +``` + +List all contexts. + +**Returns**: + +List of contexts. + + + +### restart\_code\_context + +```python +async def restart_code_context(context: Union[Context, str]) -> None +``` + +Restart a context. + +**Arguments**: + +- `context`: Context to restart. Can be a Context object or a context ID string. + +**Returns**: + +None + + + + + + + + + +## OutputMessage + +```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 +@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 +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + + +## MIMEType + +```python +class MIMEType(str) +``` + +Represents a MIME type. + + + +## Result + +```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 +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + + +### \_\_str\_\_ + +```python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + + +### \_repr\_html\_ + +```python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + + +### \_repr\_markdown\_ + +```python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + + +### \_repr\_svg\_ + +```python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + + +### \_repr\_png\_ + +```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 +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + + +### \_repr\_pdf\_ + +```python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + + +### \_repr\_latex\_ + +```python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + + +### \_repr\_json\_ + +```python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + + +### \_repr\_javascript\_ + +```python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + + +## Logs + +```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 +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + + +### serialize\_results + +```python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + + +## Execution + +```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 +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + + +## Context + +```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 +class ChartType(str, enum.Enum) +``` + +Chart types + + + +## ScaleType + +```python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + + +## Chart + +```python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. diff --git a/docs/sdk-reference/js-sdk/v2.16.0/errors.mdx b/docs/sdk-reference/js-sdk/v2.16.0/errors.mdx new file mode 100644 index 00000000..aeef2098 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.16.0/errors.mdx @@ -0,0 +1,381 @@ +--- +sidebarTitle: "Errors" +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Extended by + +- `GitAuthError` + +#### Constructors + +```ts +new AuthenticationError(message: string): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`AuthenticationError` + +``` + +*** + +### BuildError + +Thrown when the build fails. + +#### Extended by + +- `FileUploadError` + +#### Constructors + +```ts +new BuildError(message: string, stackTrace?: string): BuildError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`BuildError` + +``` + +*** + +### FileNotFoundError + +Thrown when a file or directory is not found inside a sandbox. + +#### Constructors + +```ts +new FileNotFoundError(message: string, stackTrace?: string): FileNotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`FileNotFoundError` + +*** + +### FileUploadError + +Thrown when the file upload fails. + +#### Constructors + +```ts +new FileUploadError(message: string, stackTrace?: string): FileUploadError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`FileUploadError` + +*** + +### GitAuthError + +Thrown when git authentication fails. + +#### Constructors + +```ts +new GitAuthError(message: string): GitAuthError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`GitAuthError` + +*** + +### GitUpstreamError + +Thrown when git upstream tracking is missing. + +#### Constructors + +```ts +new GitUpstreamError(message: string, stackTrace?: string): GitUpstreamError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`GitUpstreamError` + +*** + +### 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. + +#### Deprecated + +Use FileNotFoundError or SandboxNotFoundError instead. This class will be removed in the next major version. + +#### Extended by + +- `FileNotFoundError` +- `SandboxNotFoundError` + +#### 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` +- `GitUpstreamError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message?: string, stackTrace?: string): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message`? | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`SandboxError` + +``` + +*** + +### SandboxNotFoundError + +Thrown when a sandbox is not found (e.g. it doesn't exist or is no longer running). + +#### Constructors + +```ts +new SandboxNotFoundError(message: string, stackTrace?: string): SandboxNotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`SandboxNotFoundError` + +*** + +### 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/docs/sdk-reference/js-sdk/v2.16.0/sandbox-commands.mdx b/docs/sdk-reference/js-sdk/v2.16.0/sandbox-commands.mdx new file mode 100644 index 00000000..c97c6b9b --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.16.0/sandbox-commands.mdx @@ -0,0 +1,555 @@ +--- +sidebarTitle: "Commands" +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands( + transport: Transport, + connectionConfig: ConnectionConfig, + metadata: object): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | +| `metadata` | \{ `version`: `string`; \} | +| `metadata.version` | `string` | + +###### 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() + +###### Call Signature + +```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. + +###### Call Signature + +```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. + +###### Call Signature + +```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 | Uint8Array, +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` \| `Uint8Array`\<`ArrayBufferLike`\> | 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, + metadata: object): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | +| `metadata` | \{ `version`: `string`; \} | +| `metadata.version` | `string` | + +###### Returns + +`Pty` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: PtyConnectOpts): Promise +``` + +Connect to a running PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY to connect to. You can get the list of running PTYs using Commands.list. | +| `opts`? | `PtyConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### 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` | \{ `cols`: `number`; `rows`: `number`; \} | 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 +``` + +### stdin? + +```ts +optional stdin: boolean; +``` + +If true, command stdin is kept open and you can send data to it using Commands.sendStdin or CommandHandle.sendStdin. + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to run the command as. + +###### Default + +`default Sandbox user (as specified in the template)` + +*** + +### 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/docs/sdk-reference/js-sdk/v2.16.0/sandbox-filesystem.mdx b/docs/sdk-reference/js-sdk/v2.16.0/sandbox-filesystem.mdx new file mode 100644 index 00000000..aed576f6 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.16.0/sandbox-filesystem.mdx @@ -0,0 +1,665 @@ +--- +sidebarTitle: "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() + +###### Call Signature + +```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 + +###### Call Signature + +```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`\<`ArrayBufferLike`\>\> + +file content as `Uint8Array` + +###### Call Signature + +```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` + +###### Call Signature + +```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`\<`ArrayBufferLike`\>\>\> + +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() + +###### Call Signature + +```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 + +###### Call Signature + +```ts +write(files: WriteEntry[], 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 | +| ------ | ------ | ------ | +| `files` | `WriteEntry`[] | - | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +information about the written file + +### writeFiles() + +```ts +writeFiles(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +Write multiple files. + +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 | +| ------ | ------ | ------ | +| `files` | `WriteEntry`[] | list of files to write as `WriteEntry` objects, each containing `path` and `data`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +information about the written files + +## 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: string; +``` + +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: string; +``` + +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: string; +``` + +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/docs/sdk-reference/js-sdk/v2.16.0/sandbox.mdx b/docs/sdk-reference/js-sdk/v2.16.0/sandbox.mdx new file mode 100644 index 00000000..023ea3ed --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.16.0/sandbox.mdx @@ -0,0 +1,938 @@ +--- +sidebarTitle: "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 git operations +- 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 | +| `git` | `readonly` | `Git` | Module for running git operations in the sandbox | +| `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. | +| `trafficAccessToken?` | `readonly` | `string` | Traffic access token for accessing sandbox services with restricted public traffic. | + +#### Methods + +### ~~betaPause()~~ + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `ConnectionOpts` | + +###### Returns + +`Promise`\<`boolean`\> + +###### Deprecated + +Use Sandbox.pause instead. + +### connect() + +```ts +connect(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). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxConnectOpts` | 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() +``` + +### createSnapshot() + +```ts +createSnapshot(opts?: SandboxApiOpts): Promise +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshotId` with `Sandbox.create(snapshotId)` to create a new sandbox from the snapshot. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SnapshotInfo`\> + +snapshot information including the snapshot ID. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.files.write('/app/state.json', '{"step": 1}') + +// Create a snapshot +const snapshot = await sandbox.createSnapshot() + +// Create a new sandbox from the snapshot +const newSandbox = await Sandbox.create(snapshot.snapshotId) +``` + +### 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 + +### getMcpToken() + +```ts +getMcpToken(): Promise +``` + +Get the MCP token for the sandbox. + +###### Returns + +`Promise`\<`undefined` \| `string`\> + +MCP token for the sandbox, or undefined if MCP is not enabled. + +### getMcpUrl() + +```ts +getMcpUrl(): string +``` + +Get the MCP URL for the sandbox. + +###### Returns + +`string` + +MCP URL for 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`\> + +### listSnapshots() + +```ts +listSnapshots(opts?: Omit): SnapshotPaginator +``` + +List all snapshots created from this sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Omit`\<`SnapshotListOpts`, `"sandboxId"`\> | list options. | + +###### Returns + +`SnapshotPaginator` + +paginator for listing snapshots from this sandbox. + +### pause() + +```ts +pause(opts?: ConnectionOpts): Promise +``` + +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. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.pause() +``` + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. + +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() + +###### Call Signature + +```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 + +###### Call Signature + +```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 +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`boolean`\> + +###### Deprecated + +Use SandboxApi.pause instead. + +``` + +### 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() + +###### Call Signature + +```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 + +###### 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 + +### createSnapshot() + +```ts +static createSnapshot(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Create a snapshot from a sandbox. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same state. +The snapshot is a persistent image that survives sandbox deletion. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID to create snapshot from. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SnapshotInfo`\> + +snapshot information including the snapshot name that can be used with Sandbox.create(). + +``` + +### deleteSnapshot() + +```ts +static deleteSnapshot(snapshotId: string, opts?: SandboxApiOpts): Promise +``` + +Delete a snapshot. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `snapshotId` | `string` | snapshot ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the snapshot was deleted, `false` if it was not found. + +``` + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise<{ + allowInternetAccess: undefined | boolean; + cpuCount: number; + endAt: Date; + envdAccessToken: undefined | string; + envdVersion: string; + lifecycle: | undefined + | { + autoResume: boolean; + onTimeout: "kill" | "pause"; + }; + memoryMB: number; + metadata: {}; + name: string; + network: | undefined + | { + allowOut: undefined | string[]; + allowPublicTraffic: undefined | boolean; + denyOut: undefined | string[]; + maskRequestHost: undefined | string; + }; + sandboxDomain: undefined | string; + sandboxId: string; + startedAt: Date; + state: "running" | "paused"; + templateId: string; +}> +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<\{ + `allowInternetAccess`: `undefined` \| `boolean`; + `cpuCount`: `number`; + `endAt`: `Date`; + `envdAccessToken`: `undefined` \| `string`; + `envdVersion`: `string`; + `lifecycle`: \| `undefined` + \| \{ + `autoResume`: `boolean`; + `onTimeout`: `"kill"` \| `"pause"`; + \}; + `memoryMB`: `number`; + `metadata`: \{\}; + `name`: `string`; + `network`: \| `undefined` + \| \{ + `allowOut`: `undefined` \| `string`[]; + `allowPublicTraffic`: `undefined` \| `boolean`; + `denyOut`: `undefined` \| `string`[]; + `maskRequestHost`: `undefined` \| `string`; + \}; + `sandboxDomain`: `undefined` \| `string`; + `sandboxId`: `string`; + `startedAt`: `Date`; + `state`: `"running"` \| `"paused"`; + `templateId`: `string`; + \}\> + +``` + +### 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. + +### listSnapshots() + +```ts +static listSnapshots(opts?: SnapshotListOpts): SnapshotPaginator +``` + +List all snapshots. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SnapshotListOpts` | list options including filters and pagination. | + +###### Returns + +`SnapshotPaginator` + +paginator for listing snapshots. + +``` + +### pause() + +```ts +static pause(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. + +``` + +### 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: string; +``` + +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/docs/sdk-reference/js-sdk/v2.16.0/template-logger.mdx b/docs/sdk-reference/js-sdk/v2.16.0/template-logger.mdx new file mode 100644 index 00000000..bb4b9315 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.16.0/template-logger.mdx @@ -0,0 +1,195 @@ +--- +sidebarTitle: "Logger" +--- + +### LogEntry + +Represents a single log entry from the template build process. + +#### Extended by + +- `LogEntryStart` +- `LogEntryEnd` + +#### Constructors + +```ts +new LogEntry( + timestamp: Date, + level: LogEntryLevel, + message: string): LogEntry +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `level` | `LogEntryLevel` | +| `message` | `string` | + +###### Returns + +`LogEntry` + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | +| `message` | `readonly` | `string` | +| `timestamp` | `readonly` | `Date` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### LogEntryEnd + +Special log entry indicating the end of a build process. + +#### Constructors + +```ts +new LogEntryEnd(timestamp: Date, message: string): LogEntryEnd +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `message` | `string` | + +###### Returns + +`LogEntryEnd` + +#### Properties + +| Property | Modifier | Type | Inherited from | +| ------ | ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | +| `message` | `readonly` | `string` | `LogEntry`.`message` | +| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### LogEntryStart + +Special log entry indicating the start of a build process. + +#### Constructors + +```ts +new LogEntryStart(timestamp: Date, message: string): LogEntryStart +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `message` | `string` | + +###### Returns + +`LogEntryStart` + +#### Properties + +| Property | Modifier | Type | Inherited from | +| ------ | ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | +| `message` | `readonly` | `string` | `LogEntry`.`message` | +| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +## Type Aliases + +### LogEntryLevel + +```ts +type LogEntryLevel = "debug" | "info" | "warn" | "error"; +``` + +Log entry severity levels. + +## Functions + +### defaultBuildLogger() + +```ts +function defaultBuildLogger(options?: object): (logEntry: LogEntry) => void +``` + +Create a default build logger with animated timer display. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options`? | \{ `minLevel`: `LogEntryLevel`; \} | Logger configuration options | +| `options.minLevel`? | `LogEntryLevel` | Minimum log level to display (default: 'info') | + +#### Returns + +`Function` + +Logger function that accepts LogEntry instances + +### Parameters + +| Parameter | Type | +| ------ | ------ | +| `logEntry` | `LogEntry` | + +### Returns + +`void` + +#### Example + +```ts +import { Template, defaultBuildLogger } from 'e2b' + +const template = Template().fromPythonImage() + +await Template.build(template, { + alias: 'my-template', + onBuildLogs: defaultBuildLogger({ minLevel: 'debug' }) +}) +``` diff --git a/docs/sdk-reference/js-sdk/v2.16.0/template-readycmd.mdx b/docs/sdk-reference/js-sdk/v2.16.0/template-readycmd.mdx new file mode 100644 index 00000000..a35a37aa --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.16.0/template-readycmd.mdx @@ -0,0 +1,201 @@ +--- +sidebarTitle: "Readycmd" +--- + +### ReadyCmd + +Class for ready check commands. + +#### Constructors + +```ts +new ReadyCmd(cmd: string): ReadyCmd +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `cmd` | `string` | + +###### Returns + +`ReadyCmd` + +#### Methods + +### getCmd() + +```ts +getCmd(): string +``` + +###### Returns + +`string` + +## Functions + +### waitForFile() + +```ts +function waitForFile(filename: string): ReadyCmd +``` + +Wait for a file to exist. +Uses shell test command to check file existence. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filename` | `string` | Path to the file to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the file + +#### Example + +```ts +import { Template, waitForFile } from 'e2b' + +const template = Template() + .fromBaseImage() + .setStartCmd('./init.sh', waitForFile('/tmp/ready')) +``` + +*** + +### waitForPort() + +```ts +function waitForPort(port: number): ReadyCmd +``` + +Wait for a port to be listening. +Uses `ss` command to check if a port is open and listening. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | Port number to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the port + +#### Example + +```ts +import { Template, waitForPort } from 'e2b' + +const template = Template() + .fromPythonImage() + .setStartCmd('python -m http.server 8000', waitForPort(8000)) +``` + +*** + +### waitForProcess() + +```ts +function waitForProcess(processName: string): ReadyCmd +``` + +Wait for a process with a specific name to be running. +Uses `pgrep` to check if a process exists. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `processName` | `string` | Name of the process to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the process + +#### Example + +```ts +import { Template, waitForProcess } from 'e2b' + +const template = Template() + .fromBaseImage() + .setStartCmd('./my-daemon', waitForProcess('my-daemon')) +``` + +*** + +### waitForTimeout() + +```ts +function waitForTimeout(timeout: number): ReadyCmd +``` + +Wait for a specified timeout before considering the sandbox ready. +Uses `sleep` command to wait for a fixed duration. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeout` | `number` | Time to wait in milliseconds (minimum: 1000ms / 1 second) | + +#### Returns + +`ReadyCmd` + +ReadyCmd that waits for the specified duration + +#### Example + +```ts +import { Template, waitForTimeout } from 'e2b' + +const template = Template() + .fromNodeImage() + .setStartCmd('npm start', waitForTimeout(5000)) // Wait 5 seconds +``` + +*** + +### waitForURL() + +```ts +function waitForURL(url: string, statusCode: number): ReadyCmd +``` + +Wait for a URL to return a specific HTTP status code. +Uses `curl` to make HTTP requests and check the response status. + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `url` | `string` | `undefined` | URL to check (e.g., 'http://localhost:3000/health') | +| `statusCode` | `number` | `200` | Expected HTTP status code (default: 200) | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks the URL + +#### Example + +```ts +import { Template, waitForURL } from 'e2b' + +const template = Template() + .fromNodeImage() + .setStartCmd('npm start', waitForURL('http://localhost:3000/health')) +``` diff --git a/docs/sdk-reference/js-sdk/v2.16.0/template.mdx b/docs/sdk-reference/js-sdk/v2.16.0/template.mdx new file mode 100644 index 00000000..c0fbcf34 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.16.0/template.mdx @@ -0,0 +1,2377 @@ +--- +sidebarTitle: "Template" +--- + +### TemplateBase + +Base class for building E2B sandbox templates. + +#### Implements + +- `TemplateFromImage` +- `TemplateBuilder` +- `TemplateFinal` + +#### Constructors + +```ts +new TemplateBase(options?: TemplateOptions): TemplateBase +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `options`? | `TemplateOptions` | + +###### Returns + +`TemplateBase` + +#### Methods + +### addMcpServer() + +```ts +addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder +``` + +Install MCP servers using mcp-gateway. +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | + +###### Returns + +`TemplateBuilder` + +###### Throws + +If the base template is not mcp-gateway + +###### Example + +```ts +template.addMcpServer('exa') +template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) +``` + +###### Implementation of + +`TemplateBuilder`.`addMcpServer` + +### aptInstall() + +```ts +aptInstall(packages: string | string[], options?: object): TemplateBuilder +``` + +Install Debian/Ubuntu packages using apt-get. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages` | `string` \| `string`[] | Package name(s) | +| `options`? | \{ `fixMissing`: `boolean`; `noInstallRecommends`: `boolean`; \} | - | +| `options.fixMissing`? | `boolean` | - | +| `options.noInstallRecommends`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.aptInstall('vim') +template.aptInstall(['git', 'curl', 'wget']) +template.aptInstall(['vim'], { noInstallRecommends: true }) +template.aptInstall(['vim'], { fixMissing: true }) +``` + +###### Implementation of + +`TemplateBuilder`.`aptInstall` + +### betaDevContainerPrebuild() + +```ts +betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder +``` + +Prebuild a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') +``` + +###### Implementation of + +`TemplateBuilder`.`betaDevContainerPrebuild` + +### betaSetDevContainerStart() + +```ts +betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal +``` + +Start a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .startDevcontainer('/my-devcontainer') + +// Prebuild and start +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') + // Other instructions... + .betaSetDevContainerStart('/my-devcontainer') +``` + +###### Implementation of + +`TemplateBuilder`.`betaSetDevContainerStart` + +### bunInstall() + +```ts +bunInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Bun packages using bun. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | \{ `dev`: `boolean`; `g`: `boolean`; \} | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.bunInstall('express') +template.bunInstall(['lodash', 'axios']) +template.bunInstall('tsx', { g: true }) +template.bunInstall('typescript', { dev: true }) +template.bunInstall() // Installs from package.json +``` + +###### Implementation of + +`TemplateBuilder`.`bunInstall` + +### copy() + +```ts +copy( + src: PathLike | PathLike[], + dest: PathLike, + options?: object): TemplateBuilder +``` + +Copy files or directories into the template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` \| `PathLike`[] | Source path(s) | +| `dest` | `PathLike` | Destination path | +| `options`? | \{ `forceUpload`: `true`; `mode`: `number`; `resolveSymlinks`: `boolean`; `user`: `string`; \} | Copy options | +| `options.forceUpload`? | `true` | - | +| `options.mode`? | `number` | - | +| `options.resolveSymlinks`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copy('requirements.txt', '/home/user/') +template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) +``` + +###### Implementation of + +`TemplateBuilder`.`copy` + +### copyItems() + +```ts +copyItems(items: CopyItem[]): TemplateBuilder +``` + +Copy multiple items with individual options. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `items` | `CopyItem`[] | Array of copy items | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copyItems([ + { src: 'app.ts', dest: '/app/' }, + { src: 'config.ts', dest: '/app/', mode: 0o644 } +]) +``` + +###### Implementation of + +`TemplateBuilder`.`copyItems` + +### fromAWSRegistry() + +```ts +fromAWSRegistry(image: string, credentials: object): TemplateBuilder +``` + +Start from a Docker image in AWS ECR. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `image` | `string` | Full ECR image path | +| `credentials` | \{ `accessKeyId`: `string`; `region`: `string`; `secretAccessKey`: `string`; \} | AWS credentials | +| `credentials.accessKeyId` | `string` | - | +| `credentials.region` | `string` | - | +| `credentials.secretAccessKey` | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromAWSRegistry( + '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', + { + accessKeyId: 'AKIA...', + secretAccessKey: '...', + region: 'us-west-2' + } +) +``` + +###### Implementation of + +```ts +TemplateFromImage.fromAWSRegistry +``` + +### fromBaseImage() + +```ts +fromBaseImage(): TemplateBuilder +``` + +Start from E2B's default base image (e2bdev/base:latest). + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromBaseImage() +``` + +###### Implementation of + +```ts +TemplateFromImage.fromBaseImage +``` + +### fromBunImage() + +```ts +fromBunImage(variant: string): TemplateBuilder +``` + +Start from a Bun-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'latest'` | Bun variant (default: 'latest') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromBunImage('1.3') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromBunImage +``` + +### fromDebianImage() + +```ts +fromDebianImage(variant: string): TemplateBuilder +``` + +Start from a Debian-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'stable'` | Debian variant (default: 'stable') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromDebianImage('bookworm') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromDebianImage +``` + +### fromDockerfile() + +```ts +fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder +``` + +Parse a Dockerfile and convert it to Template SDK format. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `dockerfileContentOrPath` | `string` | Dockerfile content or path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromDockerfile('Dockerfile') +Template().fromDockerfile('FROM python:3\nRUN pip install numpy') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromDockerfile +``` + +### fromGCPRegistry() + +```ts +fromGCPRegistry(image: string, credentials: object): TemplateBuilder +``` + +Start from a Docker image in Google Container Registry. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `image` | `string` | Full GCR/GAR image path | +| `credentials` | \{ `serviceAccountJSON`: `string` \| `object`; \} | GCP service account credentials | +| `credentials.serviceAccountJSON` | `string` \| `object` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromGCPRegistry( + 'gcr.io/myproject/myimage:latest', + { serviceAccountJSON: 'path/to/service-account.json' } +) +``` + +###### Implementation of + +```ts +TemplateFromImage.fromGCPRegistry +``` + +### fromImage() + +```ts +fromImage(baseImage: string, credentials?: object): TemplateBuilder +``` + +Start from a custom Docker image. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `baseImage` | `string` | Docker image name | +| `credentials`? | \{ `password`: `string`; `username`: `string`; \} | Optional credentials for private registries | +| `credentials.password`? | `string` | - | +| `credentials.username`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromImage('python:3') + +// With credentials (optional) +Template().fromImage('myregistry.com/myimage:latest', { + username: 'user', + password: 'pass' +}) +``` + +###### Implementation of + +```ts +TemplateFromImage.fromImage +``` + +### fromNodeImage() + +```ts +fromNodeImage(variant: string): TemplateBuilder +``` + +Start from a Node.js-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'lts'` | Node.js variant (default: 'lts') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromNodeImage('24') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromNodeImage +``` + +### fromPythonImage() + +```ts +fromPythonImage(version: string): TemplateBuilder +``` + +Start from a Python-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `version` | `string` | `'3'` | Python version (default: '3') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromPythonImage('3') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromPythonImage +``` + +### fromTemplate() + +```ts +fromTemplate(template: string): TemplateBuilder +``` + +Start from an existing E2B template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `string` | E2B template ID or alias | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromTemplate('my-base-template') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromTemplate +``` + +### fromUbuntuImage() + +```ts +fromUbuntuImage(variant: string): TemplateBuilder +``` + +Start from an Ubuntu-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'latest'` | Ubuntu variant (default: 'latest') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromUbuntuImage('24.04') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromUbuntuImage +``` + +### gitClone() + +```ts +gitClone( + url: string, + path?: PathLike, + options?: object): TemplateBuilder +``` + +Clone a Git repository. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | Repository URL | +| `path`? | `PathLike` | Optional destination path | +| `options`? | \{ `branch`: `string`; `depth`: `number`; `user`: `string`; \} | Clone options | +| `options.branch`? | `string` | - | +| `options.depth`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.gitClone('https://github.com/user/repo.git', '/app/repo') +template.gitClone('https://github.com/user/repo.git', undefined, { + branch: 'main', + depth: 1 +}) +template.gitClone('https://github.com/user/repo.git', '/app/repo', { + user: 'root' +}) +``` + +###### Implementation of + +`TemplateBuilder`.`gitClone` + +### makeDir() + +```ts +makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Create directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | +| `options`? | \{ `mode`: `number`; `user`: `string`; \} | Directory options | +| `options.mode`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeDir('/app/data', { mode: 0o755 }) +template.makeDir(['/app/logs', '/app/cache']) +template.makeDir('/app/data', { mode: 0o755, user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`makeDir` + +### makeSymlink() + +```ts +makeSymlink( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Create a symbolic link. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path (target) | +| `dest` | `PathLike` | Destination path (symlink location) | +| `options`? | \{ `force`: `boolean`; `user`: `string`; \} | Symlink options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeSymlink('/usr/bin/python3', '/usr/bin/python') +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) +``` + +###### Implementation of + +`TemplateBuilder`.`makeSymlink` + +### npmInstall() + +```ts +npmInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Node.js packages using npm. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | \{ `dev`: `boolean`; `g`: `boolean`; \} | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.npmInstall('express') +template.npmInstall(['lodash', 'axios']) +template.npmInstall('tsx', { g: true }) +template.npmInstall('typescript', { dev: true }) +template.npmInstall() // Installs from package.json +``` + +###### Implementation of + +`TemplateBuilder`.`npmInstall` + +### pipInstall() + +```ts +pipInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Python packages using pip. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | +| `options`? | \{ `g`: `boolean`; \} | Install options | +| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.pipInstall('numpy') // Installs globally (default) +template.pipInstall(['pandas', 'scikit-learn']) +template.pipInstall('numpy', { g: false }) // Install for user only +template.pipInstall() // Installs from current directory +``` + +###### Implementation of + +`TemplateBuilder`.`pipInstall` + +### remove() + +```ts +remove(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Remove files or directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | +| `options`? | \{ `force`: `boolean`; `recursive`: `boolean`; `user`: `string`; \} | Remove options | +| `options.force`? | `boolean` | - | +| `options.recursive`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.remove('/tmp/cache', { recursive: true, force: true }) +template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`remove` + +### rename() + +```ts +rename( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Rename or move a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path | +| `dest` | `PathLike` | Destination path | +| `options`? | \{ `force`: `boolean`; `user`: `string`; \} | Rename options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`rename` + +### runCmd() + +###### Call Signature + +```ts +runCmd(command: string, options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `command` | `string` | Command string | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`runCmd` + +###### Call Signature + +```ts +runCmd(commands: string[], options?: object): TemplateBuilder +``` + +Run multiple shell commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commands` | `string`[] | Array of command strings | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Implementation of + +`TemplateBuilder`.`runCmd` + +### setEnvs() + +```ts +setEnvs(envs: Record): TemplateBuilder +``` + +Set environment variables. +Note: Environment variables defined here are available only during template build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `envs` | `Record`\<`string`, `string`\> | Environment variables | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) +``` + +###### Implementation of + +`TemplateBuilder`.`setEnvs` + +### setReadyCmd() + +```ts +setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set or update the ready check command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setReadyCmd('curl http://localhost:8000/health') + +// Using ReadyCmd helpers +import { waitForPort, waitForFile, waitForProcess } from 'e2b' + +template.setReadyCmd(waitForPort(3000)) + +template.setReadyCmd(waitForFile('/tmp/ready')) + +template.setReadyCmd(waitForProcess('nginx')) +``` + +###### Implementation of + +`TemplateBuilder`.`setReadyCmd` + +### setStartCmd() + +```ts +setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set the start command and ready check. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `startCommand` | `string` | Command to run on startup | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setStartCmd( + 'node app.js', + 'curl http://localhost:8000/health' +) + +// Using ReadyCmd helpers +import { waitForPort, waitForURL } from 'e2b' + +template.setStartCmd( + 'python -m http.server 8000', + waitForPort(8000) +) + +template.setStartCmd( + 'npm start', + waitForURL('http://localhost:3000/health', 200) +) +``` + +###### Implementation of + +`TemplateBuilder`.`setStartCmd` + +### setUser() + +```ts +setUser(user: string): TemplateBuilder +``` + +Set the user for subsequent commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `user` | `string` | Username | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setUser('root') +``` + +###### Implementation of + +`TemplateBuilder`.`setUser` + +### setWorkdir() + +```ts +setWorkdir(workdir: PathLike): TemplateBuilder +``` + +Set the working directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `workdir` | `PathLike` | Working directory path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setWorkdir('/app') +``` + +###### Implementation of + +`TemplateBuilder`.`setWorkdir` + +### skipCache() + +```ts +skipCache(): this +``` + +Skip cache for all subsequent build instructions from this point. + +###### Returns + +`this` + +###### Example + +```ts +Template().skipCache().fromPythonImage('3') +``` + +###### Implementation of + +`TemplateBuilder`.`skipCache` + +### ~~aliasExists()~~ + +```ts +static aliasExists(alias: string, options?: ConnectionOpts): Promise +``` + +Check if a template with the given alias exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `alias` | `string` | Template alias to check | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`boolean`\> + +True if the alias exists, false otherwise + +###### Deprecated + +Use `exists` instead. + +###### Example + +```ts +const exists = await Template.aliasExists('my-python-env') +if (exists) { + console.log('Template exists!') +} +``` + +### assignTags() + +```ts +static assignTags( + targetName: string, + tags: string | string[], +options?: ConnectionOpts): Promise +``` + +Assign tag(s) to an existing template build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `targetName` | `string` | Template name in 'name:tag' format (the source build to tag from) | +| `tags` | `string` \| `string`[] | Tag or tags to assign | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`TemplateTagInfo`\> + +Tag info with buildId and assigned tags + +###### Example + +```ts +// Assign a single tag +await Template.assignTags('my-template:v1.0', 'production') + +// Assign multiple tags +await Template.assignTags('my-template:v1.0', ['production', 'stable']) +``` + +### build() + +###### Call Signature + +```ts +static build( + template: TemplateClass, + name: string, +options?: Omit): Promise +``` + +Build and deploy a template to E2B infrastructure. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `name` | `string` | Template name in 'name' or 'name:tag' format | +| `options`? | `Omit`\<`BuildOptions`, `"alias"`\> | Optional build configuration options | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Example + +```ts +const template = Template().fromPythonImage('3') + +// Build with single tag in name +await Template.build(template, 'my-python-env:v1.0') + +// Build with multiple tags +await Template.build(template, 'my-python-env', { tags: ['v1.0', 'stable'] }) +``` + +###### Call Signature + +```ts +static build(template: TemplateClass, options: BuildOptions): Promise +``` + +Build and deploy a template to E2B infrastructure. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `options` | `BuildOptions` | Build configuration options with alias (deprecated) | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Deprecated + +Use the overload with `name` parameter instead. + +###### Example + +```ts +// Deprecated: +await Template.build(template, { alias: 'my-python-env' }) + +// Use instead: +await Template.build(template, 'my-python-env:v1.0') +``` + +### buildInBackground() + +###### Call Signature + +```ts +static buildInBackground( + template: TemplateClass, + name: string, +options?: Omit): Promise +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `name` | `string` | Template name in 'name' or 'name:tag' format | +| `options`? | `Omit`\<`BuildOptions`, `"alias"`\> | Optional build configuration options | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Example + +```ts +const template = Template().fromPythonImage('3') + +// Build with single tag in name +const data = await Template.buildInBackground(template, 'my-python-env:v1.0') + +// Build with multiple tags +const data = await Template.buildInBackground(template, 'my-python-env', { tags: ['v1.0', 'stable'] }) +``` + +###### Call Signature + +```ts +static buildInBackground(template: TemplateClass, options: BuildOptions): Promise +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `options` | `BuildOptions` | Build configuration options with alias (deprecated) | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Deprecated + +Use the overload with `name` parameter instead. + +###### Example + +```ts +// Deprecated: +await Template.buildInBackground(template, { alias: 'my-python-env' }) + +// Use instead: +await Template.buildInBackground(template, 'my-python-env:v1.0') +``` + +### exists() + +```ts +static exists(name: string, options?: ConnectionOpts): Promise +``` + +Check if a template with the given name exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Template name to check | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`boolean`\> + +True if the name exists, false otherwise + +###### Example + +```ts +const exists = await Template.exists('my-python-env') +if (exists) { + console.log('Template exists!') +} +``` + +### getBuildStatus() + +```ts +static getBuildStatus(data: Pick, options?: GetBuildStatusOptions): Promise +``` + +Get the status of a build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `data` | `Pick`\<`BuildInfo`, `"buildId"` \| `"templateId"`\> | Build identifiers | +| `options`? | `GetBuildStatusOptions` | Authentication options | + +###### Returns + +`Promise`\<`TemplateBuildStatusResponse`\> + +###### Example + +```ts +const status = await Template.getBuildStatus(data, { logsOffset: 0 }) +``` + +### getTags() + +```ts +static getTags(templateId: string, options?: ConnectionOpts): Promise +``` + +Get all tags for a template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `templateId` | `string` | Template ID or name | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`TemplateTag`[]\> + +Array of tag details including tag name, buildId, and creation date + +###### Example + +```ts +const tags = await Template.getTags('my-template') +for (const tag of tags) { + console.log(`Tag: ${tag.tag}, Build: ${tag.buildId}, Created: ${tag.createdAt}`) +} +``` + +### removeTags() + +```ts +static removeTags( + name: string, + tags: string | string[], +options?: ConnectionOpts): Promise +``` + +Remove tag(s) from a template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Template name | +| `tags` | `string` \| `string`[] | Tag or tags to remove | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`void`\> + +###### Example + +```ts +// Remove a single tag +await Template.removeTags('my-template', 'production') + +// Remove multiple tags from a template +await Template.removeTags('my-template', ['production', 'staging']) +``` + +### toDockerfile() + +```ts +static toDockerfile(template: TemplateClass): string +``` + +Convert a template to Dockerfile format. +Note: Templates based on other E2B templates cannot be converted to Dockerfile. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to convert | + +###### Returns + +`string` + +Dockerfile string representation + +###### Throws + +Error if the template is based on another E2B template + +### toJSON() + +```ts +static toJSON(template: TemplateClass, computeHashes: boolean): Promise +``` + +Convert a template to JSON representation. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `template` | `TemplateClass` | `undefined` | The template to convert | +| `computeHashes` | `boolean` | `true` | Whether to compute file hashes for cache invalidation | + +###### Returns + +`Promise`\<`string`\> + +JSON string representation of the template + +## Interfaces + +### TemplateBuilder + +Main builder state for constructing templates. +Provides methods for customizing the template environment. + +#### Methods + +### addMcpServer() + +```ts +addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder +``` + +Install MCP servers using mcp-gateway. +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | + +###### Returns + +`TemplateBuilder` + +###### Throws + +If the base template is not mcp-gateway + +###### Example + +```ts +template.addMcpServer('exa') +template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) +``` + +### aptInstall() + +```ts +aptInstall(packages: string | string[], options?: object): TemplateBuilder +``` + +Install Debian/Ubuntu packages using apt-get. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages` | `string` \| `string`[] | Package name(s) | +| `options`? | \{ `fixMissing`: `boolean`; `noInstallRecommends`: `boolean`; \} | - | +| `options.fixMissing`? | `boolean` | - | +| `options.noInstallRecommends`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.aptInstall('vim') +template.aptInstall(['git', 'curl', 'wget']) +template.aptInstall(['vim'], { noInstallRecommends: true }) +template.aptInstall(['vim'], { fixMissing: true }) +``` + +### betaDevContainerPrebuild() + +```ts +betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder +``` + +Prebuild a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') +``` + +### betaSetDevContainerStart() + +```ts +betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal +``` + +Start a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .startDevcontainer('/my-devcontainer') + +// Prebuild and start +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') + // Other instructions... + .betaSetDevContainerStart('/my-devcontainer') +``` + +### bunInstall() + +```ts +bunInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Bun packages using bun. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | \{ `dev`: `boolean`; `g`: `boolean`; \} | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.bunInstall('express') +template.bunInstall(['lodash', 'axios']) +template.bunInstall('tsx', { g: true }) +template.bunInstall('typescript', { dev: true }) +template.bunInstall() // Installs from package.json +``` + +### copy() + +```ts +copy( + src: PathLike | PathLike[], + dest: PathLike, + options?: object): TemplateBuilder +``` + +Copy files or directories into the template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` \| `PathLike`[] | Source path(s) | +| `dest` | `PathLike` | Destination path | +| `options`? | \{ `forceUpload`: `true`; `mode`: `number`; `resolveSymlinks`: `boolean`; `user`: `string`; \} | Copy options | +| `options.forceUpload`? | `true` | - | +| `options.mode`? | `number` | - | +| `options.resolveSymlinks`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copy('requirements.txt', '/home/user/') +template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) +``` + +### copyItems() + +```ts +copyItems(items: CopyItem[]): TemplateBuilder +``` + +Copy multiple items with individual options. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `items` | `CopyItem`[] | Array of copy items | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copyItems([ + { src: 'app.ts', dest: '/app/' }, + { src: 'config.ts', dest: '/app/', mode: 0o644 } +]) +``` + +### gitClone() + +```ts +gitClone( + url: string, + path?: PathLike, + options?: object): TemplateBuilder +``` + +Clone a Git repository. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | Repository URL | +| `path`? | `PathLike` | Optional destination path | +| `options`? | \{ `branch`: `string`; `depth`: `number`; `user`: `string`; \} | Clone options | +| `options.branch`? | `string` | - | +| `options.depth`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.gitClone('https://github.com/user/repo.git', '/app/repo') +template.gitClone('https://github.com/user/repo.git', undefined, { + branch: 'main', + depth: 1 +}) +template.gitClone('https://github.com/user/repo.git', '/app/repo', { + user: 'root' +}) +``` + +### makeDir() + +```ts +makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Create directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | +| `options`? | \{ `mode`: `number`; `user`: `string`; \} | Directory options | +| `options.mode`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeDir('/app/data', { mode: 0o755 }) +template.makeDir(['/app/logs', '/app/cache']) +template.makeDir('/app/data', { mode: 0o755, user: 'root' }) +``` + +### makeSymlink() + +```ts +makeSymlink( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Create a symbolic link. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path (target) | +| `dest` | `PathLike` | Destination path (symlink location) | +| `options`? | \{ `force`: `boolean`; `user`: `string`; \} | Symlink options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeSymlink('/usr/bin/python3', '/usr/bin/python') +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) +``` + +### npmInstall() + +```ts +npmInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Node.js packages using npm. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | \{ `dev`: `boolean`; `g`: `boolean`; \} | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.npmInstall('express') +template.npmInstall(['lodash', 'axios']) +template.npmInstall('tsx', { g: true }) +template.npmInstall('typescript', { dev: true }) +template.npmInstall() // Installs from package.json +``` + +### pipInstall() + +```ts +pipInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Python packages using pip. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | +| `options`? | \{ `g`: `boolean`; \} | Install options | +| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.pipInstall('numpy') // Installs globally (default) +template.pipInstall(['pandas', 'scikit-learn']) +template.pipInstall('numpy', { g: false }) // Install for user only +template.pipInstall() // Installs from current directory +``` + +### remove() + +```ts +remove(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Remove files or directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | +| `options`? | \{ `force`: `boolean`; `recursive`: `boolean`; `user`: `string`; \} | Remove options | +| `options.force`? | `boolean` | - | +| `options.recursive`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.remove('/tmp/cache', { recursive: true, force: true }) +template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) +``` + +### rename() + +```ts +rename( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Rename or move a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path | +| `dest` | `PathLike` | Destination path | +| `options`? | \{ `force`: `boolean`; `user`: `string`; \} | Rename options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) +``` + +### runCmd() + +###### Call Signature + +```ts +runCmd(command: string, options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `command` | `string` | Command string | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### Call Signature + +```ts +runCmd(commands: string[], options?: object): TemplateBuilder +``` + +Run multiple shell commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commands` | `string`[] | Array of command strings | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Call Signature + +```ts +runCmd(commandOrCommands: string | string[], options?: object): TemplateBuilder +``` + +Run command(s). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commandOrCommands` | `string` \| `string`[] | Command or commands | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +### setEnvs() + +```ts +setEnvs(envs: Record): TemplateBuilder +``` + +Set environment variables. +Note: Environment variables defined here are available only during template build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `envs` | `Record`\<`string`, `string`\> | Environment variables | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) +``` + +### setReadyCmd() + +```ts +setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set or update the ready check command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setReadyCmd('curl http://localhost:8000/health') + +// Using ReadyCmd helpers +import { waitForPort, waitForFile, waitForProcess } from 'e2b' + +template.setReadyCmd(waitForPort(3000)) + +template.setReadyCmd(waitForFile('/tmp/ready')) + +template.setReadyCmd(waitForProcess('nginx')) +``` + +### setStartCmd() + +```ts +setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set the start command and ready check. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `startCommand` | `string` | Command to run on startup | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setStartCmd( + 'node app.js', + 'curl http://localhost:8000/health' +) + +// Using ReadyCmd helpers +import { waitForPort, waitForURL } from 'e2b' + +template.setStartCmd( + 'python -m http.server 8000', + waitForPort(8000) +) + +template.setStartCmd( + 'npm start', + waitForURL('http://localhost:3000/health', 200) +) +``` + +### setUser() + +```ts +setUser(user: string): TemplateBuilder +``` + +Set the user for subsequent commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `user` | `string` | Username | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setUser('root') +``` + +### setWorkdir() + +```ts +setWorkdir(workdir: PathLike): TemplateBuilder +``` + +Set the working directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `workdir` | `PathLike` | Working directory path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setWorkdir('/app') +``` + +### skipCache() + +```ts +skipCache(): this +``` + +Skip cache for all subsequent build instructions from this point. + +###### Returns + +`this` + +###### Example + +```ts +template.skipCache().runCmd('apt-get update') +``` + +## Type Aliases + +### BuildInfo + +```ts +type BuildInfo = object; +``` + +Information about a built template. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `alias` | `string` | First alias from the build (for backward compatibility). **Deprecated** Use `name` instead. | +| `buildId` | `string` | Build identifier. | +| `name` | `string` | Name of the template. | +| `tags` | `string`[] | Tags assigned to this build. | +| `templateId` | `string` | Template identifier. | + +*** + +### BuildOptions + +```ts +type BuildOptions = ConnectionOpts & BasicBuildOptions; +``` + +Options for building a template with authentication. + +*** + +### BuildStatusReason + +```ts +type BuildStatusReason = object; +``` + +Reason for the current build status (typically for errors). + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `logEntries` | `LogEntry`[] | Log entries related to the status reason. | +| `message` | `string` | Message with the status reason. | +| `step`? | `string` | Step that failed. | + +*** + +### CopyItem + +```ts +type CopyItem = object; +``` + +Configuration for a single file/directory copy operation. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `dest` | `PathLike` | +| `forceUpload`? | `true` | +| `mode`? | `number` | +| `resolveSymlinks`? | `boolean` | +| `src` | `PathLike` \| `PathLike`[] | +| `user`? | `string` | + +*** + +### GetBuildStatusOptions + +```ts +type GetBuildStatusOptions = ConnectionOpts & object; +``` + +Options for getting build status. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `logsOffset`? | `number` | + +*** + +### McpServerName + +```ts +type McpServerName = keyof McpServer; +``` + +MCP server names that can be installed. + +*** + +### TemplateBuildStatus + +```ts +type TemplateBuildStatus = "building" | "waiting" | "ready" | "error"; +``` + +Status of a template build. + +*** + +### TemplateBuildStatusResponse + +```ts +type TemplateBuildStatusResponse = object; +``` + +Response from getting build status. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `buildID` | `string` | Build identifier. | +| `logEntries` | `LogEntry`[] | Build log entries. | +| `logs` | `string`[] | Build logs (raw strings). **Deprecated** Use `logEntries` instead. | +| `reason`? | `BuildStatusReason` | Reason for the current status (typically for errors). | +| `status` | `TemplateBuildStatus` | Current status of the build. | +| `templateID` | `string` | Template identifier. | + +*** + +### TemplateClass + +```ts +type TemplateClass = TemplateBuilder | TemplateFinal; +``` + +Type representing a template in any state (builder or final). + +*** + +### TemplateTag + +```ts +type TemplateTag = object; +``` + +Detailed information about a single template tag. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `buildId` | `string` | Build identifier associated with this tag. | +| `createdAt` | `Date` | When this tag was assigned. | +| `tag` | `string` | Name of the tag. | + +*** + +### TemplateTagInfo + +```ts +type TemplateTagInfo = object; +``` + +Information about assigned template tags. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `buildId` | `string` | Build identifier associated with this tag. | +| `tags` | `string`[] | Assigned tags of the template. | + +## Functions + +### Template() + +```ts +function Template(options?: TemplateOptions): TemplateFromImage +``` + +Create a new E2B template builder instance. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options`? | `TemplateOptions` | Optional configuration for the template builder | + +#### Returns + +`TemplateFromImage` + +A new template builder instance + +#### Example + +```ts +import { Template } from 'e2b' + +const template = Template() + .fromPythonImage('3') + .copy('requirements.txt', '/app/') + .pipInstall() + +await Template.build(template, 'my-python-app:v1.0') +``` diff --git a/docs/sdk-reference/js-sdk/v2.17.0/errors.mdx b/docs/sdk-reference/js-sdk/v2.17.0/errors.mdx new file mode 100644 index 00000000..aeef2098 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.17.0/errors.mdx @@ -0,0 +1,381 @@ +--- +sidebarTitle: "Errors" +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Extended by + +- `GitAuthError` + +#### Constructors + +```ts +new AuthenticationError(message: string): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`AuthenticationError` + +``` + +*** + +### BuildError + +Thrown when the build fails. + +#### Extended by + +- `FileUploadError` + +#### Constructors + +```ts +new BuildError(message: string, stackTrace?: string): BuildError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`BuildError` + +``` + +*** + +### FileNotFoundError + +Thrown when a file or directory is not found inside a sandbox. + +#### Constructors + +```ts +new FileNotFoundError(message: string, stackTrace?: string): FileNotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`FileNotFoundError` + +*** + +### FileUploadError + +Thrown when the file upload fails. + +#### Constructors + +```ts +new FileUploadError(message: string, stackTrace?: string): FileUploadError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`FileUploadError` + +*** + +### GitAuthError + +Thrown when git authentication fails. + +#### Constructors + +```ts +new GitAuthError(message: string): GitAuthError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`GitAuthError` + +*** + +### GitUpstreamError + +Thrown when git upstream tracking is missing. + +#### Constructors + +```ts +new GitUpstreamError(message: string, stackTrace?: string): GitUpstreamError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`GitUpstreamError` + +*** + +### 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. + +#### Deprecated + +Use FileNotFoundError or SandboxNotFoundError instead. This class will be removed in the next major version. + +#### Extended by + +- `FileNotFoundError` +- `SandboxNotFoundError` + +#### 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` +- `GitUpstreamError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message?: string, stackTrace?: string): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message`? | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`SandboxError` + +``` + +*** + +### SandboxNotFoundError + +Thrown when a sandbox is not found (e.g. it doesn't exist or is no longer running). + +#### Constructors + +```ts +new SandboxNotFoundError(message: string, stackTrace?: string): SandboxNotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`SandboxNotFoundError` + +*** + +### 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/docs/sdk-reference/js-sdk/v2.17.0/sandbox-commands.mdx b/docs/sdk-reference/js-sdk/v2.17.0/sandbox-commands.mdx new file mode 100644 index 00000000..c97c6b9b --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.17.0/sandbox-commands.mdx @@ -0,0 +1,555 @@ +--- +sidebarTitle: "Commands" +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands( + transport: Transport, + connectionConfig: ConnectionConfig, + metadata: object): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | +| `metadata` | \{ `version`: `string`; \} | +| `metadata.version` | `string` | + +###### 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() + +###### Call Signature + +```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. + +###### Call Signature + +```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. + +###### Call Signature + +```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 | Uint8Array, +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` \| `Uint8Array`\<`ArrayBufferLike`\> | 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, + metadata: object): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | +| `metadata` | \{ `version`: `string`; \} | +| `metadata.version` | `string` | + +###### Returns + +`Pty` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: PtyConnectOpts): Promise +``` + +Connect to a running PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY to connect to. You can get the list of running PTYs using Commands.list. | +| `opts`? | `PtyConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### 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` | \{ `cols`: `number`; `rows`: `number`; \} | 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 +``` + +### stdin? + +```ts +optional stdin: boolean; +``` + +If true, command stdin is kept open and you can send data to it using Commands.sendStdin or CommandHandle.sendStdin. + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to run the command as. + +###### Default + +`default Sandbox user (as specified in the template)` + +*** + +### 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/docs/sdk-reference/js-sdk/v2.17.0/sandbox-filesystem.mdx b/docs/sdk-reference/js-sdk/v2.17.0/sandbox-filesystem.mdx new file mode 100644 index 00000000..aed576f6 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.17.0/sandbox-filesystem.mdx @@ -0,0 +1,665 @@ +--- +sidebarTitle: "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() + +###### Call Signature + +```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 + +###### Call Signature + +```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`\<`ArrayBufferLike`\>\> + +file content as `Uint8Array` + +###### Call Signature + +```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` + +###### Call Signature + +```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`\<`ArrayBufferLike`\>\>\> + +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() + +###### Call Signature + +```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 + +###### Call Signature + +```ts +write(files: WriteEntry[], 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 | +| ------ | ------ | ------ | +| `files` | `WriteEntry`[] | - | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +information about the written file + +### writeFiles() + +```ts +writeFiles(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +Write multiple files. + +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 | +| ------ | ------ | ------ | +| `files` | `WriteEntry`[] | list of files to write as `WriteEntry` objects, each containing `path` and `data`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +information about the written files + +## 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: string; +``` + +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: string; +``` + +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: string; +``` + +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/docs/sdk-reference/js-sdk/v2.17.0/sandbox.mdx b/docs/sdk-reference/js-sdk/v2.17.0/sandbox.mdx new file mode 100644 index 00000000..023ea3ed --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.17.0/sandbox.mdx @@ -0,0 +1,938 @@ +--- +sidebarTitle: "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 git operations +- 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 | +| `git` | `readonly` | `Git` | Module for running git operations in the sandbox | +| `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. | +| `trafficAccessToken?` | `readonly` | `string` | Traffic access token for accessing sandbox services with restricted public traffic. | + +#### Methods + +### ~~betaPause()~~ + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `ConnectionOpts` | + +###### Returns + +`Promise`\<`boolean`\> + +###### Deprecated + +Use Sandbox.pause instead. + +### connect() + +```ts +connect(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). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxConnectOpts` | 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() +``` + +### createSnapshot() + +```ts +createSnapshot(opts?: SandboxApiOpts): Promise +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshotId` with `Sandbox.create(snapshotId)` to create a new sandbox from the snapshot. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SnapshotInfo`\> + +snapshot information including the snapshot ID. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.files.write('/app/state.json', '{"step": 1}') + +// Create a snapshot +const snapshot = await sandbox.createSnapshot() + +// Create a new sandbox from the snapshot +const newSandbox = await Sandbox.create(snapshot.snapshotId) +``` + +### 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 + +### getMcpToken() + +```ts +getMcpToken(): Promise +``` + +Get the MCP token for the sandbox. + +###### Returns + +`Promise`\<`undefined` \| `string`\> + +MCP token for the sandbox, or undefined if MCP is not enabled. + +### getMcpUrl() + +```ts +getMcpUrl(): string +``` + +Get the MCP URL for the sandbox. + +###### Returns + +`string` + +MCP URL for 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`\> + +### listSnapshots() + +```ts +listSnapshots(opts?: Omit): SnapshotPaginator +``` + +List all snapshots created from this sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Omit`\<`SnapshotListOpts`, `"sandboxId"`\> | list options. | + +###### Returns + +`SnapshotPaginator` + +paginator for listing snapshots from this sandbox. + +### pause() + +```ts +pause(opts?: ConnectionOpts): Promise +``` + +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. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.pause() +``` + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. + +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() + +###### Call Signature + +```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 + +###### Call Signature + +```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 +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`boolean`\> + +###### Deprecated + +Use SandboxApi.pause instead. + +``` + +### 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() + +###### Call Signature + +```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 + +###### 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 + +### createSnapshot() + +```ts +static createSnapshot(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Create a snapshot from a sandbox. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same state. +The snapshot is a persistent image that survives sandbox deletion. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID to create snapshot from. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SnapshotInfo`\> + +snapshot information including the snapshot name that can be used with Sandbox.create(). + +``` + +### deleteSnapshot() + +```ts +static deleteSnapshot(snapshotId: string, opts?: SandboxApiOpts): Promise +``` + +Delete a snapshot. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `snapshotId` | `string` | snapshot ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the snapshot was deleted, `false` if it was not found. + +``` + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise<{ + allowInternetAccess: undefined | boolean; + cpuCount: number; + endAt: Date; + envdAccessToken: undefined | string; + envdVersion: string; + lifecycle: | undefined + | { + autoResume: boolean; + onTimeout: "kill" | "pause"; + }; + memoryMB: number; + metadata: {}; + name: string; + network: | undefined + | { + allowOut: undefined | string[]; + allowPublicTraffic: undefined | boolean; + denyOut: undefined | string[]; + maskRequestHost: undefined | string; + }; + sandboxDomain: undefined | string; + sandboxId: string; + startedAt: Date; + state: "running" | "paused"; + templateId: string; +}> +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<\{ + `allowInternetAccess`: `undefined` \| `boolean`; + `cpuCount`: `number`; + `endAt`: `Date`; + `envdAccessToken`: `undefined` \| `string`; + `envdVersion`: `string`; + `lifecycle`: \| `undefined` + \| \{ + `autoResume`: `boolean`; + `onTimeout`: `"kill"` \| `"pause"`; + \}; + `memoryMB`: `number`; + `metadata`: \{\}; + `name`: `string`; + `network`: \| `undefined` + \| \{ + `allowOut`: `undefined` \| `string`[]; + `allowPublicTraffic`: `undefined` \| `boolean`; + `denyOut`: `undefined` \| `string`[]; + `maskRequestHost`: `undefined` \| `string`; + \}; + `sandboxDomain`: `undefined` \| `string`; + `sandboxId`: `string`; + `startedAt`: `Date`; + `state`: `"running"` \| `"paused"`; + `templateId`: `string`; + \}\> + +``` + +### 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. + +### listSnapshots() + +```ts +static listSnapshots(opts?: SnapshotListOpts): SnapshotPaginator +``` + +List all snapshots. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SnapshotListOpts` | list options including filters and pagination. | + +###### Returns + +`SnapshotPaginator` + +paginator for listing snapshots. + +``` + +### pause() + +```ts +static pause(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. + +``` + +### 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: string; +``` + +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/docs/sdk-reference/js-sdk/v2.17.0/template-logger.mdx b/docs/sdk-reference/js-sdk/v2.17.0/template-logger.mdx new file mode 100644 index 00000000..bb4b9315 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.17.0/template-logger.mdx @@ -0,0 +1,195 @@ +--- +sidebarTitle: "Logger" +--- + +### LogEntry + +Represents a single log entry from the template build process. + +#### Extended by + +- `LogEntryStart` +- `LogEntryEnd` + +#### Constructors + +```ts +new LogEntry( + timestamp: Date, + level: LogEntryLevel, + message: string): LogEntry +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `level` | `LogEntryLevel` | +| `message` | `string` | + +###### Returns + +`LogEntry` + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | +| `message` | `readonly` | `string` | +| `timestamp` | `readonly` | `Date` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### LogEntryEnd + +Special log entry indicating the end of a build process. + +#### Constructors + +```ts +new LogEntryEnd(timestamp: Date, message: string): LogEntryEnd +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `message` | `string` | + +###### Returns + +`LogEntryEnd` + +#### Properties + +| Property | Modifier | Type | Inherited from | +| ------ | ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | +| `message` | `readonly` | `string` | `LogEntry`.`message` | +| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### LogEntryStart + +Special log entry indicating the start of a build process. + +#### Constructors + +```ts +new LogEntryStart(timestamp: Date, message: string): LogEntryStart +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `message` | `string` | + +###### Returns + +`LogEntryStart` + +#### Properties + +| Property | Modifier | Type | Inherited from | +| ------ | ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | +| `message` | `readonly` | `string` | `LogEntry`.`message` | +| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +## Type Aliases + +### LogEntryLevel + +```ts +type LogEntryLevel = "debug" | "info" | "warn" | "error"; +``` + +Log entry severity levels. + +## Functions + +### defaultBuildLogger() + +```ts +function defaultBuildLogger(options?: object): (logEntry: LogEntry) => void +``` + +Create a default build logger with animated timer display. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options`? | \{ `minLevel`: `LogEntryLevel`; \} | Logger configuration options | +| `options.minLevel`? | `LogEntryLevel` | Minimum log level to display (default: 'info') | + +#### Returns + +`Function` + +Logger function that accepts LogEntry instances + +### Parameters + +| Parameter | Type | +| ------ | ------ | +| `logEntry` | `LogEntry` | + +### Returns + +`void` + +#### Example + +```ts +import { Template, defaultBuildLogger } from 'e2b' + +const template = Template().fromPythonImage() + +await Template.build(template, { + alias: 'my-template', + onBuildLogs: defaultBuildLogger({ minLevel: 'debug' }) +}) +``` diff --git a/docs/sdk-reference/js-sdk/v2.17.0/template-readycmd.mdx b/docs/sdk-reference/js-sdk/v2.17.0/template-readycmd.mdx new file mode 100644 index 00000000..a35a37aa --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.17.0/template-readycmd.mdx @@ -0,0 +1,201 @@ +--- +sidebarTitle: "Readycmd" +--- + +### ReadyCmd + +Class for ready check commands. + +#### Constructors + +```ts +new ReadyCmd(cmd: string): ReadyCmd +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `cmd` | `string` | + +###### Returns + +`ReadyCmd` + +#### Methods + +### getCmd() + +```ts +getCmd(): string +``` + +###### Returns + +`string` + +## Functions + +### waitForFile() + +```ts +function waitForFile(filename: string): ReadyCmd +``` + +Wait for a file to exist. +Uses shell test command to check file existence. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filename` | `string` | Path to the file to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the file + +#### Example + +```ts +import { Template, waitForFile } from 'e2b' + +const template = Template() + .fromBaseImage() + .setStartCmd('./init.sh', waitForFile('/tmp/ready')) +``` + +*** + +### waitForPort() + +```ts +function waitForPort(port: number): ReadyCmd +``` + +Wait for a port to be listening. +Uses `ss` command to check if a port is open and listening. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | Port number to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the port + +#### Example + +```ts +import { Template, waitForPort } from 'e2b' + +const template = Template() + .fromPythonImage() + .setStartCmd('python -m http.server 8000', waitForPort(8000)) +``` + +*** + +### waitForProcess() + +```ts +function waitForProcess(processName: string): ReadyCmd +``` + +Wait for a process with a specific name to be running. +Uses `pgrep` to check if a process exists. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `processName` | `string` | Name of the process to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the process + +#### Example + +```ts +import { Template, waitForProcess } from 'e2b' + +const template = Template() + .fromBaseImage() + .setStartCmd('./my-daemon', waitForProcess('my-daemon')) +``` + +*** + +### waitForTimeout() + +```ts +function waitForTimeout(timeout: number): ReadyCmd +``` + +Wait for a specified timeout before considering the sandbox ready. +Uses `sleep` command to wait for a fixed duration. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeout` | `number` | Time to wait in milliseconds (minimum: 1000ms / 1 second) | + +#### Returns + +`ReadyCmd` + +ReadyCmd that waits for the specified duration + +#### Example + +```ts +import { Template, waitForTimeout } from 'e2b' + +const template = Template() + .fromNodeImage() + .setStartCmd('npm start', waitForTimeout(5000)) // Wait 5 seconds +``` + +*** + +### waitForURL() + +```ts +function waitForURL(url: string, statusCode: number): ReadyCmd +``` + +Wait for a URL to return a specific HTTP status code. +Uses `curl` to make HTTP requests and check the response status. + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `url` | `string` | `undefined` | URL to check (e.g., 'http://localhost:3000/health') | +| `statusCode` | `number` | `200` | Expected HTTP status code (default: 200) | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks the URL + +#### Example + +```ts +import { Template, waitForURL } from 'e2b' + +const template = Template() + .fromNodeImage() + .setStartCmd('npm start', waitForURL('http://localhost:3000/health')) +``` diff --git a/docs/sdk-reference/js-sdk/v2.17.0/template.mdx b/docs/sdk-reference/js-sdk/v2.17.0/template.mdx new file mode 100644 index 00000000..c0fbcf34 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.17.0/template.mdx @@ -0,0 +1,2377 @@ +--- +sidebarTitle: "Template" +--- + +### TemplateBase + +Base class for building E2B sandbox templates. + +#### Implements + +- `TemplateFromImage` +- `TemplateBuilder` +- `TemplateFinal` + +#### Constructors + +```ts +new TemplateBase(options?: TemplateOptions): TemplateBase +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `options`? | `TemplateOptions` | + +###### Returns + +`TemplateBase` + +#### Methods + +### addMcpServer() + +```ts +addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder +``` + +Install MCP servers using mcp-gateway. +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | + +###### Returns + +`TemplateBuilder` + +###### Throws + +If the base template is not mcp-gateway + +###### Example + +```ts +template.addMcpServer('exa') +template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) +``` + +###### Implementation of + +`TemplateBuilder`.`addMcpServer` + +### aptInstall() + +```ts +aptInstall(packages: string | string[], options?: object): TemplateBuilder +``` + +Install Debian/Ubuntu packages using apt-get. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages` | `string` \| `string`[] | Package name(s) | +| `options`? | \{ `fixMissing`: `boolean`; `noInstallRecommends`: `boolean`; \} | - | +| `options.fixMissing`? | `boolean` | - | +| `options.noInstallRecommends`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.aptInstall('vim') +template.aptInstall(['git', 'curl', 'wget']) +template.aptInstall(['vim'], { noInstallRecommends: true }) +template.aptInstall(['vim'], { fixMissing: true }) +``` + +###### Implementation of + +`TemplateBuilder`.`aptInstall` + +### betaDevContainerPrebuild() + +```ts +betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder +``` + +Prebuild a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') +``` + +###### Implementation of + +`TemplateBuilder`.`betaDevContainerPrebuild` + +### betaSetDevContainerStart() + +```ts +betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal +``` + +Start a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .startDevcontainer('/my-devcontainer') + +// Prebuild and start +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') + // Other instructions... + .betaSetDevContainerStart('/my-devcontainer') +``` + +###### Implementation of + +`TemplateBuilder`.`betaSetDevContainerStart` + +### bunInstall() + +```ts +bunInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Bun packages using bun. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | \{ `dev`: `boolean`; `g`: `boolean`; \} | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.bunInstall('express') +template.bunInstall(['lodash', 'axios']) +template.bunInstall('tsx', { g: true }) +template.bunInstall('typescript', { dev: true }) +template.bunInstall() // Installs from package.json +``` + +###### Implementation of + +`TemplateBuilder`.`bunInstall` + +### copy() + +```ts +copy( + src: PathLike | PathLike[], + dest: PathLike, + options?: object): TemplateBuilder +``` + +Copy files or directories into the template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` \| `PathLike`[] | Source path(s) | +| `dest` | `PathLike` | Destination path | +| `options`? | \{ `forceUpload`: `true`; `mode`: `number`; `resolveSymlinks`: `boolean`; `user`: `string`; \} | Copy options | +| `options.forceUpload`? | `true` | - | +| `options.mode`? | `number` | - | +| `options.resolveSymlinks`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copy('requirements.txt', '/home/user/') +template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) +``` + +###### Implementation of + +`TemplateBuilder`.`copy` + +### copyItems() + +```ts +copyItems(items: CopyItem[]): TemplateBuilder +``` + +Copy multiple items with individual options. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `items` | `CopyItem`[] | Array of copy items | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copyItems([ + { src: 'app.ts', dest: '/app/' }, + { src: 'config.ts', dest: '/app/', mode: 0o644 } +]) +``` + +###### Implementation of + +`TemplateBuilder`.`copyItems` + +### fromAWSRegistry() + +```ts +fromAWSRegistry(image: string, credentials: object): TemplateBuilder +``` + +Start from a Docker image in AWS ECR. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `image` | `string` | Full ECR image path | +| `credentials` | \{ `accessKeyId`: `string`; `region`: `string`; `secretAccessKey`: `string`; \} | AWS credentials | +| `credentials.accessKeyId` | `string` | - | +| `credentials.region` | `string` | - | +| `credentials.secretAccessKey` | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromAWSRegistry( + '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', + { + accessKeyId: 'AKIA...', + secretAccessKey: '...', + region: 'us-west-2' + } +) +``` + +###### Implementation of + +```ts +TemplateFromImage.fromAWSRegistry +``` + +### fromBaseImage() + +```ts +fromBaseImage(): TemplateBuilder +``` + +Start from E2B's default base image (e2bdev/base:latest). + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromBaseImage() +``` + +###### Implementation of + +```ts +TemplateFromImage.fromBaseImage +``` + +### fromBunImage() + +```ts +fromBunImage(variant: string): TemplateBuilder +``` + +Start from a Bun-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'latest'` | Bun variant (default: 'latest') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromBunImage('1.3') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromBunImage +``` + +### fromDebianImage() + +```ts +fromDebianImage(variant: string): TemplateBuilder +``` + +Start from a Debian-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'stable'` | Debian variant (default: 'stable') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromDebianImage('bookworm') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromDebianImage +``` + +### fromDockerfile() + +```ts +fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder +``` + +Parse a Dockerfile and convert it to Template SDK format. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `dockerfileContentOrPath` | `string` | Dockerfile content or path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromDockerfile('Dockerfile') +Template().fromDockerfile('FROM python:3\nRUN pip install numpy') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromDockerfile +``` + +### fromGCPRegistry() + +```ts +fromGCPRegistry(image: string, credentials: object): TemplateBuilder +``` + +Start from a Docker image in Google Container Registry. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `image` | `string` | Full GCR/GAR image path | +| `credentials` | \{ `serviceAccountJSON`: `string` \| `object`; \} | GCP service account credentials | +| `credentials.serviceAccountJSON` | `string` \| `object` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromGCPRegistry( + 'gcr.io/myproject/myimage:latest', + { serviceAccountJSON: 'path/to/service-account.json' } +) +``` + +###### Implementation of + +```ts +TemplateFromImage.fromGCPRegistry +``` + +### fromImage() + +```ts +fromImage(baseImage: string, credentials?: object): TemplateBuilder +``` + +Start from a custom Docker image. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `baseImage` | `string` | Docker image name | +| `credentials`? | \{ `password`: `string`; `username`: `string`; \} | Optional credentials for private registries | +| `credentials.password`? | `string` | - | +| `credentials.username`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromImage('python:3') + +// With credentials (optional) +Template().fromImage('myregistry.com/myimage:latest', { + username: 'user', + password: 'pass' +}) +``` + +###### Implementation of + +```ts +TemplateFromImage.fromImage +``` + +### fromNodeImage() + +```ts +fromNodeImage(variant: string): TemplateBuilder +``` + +Start from a Node.js-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'lts'` | Node.js variant (default: 'lts') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromNodeImage('24') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromNodeImage +``` + +### fromPythonImage() + +```ts +fromPythonImage(version: string): TemplateBuilder +``` + +Start from a Python-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `version` | `string` | `'3'` | Python version (default: '3') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromPythonImage('3') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromPythonImage +``` + +### fromTemplate() + +```ts +fromTemplate(template: string): TemplateBuilder +``` + +Start from an existing E2B template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `string` | E2B template ID or alias | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromTemplate('my-base-template') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromTemplate +``` + +### fromUbuntuImage() + +```ts +fromUbuntuImage(variant: string): TemplateBuilder +``` + +Start from an Ubuntu-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'latest'` | Ubuntu variant (default: 'latest') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromUbuntuImage('24.04') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromUbuntuImage +``` + +### gitClone() + +```ts +gitClone( + url: string, + path?: PathLike, + options?: object): TemplateBuilder +``` + +Clone a Git repository. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | Repository URL | +| `path`? | `PathLike` | Optional destination path | +| `options`? | \{ `branch`: `string`; `depth`: `number`; `user`: `string`; \} | Clone options | +| `options.branch`? | `string` | - | +| `options.depth`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.gitClone('https://github.com/user/repo.git', '/app/repo') +template.gitClone('https://github.com/user/repo.git', undefined, { + branch: 'main', + depth: 1 +}) +template.gitClone('https://github.com/user/repo.git', '/app/repo', { + user: 'root' +}) +``` + +###### Implementation of + +`TemplateBuilder`.`gitClone` + +### makeDir() + +```ts +makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Create directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | +| `options`? | \{ `mode`: `number`; `user`: `string`; \} | Directory options | +| `options.mode`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeDir('/app/data', { mode: 0o755 }) +template.makeDir(['/app/logs', '/app/cache']) +template.makeDir('/app/data', { mode: 0o755, user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`makeDir` + +### makeSymlink() + +```ts +makeSymlink( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Create a symbolic link. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path (target) | +| `dest` | `PathLike` | Destination path (symlink location) | +| `options`? | \{ `force`: `boolean`; `user`: `string`; \} | Symlink options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeSymlink('/usr/bin/python3', '/usr/bin/python') +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) +``` + +###### Implementation of + +`TemplateBuilder`.`makeSymlink` + +### npmInstall() + +```ts +npmInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Node.js packages using npm. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | \{ `dev`: `boolean`; `g`: `boolean`; \} | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.npmInstall('express') +template.npmInstall(['lodash', 'axios']) +template.npmInstall('tsx', { g: true }) +template.npmInstall('typescript', { dev: true }) +template.npmInstall() // Installs from package.json +``` + +###### Implementation of + +`TemplateBuilder`.`npmInstall` + +### pipInstall() + +```ts +pipInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Python packages using pip. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | +| `options`? | \{ `g`: `boolean`; \} | Install options | +| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.pipInstall('numpy') // Installs globally (default) +template.pipInstall(['pandas', 'scikit-learn']) +template.pipInstall('numpy', { g: false }) // Install for user only +template.pipInstall() // Installs from current directory +``` + +###### Implementation of + +`TemplateBuilder`.`pipInstall` + +### remove() + +```ts +remove(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Remove files or directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | +| `options`? | \{ `force`: `boolean`; `recursive`: `boolean`; `user`: `string`; \} | Remove options | +| `options.force`? | `boolean` | - | +| `options.recursive`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.remove('/tmp/cache', { recursive: true, force: true }) +template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`remove` + +### rename() + +```ts +rename( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Rename or move a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path | +| `dest` | `PathLike` | Destination path | +| `options`? | \{ `force`: `boolean`; `user`: `string`; \} | Rename options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`rename` + +### runCmd() + +###### Call Signature + +```ts +runCmd(command: string, options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `command` | `string` | Command string | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`runCmd` + +###### Call Signature + +```ts +runCmd(commands: string[], options?: object): TemplateBuilder +``` + +Run multiple shell commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commands` | `string`[] | Array of command strings | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Implementation of + +`TemplateBuilder`.`runCmd` + +### setEnvs() + +```ts +setEnvs(envs: Record): TemplateBuilder +``` + +Set environment variables. +Note: Environment variables defined here are available only during template build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `envs` | `Record`\<`string`, `string`\> | Environment variables | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) +``` + +###### Implementation of + +`TemplateBuilder`.`setEnvs` + +### setReadyCmd() + +```ts +setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set or update the ready check command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setReadyCmd('curl http://localhost:8000/health') + +// Using ReadyCmd helpers +import { waitForPort, waitForFile, waitForProcess } from 'e2b' + +template.setReadyCmd(waitForPort(3000)) + +template.setReadyCmd(waitForFile('/tmp/ready')) + +template.setReadyCmd(waitForProcess('nginx')) +``` + +###### Implementation of + +`TemplateBuilder`.`setReadyCmd` + +### setStartCmd() + +```ts +setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set the start command and ready check. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `startCommand` | `string` | Command to run on startup | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setStartCmd( + 'node app.js', + 'curl http://localhost:8000/health' +) + +// Using ReadyCmd helpers +import { waitForPort, waitForURL } from 'e2b' + +template.setStartCmd( + 'python -m http.server 8000', + waitForPort(8000) +) + +template.setStartCmd( + 'npm start', + waitForURL('http://localhost:3000/health', 200) +) +``` + +###### Implementation of + +`TemplateBuilder`.`setStartCmd` + +### setUser() + +```ts +setUser(user: string): TemplateBuilder +``` + +Set the user for subsequent commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `user` | `string` | Username | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setUser('root') +``` + +###### Implementation of + +`TemplateBuilder`.`setUser` + +### setWorkdir() + +```ts +setWorkdir(workdir: PathLike): TemplateBuilder +``` + +Set the working directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `workdir` | `PathLike` | Working directory path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setWorkdir('/app') +``` + +###### Implementation of + +`TemplateBuilder`.`setWorkdir` + +### skipCache() + +```ts +skipCache(): this +``` + +Skip cache for all subsequent build instructions from this point. + +###### Returns + +`this` + +###### Example + +```ts +Template().skipCache().fromPythonImage('3') +``` + +###### Implementation of + +`TemplateBuilder`.`skipCache` + +### ~~aliasExists()~~ + +```ts +static aliasExists(alias: string, options?: ConnectionOpts): Promise +``` + +Check if a template with the given alias exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `alias` | `string` | Template alias to check | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`boolean`\> + +True if the alias exists, false otherwise + +###### Deprecated + +Use `exists` instead. + +###### Example + +```ts +const exists = await Template.aliasExists('my-python-env') +if (exists) { + console.log('Template exists!') +} +``` + +### assignTags() + +```ts +static assignTags( + targetName: string, + tags: string | string[], +options?: ConnectionOpts): Promise +``` + +Assign tag(s) to an existing template build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `targetName` | `string` | Template name in 'name:tag' format (the source build to tag from) | +| `tags` | `string` \| `string`[] | Tag or tags to assign | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`TemplateTagInfo`\> + +Tag info with buildId and assigned tags + +###### Example + +```ts +// Assign a single tag +await Template.assignTags('my-template:v1.0', 'production') + +// Assign multiple tags +await Template.assignTags('my-template:v1.0', ['production', 'stable']) +``` + +### build() + +###### Call Signature + +```ts +static build( + template: TemplateClass, + name: string, +options?: Omit): Promise +``` + +Build and deploy a template to E2B infrastructure. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `name` | `string` | Template name in 'name' or 'name:tag' format | +| `options`? | `Omit`\<`BuildOptions`, `"alias"`\> | Optional build configuration options | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Example + +```ts +const template = Template().fromPythonImage('3') + +// Build with single tag in name +await Template.build(template, 'my-python-env:v1.0') + +// Build with multiple tags +await Template.build(template, 'my-python-env', { tags: ['v1.0', 'stable'] }) +``` + +###### Call Signature + +```ts +static build(template: TemplateClass, options: BuildOptions): Promise +``` + +Build and deploy a template to E2B infrastructure. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `options` | `BuildOptions` | Build configuration options with alias (deprecated) | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Deprecated + +Use the overload with `name` parameter instead. + +###### Example + +```ts +// Deprecated: +await Template.build(template, { alias: 'my-python-env' }) + +// Use instead: +await Template.build(template, 'my-python-env:v1.0') +``` + +### buildInBackground() + +###### Call Signature + +```ts +static buildInBackground( + template: TemplateClass, + name: string, +options?: Omit): Promise +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `name` | `string` | Template name in 'name' or 'name:tag' format | +| `options`? | `Omit`\<`BuildOptions`, `"alias"`\> | Optional build configuration options | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Example + +```ts +const template = Template().fromPythonImage('3') + +// Build with single tag in name +const data = await Template.buildInBackground(template, 'my-python-env:v1.0') + +// Build with multiple tags +const data = await Template.buildInBackground(template, 'my-python-env', { tags: ['v1.0', 'stable'] }) +``` + +###### Call Signature + +```ts +static buildInBackground(template: TemplateClass, options: BuildOptions): Promise +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `options` | `BuildOptions` | Build configuration options with alias (deprecated) | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Deprecated + +Use the overload with `name` parameter instead. + +###### Example + +```ts +// Deprecated: +await Template.buildInBackground(template, { alias: 'my-python-env' }) + +// Use instead: +await Template.buildInBackground(template, 'my-python-env:v1.0') +``` + +### exists() + +```ts +static exists(name: string, options?: ConnectionOpts): Promise +``` + +Check if a template with the given name exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Template name to check | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`boolean`\> + +True if the name exists, false otherwise + +###### Example + +```ts +const exists = await Template.exists('my-python-env') +if (exists) { + console.log('Template exists!') +} +``` + +### getBuildStatus() + +```ts +static getBuildStatus(data: Pick, options?: GetBuildStatusOptions): Promise +``` + +Get the status of a build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `data` | `Pick`\<`BuildInfo`, `"buildId"` \| `"templateId"`\> | Build identifiers | +| `options`? | `GetBuildStatusOptions` | Authentication options | + +###### Returns + +`Promise`\<`TemplateBuildStatusResponse`\> + +###### Example + +```ts +const status = await Template.getBuildStatus(data, { logsOffset: 0 }) +``` + +### getTags() + +```ts +static getTags(templateId: string, options?: ConnectionOpts): Promise +``` + +Get all tags for a template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `templateId` | `string` | Template ID or name | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`TemplateTag`[]\> + +Array of tag details including tag name, buildId, and creation date + +###### Example + +```ts +const tags = await Template.getTags('my-template') +for (const tag of tags) { + console.log(`Tag: ${tag.tag}, Build: ${tag.buildId}, Created: ${tag.createdAt}`) +} +``` + +### removeTags() + +```ts +static removeTags( + name: string, + tags: string | string[], +options?: ConnectionOpts): Promise +``` + +Remove tag(s) from a template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Template name | +| `tags` | `string` \| `string`[] | Tag or tags to remove | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`void`\> + +###### Example + +```ts +// Remove a single tag +await Template.removeTags('my-template', 'production') + +// Remove multiple tags from a template +await Template.removeTags('my-template', ['production', 'staging']) +``` + +### toDockerfile() + +```ts +static toDockerfile(template: TemplateClass): string +``` + +Convert a template to Dockerfile format. +Note: Templates based on other E2B templates cannot be converted to Dockerfile. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to convert | + +###### Returns + +`string` + +Dockerfile string representation + +###### Throws + +Error if the template is based on another E2B template + +### toJSON() + +```ts +static toJSON(template: TemplateClass, computeHashes: boolean): Promise +``` + +Convert a template to JSON representation. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `template` | `TemplateClass` | `undefined` | The template to convert | +| `computeHashes` | `boolean` | `true` | Whether to compute file hashes for cache invalidation | + +###### Returns + +`Promise`\<`string`\> + +JSON string representation of the template + +## Interfaces + +### TemplateBuilder + +Main builder state for constructing templates. +Provides methods for customizing the template environment. + +#### Methods + +### addMcpServer() + +```ts +addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder +``` + +Install MCP servers using mcp-gateway. +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | + +###### Returns + +`TemplateBuilder` + +###### Throws + +If the base template is not mcp-gateway + +###### Example + +```ts +template.addMcpServer('exa') +template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) +``` + +### aptInstall() + +```ts +aptInstall(packages: string | string[], options?: object): TemplateBuilder +``` + +Install Debian/Ubuntu packages using apt-get. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages` | `string` \| `string`[] | Package name(s) | +| `options`? | \{ `fixMissing`: `boolean`; `noInstallRecommends`: `boolean`; \} | - | +| `options.fixMissing`? | `boolean` | - | +| `options.noInstallRecommends`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.aptInstall('vim') +template.aptInstall(['git', 'curl', 'wget']) +template.aptInstall(['vim'], { noInstallRecommends: true }) +template.aptInstall(['vim'], { fixMissing: true }) +``` + +### betaDevContainerPrebuild() + +```ts +betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder +``` + +Prebuild a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') +``` + +### betaSetDevContainerStart() + +```ts +betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal +``` + +Start a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .startDevcontainer('/my-devcontainer') + +// Prebuild and start +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') + // Other instructions... + .betaSetDevContainerStart('/my-devcontainer') +``` + +### bunInstall() + +```ts +bunInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Bun packages using bun. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | \{ `dev`: `boolean`; `g`: `boolean`; \} | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.bunInstall('express') +template.bunInstall(['lodash', 'axios']) +template.bunInstall('tsx', { g: true }) +template.bunInstall('typescript', { dev: true }) +template.bunInstall() // Installs from package.json +``` + +### copy() + +```ts +copy( + src: PathLike | PathLike[], + dest: PathLike, + options?: object): TemplateBuilder +``` + +Copy files or directories into the template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` \| `PathLike`[] | Source path(s) | +| `dest` | `PathLike` | Destination path | +| `options`? | \{ `forceUpload`: `true`; `mode`: `number`; `resolveSymlinks`: `boolean`; `user`: `string`; \} | Copy options | +| `options.forceUpload`? | `true` | - | +| `options.mode`? | `number` | - | +| `options.resolveSymlinks`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copy('requirements.txt', '/home/user/') +template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) +``` + +### copyItems() + +```ts +copyItems(items: CopyItem[]): TemplateBuilder +``` + +Copy multiple items with individual options. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `items` | `CopyItem`[] | Array of copy items | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copyItems([ + { src: 'app.ts', dest: '/app/' }, + { src: 'config.ts', dest: '/app/', mode: 0o644 } +]) +``` + +### gitClone() + +```ts +gitClone( + url: string, + path?: PathLike, + options?: object): TemplateBuilder +``` + +Clone a Git repository. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | Repository URL | +| `path`? | `PathLike` | Optional destination path | +| `options`? | \{ `branch`: `string`; `depth`: `number`; `user`: `string`; \} | Clone options | +| `options.branch`? | `string` | - | +| `options.depth`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.gitClone('https://github.com/user/repo.git', '/app/repo') +template.gitClone('https://github.com/user/repo.git', undefined, { + branch: 'main', + depth: 1 +}) +template.gitClone('https://github.com/user/repo.git', '/app/repo', { + user: 'root' +}) +``` + +### makeDir() + +```ts +makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Create directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | +| `options`? | \{ `mode`: `number`; `user`: `string`; \} | Directory options | +| `options.mode`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeDir('/app/data', { mode: 0o755 }) +template.makeDir(['/app/logs', '/app/cache']) +template.makeDir('/app/data', { mode: 0o755, user: 'root' }) +``` + +### makeSymlink() + +```ts +makeSymlink( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Create a symbolic link. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path (target) | +| `dest` | `PathLike` | Destination path (symlink location) | +| `options`? | \{ `force`: `boolean`; `user`: `string`; \} | Symlink options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeSymlink('/usr/bin/python3', '/usr/bin/python') +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) +``` + +### npmInstall() + +```ts +npmInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Node.js packages using npm. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | \{ `dev`: `boolean`; `g`: `boolean`; \} | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.npmInstall('express') +template.npmInstall(['lodash', 'axios']) +template.npmInstall('tsx', { g: true }) +template.npmInstall('typescript', { dev: true }) +template.npmInstall() // Installs from package.json +``` + +### pipInstall() + +```ts +pipInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Python packages using pip. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | +| `options`? | \{ `g`: `boolean`; \} | Install options | +| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.pipInstall('numpy') // Installs globally (default) +template.pipInstall(['pandas', 'scikit-learn']) +template.pipInstall('numpy', { g: false }) // Install for user only +template.pipInstall() // Installs from current directory +``` + +### remove() + +```ts +remove(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Remove files or directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | +| `options`? | \{ `force`: `boolean`; `recursive`: `boolean`; `user`: `string`; \} | Remove options | +| `options.force`? | `boolean` | - | +| `options.recursive`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.remove('/tmp/cache', { recursive: true, force: true }) +template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) +``` + +### rename() + +```ts +rename( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Rename or move a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path | +| `dest` | `PathLike` | Destination path | +| `options`? | \{ `force`: `boolean`; `user`: `string`; \} | Rename options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) +``` + +### runCmd() + +###### Call Signature + +```ts +runCmd(command: string, options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `command` | `string` | Command string | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### Call Signature + +```ts +runCmd(commands: string[], options?: object): TemplateBuilder +``` + +Run multiple shell commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commands` | `string`[] | Array of command strings | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Call Signature + +```ts +runCmd(commandOrCommands: string | string[], options?: object): TemplateBuilder +``` + +Run command(s). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commandOrCommands` | `string` \| `string`[] | Command or commands | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +### setEnvs() + +```ts +setEnvs(envs: Record): TemplateBuilder +``` + +Set environment variables. +Note: Environment variables defined here are available only during template build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `envs` | `Record`\<`string`, `string`\> | Environment variables | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) +``` + +### setReadyCmd() + +```ts +setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set or update the ready check command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setReadyCmd('curl http://localhost:8000/health') + +// Using ReadyCmd helpers +import { waitForPort, waitForFile, waitForProcess } from 'e2b' + +template.setReadyCmd(waitForPort(3000)) + +template.setReadyCmd(waitForFile('/tmp/ready')) + +template.setReadyCmd(waitForProcess('nginx')) +``` + +### setStartCmd() + +```ts +setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set the start command and ready check. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `startCommand` | `string` | Command to run on startup | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setStartCmd( + 'node app.js', + 'curl http://localhost:8000/health' +) + +// Using ReadyCmd helpers +import { waitForPort, waitForURL } from 'e2b' + +template.setStartCmd( + 'python -m http.server 8000', + waitForPort(8000) +) + +template.setStartCmd( + 'npm start', + waitForURL('http://localhost:3000/health', 200) +) +``` + +### setUser() + +```ts +setUser(user: string): TemplateBuilder +``` + +Set the user for subsequent commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `user` | `string` | Username | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setUser('root') +``` + +### setWorkdir() + +```ts +setWorkdir(workdir: PathLike): TemplateBuilder +``` + +Set the working directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `workdir` | `PathLike` | Working directory path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setWorkdir('/app') +``` + +### skipCache() + +```ts +skipCache(): this +``` + +Skip cache for all subsequent build instructions from this point. + +###### Returns + +`this` + +###### Example + +```ts +template.skipCache().runCmd('apt-get update') +``` + +## Type Aliases + +### BuildInfo + +```ts +type BuildInfo = object; +``` + +Information about a built template. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `alias` | `string` | First alias from the build (for backward compatibility). **Deprecated** Use `name` instead. | +| `buildId` | `string` | Build identifier. | +| `name` | `string` | Name of the template. | +| `tags` | `string`[] | Tags assigned to this build. | +| `templateId` | `string` | Template identifier. | + +*** + +### BuildOptions + +```ts +type BuildOptions = ConnectionOpts & BasicBuildOptions; +``` + +Options for building a template with authentication. + +*** + +### BuildStatusReason + +```ts +type BuildStatusReason = object; +``` + +Reason for the current build status (typically for errors). + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `logEntries` | `LogEntry`[] | Log entries related to the status reason. | +| `message` | `string` | Message with the status reason. | +| `step`? | `string` | Step that failed. | + +*** + +### CopyItem + +```ts +type CopyItem = object; +``` + +Configuration for a single file/directory copy operation. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `dest` | `PathLike` | +| `forceUpload`? | `true` | +| `mode`? | `number` | +| `resolveSymlinks`? | `boolean` | +| `src` | `PathLike` \| `PathLike`[] | +| `user`? | `string` | + +*** + +### GetBuildStatusOptions + +```ts +type GetBuildStatusOptions = ConnectionOpts & object; +``` + +Options for getting build status. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `logsOffset`? | `number` | + +*** + +### McpServerName + +```ts +type McpServerName = keyof McpServer; +``` + +MCP server names that can be installed. + +*** + +### TemplateBuildStatus + +```ts +type TemplateBuildStatus = "building" | "waiting" | "ready" | "error"; +``` + +Status of a template build. + +*** + +### TemplateBuildStatusResponse + +```ts +type TemplateBuildStatusResponse = object; +``` + +Response from getting build status. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `buildID` | `string` | Build identifier. | +| `logEntries` | `LogEntry`[] | Build log entries. | +| `logs` | `string`[] | Build logs (raw strings). **Deprecated** Use `logEntries` instead. | +| `reason`? | `BuildStatusReason` | Reason for the current status (typically for errors). | +| `status` | `TemplateBuildStatus` | Current status of the build. | +| `templateID` | `string` | Template identifier. | + +*** + +### TemplateClass + +```ts +type TemplateClass = TemplateBuilder | TemplateFinal; +``` + +Type representing a template in any state (builder or final). + +*** + +### TemplateTag + +```ts +type TemplateTag = object; +``` + +Detailed information about a single template tag. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `buildId` | `string` | Build identifier associated with this tag. | +| `createdAt` | `Date` | When this tag was assigned. | +| `tag` | `string` | Name of the tag. | + +*** + +### TemplateTagInfo + +```ts +type TemplateTagInfo = object; +``` + +Information about assigned template tags. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `buildId` | `string` | Build identifier associated with this tag. | +| `tags` | `string`[] | Assigned tags of the template. | + +## Functions + +### Template() + +```ts +function Template(options?: TemplateOptions): TemplateFromImage +``` + +Create a new E2B template builder instance. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options`? | `TemplateOptions` | Optional configuration for the template builder | + +#### Returns + +`TemplateFromImage` + +A new template builder instance + +#### Example + +```ts +import { Template } from 'e2b' + +const template = Template() + .fromPythonImage('3') + .copy('requirements.txt', '/app/') + .pipInstall() + +await Template.build(template, 'my-python-app:v1.0') +``` diff --git a/docs/sdk-reference/js-sdk/v2.18.0/errors.mdx b/docs/sdk-reference/js-sdk/v2.18.0/errors.mdx new file mode 100644 index 00000000..dde55e69 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.18.0/errors.mdx @@ -0,0 +1,407 @@ +--- +sidebarTitle: "Errors" +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Extended by + +- `GitAuthError` + +#### Constructors + +```ts +new AuthenticationError(message: string): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`AuthenticationError` + +``` + +*** + +### BuildError + +Thrown when the build fails. + +#### Extended by + +- `FileUploadError` + +#### Constructors + +```ts +new BuildError(message: string, stackTrace?: string): BuildError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`BuildError` + +``` + +*** + +### FileNotFoundError + +Thrown when a file or directory is not found inside a sandbox. + +#### Constructors + +```ts +new FileNotFoundError(message: string, stackTrace?: string): FileNotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`FileNotFoundError` + +*** + +### FileUploadError + +Thrown when the file upload fails. + +#### Constructors + +```ts +new FileUploadError(message: string, stackTrace?: string): FileUploadError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`FileUploadError` + +*** + +### GitAuthError + +Thrown when git authentication fails. + +#### Constructors + +```ts +new GitAuthError(message: string): GitAuthError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`GitAuthError` + +*** + +### GitUpstreamError + +Thrown when git upstream tracking is missing. + +#### Constructors + +```ts +new GitUpstreamError(message: string, stackTrace?: string): GitUpstreamError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`GitUpstreamError` + +*** + +### 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. + +#### Deprecated + +Use FileNotFoundError or SandboxNotFoundError instead. This class will be removed in the next major version. + +#### Extended by + +- `FileNotFoundError` +- `SandboxNotFoundError` + +#### 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` +- `GitUpstreamError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message?: string, stackTrace?: string): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message`? | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`SandboxError` + +``` + +*** + +### SandboxNotFoundError + +Thrown when a sandbox is not found (e.g. it doesn't exist or is no longer running). + +#### Constructors + +```ts +new SandboxNotFoundError(message: string, stackTrace?: string): SandboxNotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`SandboxNotFoundError` + +*** + +### 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` + +*** + +### VolumeError + +Base class for all volume errors. + +Thrown when general volume errors occur. + +#### Constructors + +```ts +new VolumeError(message: string): VolumeError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`VolumeError` + +``` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/docs/sdk-reference/js-sdk/v2.18.0/sandbox-commands.mdx b/docs/sdk-reference/js-sdk/v2.18.0/sandbox-commands.mdx new file mode 100644 index 00000000..c97c6b9b --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.18.0/sandbox-commands.mdx @@ -0,0 +1,555 @@ +--- +sidebarTitle: "Commands" +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands( + transport: Transport, + connectionConfig: ConnectionConfig, + metadata: object): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | +| `metadata` | \{ `version`: `string`; \} | +| `metadata.version` | `string` | + +###### 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() + +###### Call Signature + +```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. + +###### Call Signature + +```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. + +###### Call Signature + +```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 | Uint8Array, +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` \| `Uint8Array`\<`ArrayBufferLike`\> | 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, + metadata: object): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | +| `metadata` | \{ `version`: `string`; \} | +| `metadata.version` | `string` | + +###### Returns + +`Pty` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: PtyConnectOpts): Promise +``` + +Connect to a running PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY to connect to. You can get the list of running PTYs using Commands.list. | +| `opts`? | `PtyConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### 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` | \{ `cols`: `number`; `rows`: `number`; \} | 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 +``` + +### stdin? + +```ts +optional stdin: boolean; +``` + +If true, command stdin is kept open and you can send data to it using Commands.sendStdin or CommandHandle.sendStdin. + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to run the command as. + +###### Default + +`default Sandbox user (as specified in the template)` + +*** + +### 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/docs/sdk-reference/js-sdk/v2.18.0/sandbox-filesystem.mdx b/docs/sdk-reference/js-sdk/v2.18.0/sandbox-filesystem.mdx new file mode 100644 index 00000000..aed576f6 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.18.0/sandbox-filesystem.mdx @@ -0,0 +1,665 @@ +--- +sidebarTitle: "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() + +###### Call Signature + +```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 + +###### Call Signature + +```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`\<`ArrayBufferLike`\>\> + +file content as `Uint8Array` + +###### Call Signature + +```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` + +###### Call Signature + +```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`\<`ArrayBufferLike`\>\>\> + +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() + +###### Call Signature + +```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 + +###### Call Signature + +```ts +write(files: WriteEntry[], 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 | +| ------ | ------ | ------ | +| `files` | `WriteEntry`[] | - | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +information about the written file + +### writeFiles() + +```ts +writeFiles(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +Write multiple files. + +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 | +| ------ | ------ | ------ | +| `files` | `WriteEntry`[] | list of files to write as `WriteEntry` objects, each containing `path` and `data`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +information about the written files + +## 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: string; +``` + +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: string; +``` + +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: string; +``` + +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/docs/sdk-reference/js-sdk/v2.18.0/sandbox.mdx b/docs/sdk-reference/js-sdk/v2.18.0/sandbox.mdx new file mode 100644 index 00000000..3cda892c --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.18.0/sandbox.mdx @@ -0,0 +1,940 @@ +--- +sidebarTitle: "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 git operations +- 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 | +| `git` | `readonly` | `Git` | Module for running git operations in the sandbox | +| `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. | +| `trafficAccessToken?` | `readonly` | `string` | Traffic access token for accessing sandbox services with restricted public traffic. | + +#### Methods + +### ~~betaPause()~~ + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `ConnectionOpts` | + +###### Returns + +`Promise`\<`boolean`\> + +###### Deprecated + +Use Sandbox.pause instead. + +### connect() + +```ts +connect(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). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxConnectOpts` | 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() +``` + +### createSnapshot() + +```ts +createSnapshot(opts?: SandboxApiOpts): Promise +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshotId` with `Sandbox.create(snapshotId)` to create a new sandbox from the snapshot. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SnapshotInfo`\> + +snapshot information including the snapshot ID. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.files.write('/app/state.json', '{"step": 1}') + +// Create a snapshot +const snapshot = await sandbox.createSnapshot() + +// Create a new sandbox from the snapshot +const newSandbox = await Sandbox.create(snapshot.snapshotId) +``` + +### 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 + +### getMcpToken() + +```ts +getMcpToken(): Promise +``` + +Get the MCP token for the sandbox. + +###### Returns + +`Promise`\<`undefined` \| `string`\> + +MCP token for the sandbox, or undefined if MCP is not enabled. + +### getMcpUrl() + +```ts +getMcpUrl(): string +``` + +Get the MCP URL for the sandbox. + +###### Returns + +`string` + +MCP URL for 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`\> + +### listSnapshots() + +```ts +listSnapshots(opts?: Omit): SnapshotPaginator +``` + +List all snapshots created from this sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Omit`\<`SnapshotListOpts`, `"sandboxId"`\> | list options. | + +###### Returns + +`SnapshotPaginator` + +paginator for listing snapshots from this sandbox. + +### pause() + +```ts +pause(opts?: ConnectionOpts): Promise +``` + +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. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.pause() +``` + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. + +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() + +###### Call Signature + +```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 + +###### Call Signature + +```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 +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`boolean`\> + +###### Deprecated + +Use SandboxApi.pause instead. + +``` + +### 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() + +###### Call Signature + +```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 + +###### 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 + +### createSnapshot() + +```ts +static createSnapshot(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Create a snapshot from a sandbox. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same state. +The snapshot is a persistent image that survives sandbox deletion. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID to create snapshot from. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SnapshotInfo`\> + +snapshot information including the snapshot name that can be used with Sandbox.create(). + +``` + +### deleteSnapshot() + +```ts +static deleteSnapshot(snapshotId: string, opts?: SandboxApiOpts): Promise +``` + +Delete a snapshot. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `snapshotId` | `string` | snapshot ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the snapshot was deleted, `false` if it was not found. + +``` + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise<{ + allowInternetAccess: undefined | boolean; + cpuCount: number; + endAt: Date; + envdAccessToken: undefined | string; + envdVersion: string; + lifecycle: | undefined + | { + autoResume: boolean; + onTimeout: "kill" | "pause"; + }; + memoryMB: number; + metadata: {}; + name: string; + network: | undefined + | { + allowOut: undefined | string[]; + allowPublicTraffic: undefined | boolean; + denyOut: undefined | string[]; + maskRequestHost: undefined | string; + }; + sandboxDomain: undefined | string; + sandboxId: string; + startedAt: Date; + state: "running" | "paused"; + templateId: string; + volumeMounts: object[]; +}> +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<\{ + `allowInternetAccess`: `undefined` \| `boolean`; + `cpuCount`: `number`; + `endAt`: `Date`; + `envdAccessToken`: `undefined` \| `string`; + `envdVersion`: `string`; + `lifecycle`: \| `undefined` + \| \{ + `autoResume`: `boolean`; + `onTimeout`: `"kill"` \| `"pause"`; + \}; + `memoryMB`: `number`; + `metadata`: \{\}; + `name`: `string`; + `network`: \| `undefined` + \| \{ + `allowOut`: `undefined` \| `string`[]; + `allowPublicTraffic`: `undefined` \| `boolean`; + `denyOut`: `undefined` \| `string`[]; + `maskRequestHost`: `undefined` \| `string`; + \}; + `sandboxDomain`: `undefined` \| `string`; + `sandboxId`: `string`; + `startedAt`: `Date`; + `state`: `"running"` \| `"paused"`; + `templateId`: `string`; + `volumeMounts`: `object`[]; + \}\> + +``` + +### 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. + +### listSnapshots() + +```ts +static listSnapshots(opts?: SnapshotListOpts): SnapshotPaginator +``` + +List all snapshots. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SnapshotListOpts` | list options including filters and pagination. | + +###### Returns + +`SnapshotPaginator` + +paginator for listing snapshots. + +``` + +### pause() + +```ts +static pause(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. + +``` + +### 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: string; +``` + +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/docs/sdk-reference/js-sdk/v2.18.0/template-logger.mdx b/docs/sdk-reference/js-sdk/v2.18.0/template-logger.mdx new file mode 100644 index 00000000..bb4b9315 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.18.0/template-logger.mdx @@ -0,0 +1,195 @@ +--- +sidebarTitle: "Logger" +--- + +### LogEntry + +Represents a single log entry from the template build process. + +#### Extended by + +- `LogEntryStart` +- `LogEntryEnd` + +#### Constructors + +```ts +new LogEntry( + timestamp: Date, + level: LogEntryLevel, + message: string): LogEntry +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `level` | `LogEntryLevel` | +| `message` | `string` | + +###### Returns + +`LogEntry` + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | +| `message` | `readonly` | `string` | +| `timestamp` | `readonly` | `Date` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### LogEntryEnd + +Special log entry indicating the end of a build process. + +#### Constructors + +```ts +new LogEntryEnd(timestamp: Date, message: string): LogEntryEnd +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `message` | `string` | + +###### Returns + +`LogEntryEnd` + +#### Properties + +| Property | Modifier | Type | Inherited from | +| ------ | ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | +| `message` | `readonly` | `string` | `LogEntry`.`message` | +| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### LogEntryStart + +Special log entry indicating the start of a build process. + +#### Constructors + +```ts +new LogEntryStart(timestamp: Date, message: string): LogEntryStart +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `message` | `string` | + +###### Returns + +`LogEntryStart` + +#### Properties + +| Property | Modifier | Type | Inherited from | +| ------ | ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | +| `message` | `readonly` | `string` | `LogEntry`.`message` | +| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +## Type Aliases + +### LogEntryLevel + +```ts +type LogEntryLevel = "debug" | "info" | "warn" | "error"; +``` + +Log entry severity levels. + +## Functions + +### defaultBuildLogger() + +```ts +function defaultBuildLogger(options?: object): (logEntry: LogEntry) => void +``` + +Create a default build logger with animated timer display. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options`? | \{ `minLevel`: `LogEntryLevel`; \} | Logger configuration options | +| `options.minLevel`? | `LogEntryLevel` | Minimum log level to display (default: 'info') | + +#### Returns + +`Function` + +Logger function that accepts LogEntry instances + +### Parameters + +| Parameter | Type | +| ------ | ------ | +| `logEntry` | `LogEntry` | + +### Returns + +`void` + +#### Example + +```ts +import { Template, defaultBuildLogger } from 'e2b' + +const template = Template().fromPythonImage() + +await Template.build(template, { + alias: 'my-template', + onBuildLogs: defaultBuildLogger({ minLevel: 'debug' }) +}) +``` diff --git a/docs/sdk-reference/js-sdk/v2.18.0/template-readycmd.mdx b/docs/sdk-reference/js-sdk/v2.18.0/template-readycmd.mdx new file mode 100644 index 00000000..a35a37aa --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.18.0/template-readycmd.mdx @@ -0,0 +1,201 @@ +--- +sidebarTitle: "Readycmd" +--- + +### ReadyCmd + +Class for ready check commands. + +#### Constructors + +```ts +new ReadyCmd(cmd: string): ReadyCmd +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `cmd` | `string` | + +###### Returns + +`ReadyCmd` + +#### Methods + +### getCmd() + +```ts +getCmd(): string +``` + +###### Returns + +`string` + +## Functions + +### waitForFile() + +```ts +function waitForFile(filename: string): ReadyCmd +``` + +Wait for a file to exist. +Uses shell test command to check file existence. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filename` | `string` | Path to the file to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the file + +#### Example + +```ts +import { Template, waitForFile } from 'e2b' + +const template = Template() + .fromBaseImage() + .setStartCmd('./init.sh', waitForFile('/tmp/ready')) +``` + +*** + +### waitForPort() + +```ts +function waitForPort(port: number): ReadyCmd +``` + +Wait for a port to be listening. +Uses `ss` command to check if a port is open and listening. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | Port number to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the port + +#### Example + +```ts +import { Template, waitForPort } from 'e2b' + +const template = Template() + .fromPythonImage() + .setStartCmd('python -m http.server 8000', waitForPort(8000)) +``` + +*** + +### waitForProcess() + +```ts +function waitForProcess(processName: string): ReadyCmd +``` + +Wait for a process with a specific name to be running. +Uses `pgrep` to check if a process exists. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `processName` | `string` | Name of the process to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the process + +#### Example + +```ts +import { Template, waitForProcess } from 'e2b' + +const template = Template() + .fromBaseImage() + .setStartCmd('./my-daemon', waitForProcess('my-daemon')) +``` + +*** + +### waitForTimeout() + +```ts +function waitForTimeout(timeout: number): ReadyCmd +``` + +Wait for a specified timeout before considering the sandbox ready. +Uses `sleep` command to wait for a fixed duration. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeout` | `number` | Time to wait in milliseconds (minimum: 1000ms / 1 second) | + +#### Returns + +`ReadyCmd` + +ReadyCmd that waits for the specified duration + +#### Example + +```ts +import { Template, waitForTimeout } from 'e2b' + +const template = Template() + .fromNodeImage() + .setStartCmd('npm start', waitForTimeout(5000)) // Wait 5 seconds +``` + +*** + +### waitForURL() + +```ts +function waitForURL(url: string, statusCode: number): ReadyCmd +``` + +Wait for a URL to return a specific HTTP status code. +Uses `curl` to make HTTP requests and check the response status. + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `url` | `string` | `undefined` | URL to check (e.g., 'http://localhost:3000/health') | +| `statusCode` | `number` | `200` | Expected HTTP status code (default: 200) | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks the URL + +#### Example + +```ts +import { Template, waitForURL } from 'e2b' + +const template = Template() + .fromNodeImage() + .setStartCmd('npm start', waitForURL('http://localhost:3000/health')) +``` diff --git a/docs/sdk-reference/js-sdk/v2.18.0/template.mdx b/docs/sdk-reference/js-sdk/v2.18.0/template.mdx new file mode 100644 index 00000000..c0fbcf34 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.18.0/template.mdx @@ -0,0 +1,2377 @@ +--- +sidebarTitle: "Template" +--- + +### TemplateBase + +Base class for building E2B sandbox templates. + +#### Implements + +- `TemplateFromImage` +- `TemplateBuilder` +- `TemplateFinal` + +#### Constructors + +```ts +new TemplateBase(options?: TemplateOptions): TemplateBase +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `options`? | `TemplateOptions` | + +###### Returns + +`TemplateBase` + +#### Methods + +### addMcpServer() + +```ts +addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder +``` + +Install MCP servers using mcp-gateway. +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | + +###### Returns + +`TemplateBuilder` + +###### Throws + +If the base template is not mcp-gateway + +###### Example + +```ts +template.addMcpServer('exa') +template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) +``` + +###### Implementation of + +`TemplateBuilder`.`addMcpServer` + +### aptInstall() + +```ts +aptInstall(packages: string | string[], options?: object): TemplateBuilder +``` + +Install Debian/Ubuntu packages using apt-get. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages` | `string` \| `string`[] | Package name(s) | +| `options`? | \{ `fixMissing`: `boolean`; `noInstallRecommends`: `boolean`; \} | - | +| `options.fixMissing`? | `boolean` | - | +| `options.noInstallRecommends`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.aptInstall('vim') +template.aptInstall(['git', 'curl', 'wget']) +template.aptInstall(['vim'], { noInstallRecommends: true }) +template.aptInstall(['vim'], { fixMissing: true }) +``` + +###### Implementation of + +`TemplateBuilder`.`aptInstall` + +### betaDevContainerPrebuild() + +```ts +betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder +``` + +Prebuild a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') +``` + +###### Implementation of + +`TemplateBuilder`.`betaDevContainerPrebuild` + +### betaSetDevContainerStart() + +```ts +betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal +``` + +Start a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .startDevcontainer('/my-devcontainer') + +// Prebuild and start +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') + // Other instructions... + .betaSetDevContainerStart('/my-devcontainer') +``` + +###### Implementation of + +`TemplateBuilder`.`betaSetDevContainerStart` + +### bunInstall() + +```ts +bunInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Bun packages using bun. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | \{ `dev`: `boolean`; `g`: `boolean`; \} | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.bunInstall('express') +template.bunInstall(['lodash', 'axios']) +template.bunInstall('tsx', { g: true }) +template.bunInstall('typescript', { dev: true }) +template.bunInstall() // Installs from package.json +``` + +###### Implementation of + +`TemplateBuilder`.`bunInstall` + +### copy() + +```ts +copy( + src: PathLike | PathLike[], + dest: PathLike, + options?: object): TemplateBuilder +``` + +Copy files or directories into the template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` \| `PathLike`[] | Source path(s) | +| `dest` | `PathLike` | Destination path | +| `options`? | \{ `forceUpload`: `true`; `mode`: `number`; `resolveSymlinks`: `boolean`; `user`: `string`; \} | Copy options | +| `options.forceUpload`? | `true` | - | +| `options.mode`? | `number` | - | +| `options.resolveSymlinks`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copy('requirements.txt', '/home/user/') +template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) +``` + +###### Implementation of + +`TemplateBuilder`.`copy` + +### copyItems() + +```ts +copyItems(items: CopyItem[]): TemplateBuilder +``` + +Copy multiple items with individual options. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `items` | `CopyItem`[] | Array of copy items | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copyItems([ + { src: 'app.ts', dest: '/app/' }, + { src: 'config.ts', dest: '/app/', mode: 0o644 } +]) +``` + +###### Implementation of + +`TemplateBuilder`.`copyItems` + +### fromAWSRegistry() + +```ts +fromAWSRegistry(image: string, credentials: object): TemplateBuilder +``` + +Start from a Docker image in AWS ECR. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `image` | `string` | Full ECR image path | +| `credentials` | \{ `accessKeyId`: `string`; `region`: `string`; `secretAccessKey`: `string`; \} | AWS credentials | +| `credentials.accessKeyId` | `string` | - | +| `credentials.region` | `string` | - | +| `credentials.secretAccessKey` | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromAWSRegistry( + '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', + { + accessKeyId: 'AKIA...', + secretAccessKey: '...', + region: 'us-west-2' + } +) +``` + +###### Implementation of + +```ts +TemplateFromImage.fromAWSRegistry +``` + +### fromBaseImage() + +```ts +fromBaseImage(): TemplateBuilder +``` + +Start from E2B's default base image (e2bdev/base:latest). + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromBaseImage() +``` + +###### Implementation of + +```ts +TemplateFromImage.fromBaseImage +``` + +### fromBunImage() + +```ts +fromBunImage(variant: string): TemplateBuilder +``` + +Start from a Bun-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'latest'` | Bun variant (default: 'latest') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromBunImage('1.3') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromBunImage +``` + +### fromDebianImage() + +```ts +fromDebianImage(variant: string): TemplateBuilder +``` + +Start from a Debian-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'stable'` | Debian variant (default: 'stable') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromDebianImage('bookworm') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromDebianImage +``` + +### fromDockerfile() + +```ts +fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder +``` + +Parse a Dockerfile and convert it to Template SDK format. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `dockerfileContentOrPath` | `string` | Dockerfile content or path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromDockerfile('Dockerfile') +Template().fromDockerfile('FROM python:3\nRUN pip install numpy') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromDockerfile +``` + +### fromGCPRegistry() + +```ts +fromGCPRegistry(image: string, credentials: object): TemplateBuilder +``` + +Start from a Docker image in Google Container Registry. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `image` | `string` | Full GCR/GAR image path | +| `credentials` | \{ `serviceAccountJSON`: `string` \| `object`; \} | GCP service account credentials | +| `credentials.serviceAccountJSON` | `string` \| `object` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromGCPRegistry( + 'gcr.io/myproject/myimage:latest', + { serviceAccountJSON: 'path/to/service-account.json' } +) +``` + +###### Implementation of + +```ts +TemplateFromImage.fromGCPRegistry +``` + +### fromImage() + +```ts +fromImage(baseImage: string, credentials?: object): TemplateBuilder +``` + +Start from a custom Docker image. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `baseImage` | `string` | Docker image name | +| `credentials`? | \{ `password`: `string`; `username`: `string`; \} | Optional credentials for private registries | +| `credentials.password`? | `string` | - | +| `credentials.username`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromImage('python:3') + +// With credentials (optional) +Template().fromImage('myregistry.com/myimage:latest', { + username: 'user', + password: 'pass' +}) +``` + +###### Implementation of + +```ts +TemplateFromImage.fromImage +``` + +### fromNodeImage() + +```ts +fromNodeImage(variant: string): TemplateBuilder +``` + +Start from a Node.js-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'lts'` | Node.js variant (default: 'lts') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromNodeImage('24') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromNodeImage +``` + +### fromPythonImage() + +```ts +fromPythonImage(version: string): TemplateBuilder +``` + +Start from a Python-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `version` | `string` | `'3'` | Python version (default: '3') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromPythonImage('3') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromPythonImage +``` + +### fromTemplate() + +```ts +fromTemplate(template: string): TemplateBuilder +``` + +Start from an existing E2B template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `string` | E2B template ID or alias | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromTemplate('my-base-template') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromTemplate +``` + +### fromUbuntuImage() + +```ts +fromUbuntuImage(variant: string): TemplateBuilder +``` + +Start from an Ubuntu-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'latest'` | Ubuntu variant (default: 'latest') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromUbuntuImage('24.04') +``` + +###### Implementation of + +```ts +TemplateFromImage.fromUbuntuImage +``` + +### gitClone() + +```ts +gitClone( + url: string, + path?: PathLike, + options?: object): TemplateBuilder +``` + +Clone a Git repository. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | Repository URL | +| `path`? | `PathLike` | Optional destination path | +| `options`? | \{ `branch`: `string`; `depth`: `number`; `user`: `string`; \} | Clone options | +| `options.branch`? | `string` | - | +| `options.depth`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.gitClone('https://github.com/user/repo.git', '/app/repo') +template.gitClone('https://github.com/user/repo.git', undefined, { + branch: 'main', + depth: 1 +}) +template.gitClone('https://github.com/user/repo.git', '/app/repo', { + user: 'root' +}) +``` + +###### Implementation of + +`TemplateBuilder`.`gitClone` + +### makeDir() + +```ts +makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Create directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | +| `options`? | \{ `mode`: `number`; `user`: `string`; \} | Directory options | +| `options.mode`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeDir('/app/data', { mode: 0o755 }) +template.makeDir(['/app/logs', '/app/cache']) +template.makeDir('/app/data', { mode: 0o755, user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`makeDir` + +### makeSymlink() + +```ts +makeSymlink( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Create a symbolic link. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path (target) | +| `dest` | `PathLike` | Destination path (symlink location) | +| `options`? | \{ `force`: `boolean`; `user`: `string`; \} | Symlink options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeSymlink('/usr/bin/python3', '/usr/bin/python') +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) +``` + +###### Implementation of + +`TemplateBuilder`.`makeSymlink` + +### npmInstall() + +```ts +npmInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Node.js packages using npm. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | \{ `dev`: `boolean`; `g`: `boolean`; \} | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.npmInstall('express') +template.npmInstall(['lodash', 'axios']) +template.npmInstall('tsx', { g: true }) +template.npmInstall('typescript', { dev: true }) +template.npmInstall() // Installs from package.json +``` + +###### Implementation of + +`TemplateBuilder`.`npmInstall` + +### pipInstall() + +```ts +pipInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Python packages using pip. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | +| `options`? | \{ `g`: `boolean`; \} | Install options | +| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.pipInstall('numpy') // Installs globally (default) +template.pipInstall(['pandas', 'scikit-learn']) +template.pipInstall('numpy', { g: false }) // Install for user only +template.pipInstall() // Installs from current directory +``` + +###### Implementation of + +`TemplateBuilder`.`pipInstall` + +### remove() + +```ts +remove(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Remove files or directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | +| `options`? | \{ `force`: `boolean`; `recursive`: `boolean`; `user`: `string`; \} | Remove options | +| `options.force`? | `boolean` | - | +| `options.recursive`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.remove('/tmp/cache', { recursive: true, force: true }) +template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`remove` + +### rename() + +```ts +rename( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Rename or move a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path | +| `dest` | `PathLike` | Destination path | +| `options`? | \{ `force`: `boolean`; `user`: `string`; \} | Rename options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`rename` + +### runCmd() + +###### Call Signature + +```ts +runCmd(command: string, options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `command` | `string` | Command string | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`runCmd` + +###### Call Signature + +```ts +runCmd(commands: string[], options?: object): TemplateBuilder +``` + +Run multiple shell commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commands` | `string`[] | Array of command strings | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Implementation of + +`TemplateBuilder`.`runCmd` + +### setEnvs() + +```ts +setEnvs(envs: Record): TemplateBuilder +``` + +Set environment variables. +Note: Environment variables defined here are available only during template build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `envs` | `Record`\<`string`, `string`\> | Environment variables | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) +``` + +###### Implementation of + +`TemplateBuilder`.`setEnvs` + +### setReadyCmd() + +```ts +setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set or update the ready check command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setReadyCmd('curl http://localhost:8000/health') + +// Using ReadyCmd helpers +import { waitForPort, waitForFile, waitForProcess } from 'e2b' + +template.setReadyCmd(waitForPort(3000)) + +template.setReadyCmd(waitForFile('/tmp/ready')) + +template.setReadyCmd(waitForProcess('nginx')) +``` + +###### Implementation of + +`TemplateBuilder`.`setReadyCmd` + +### setStartCmd() + +```ts +setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set the start command and ready check. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `startCommand` | `string` | Command to run on startup | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setStartCmd( + 'node app.js', + 'curl http://localhost:8000/health' +) + +// Using ReadyCmd helpers +import { waitForPort, waitForURL } from 'e2b' + +template.setStartCmd( + 'python -m http.server 8000', + waitForPort(8000) +) + +template.setStartCmd( + 'npm start', + waitForURL('http://localhost:3000/health', 200) +) +``` + +###### Implementation of + +`TemplateBuilder`.`setStartCmd` + +### setUser() + +```ts +setUser(user: string): TemplateBuilder +``` + +Set the user for subsequent commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `user` | `string` | Username | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setUser('root') +``` + +###### Implementation of + +`TemplateBuilder`.`setUser` + +### setWorkdir() + +```ts +setWorkdir(workdir: PathLike): TemplateBuilder +``` + +Set the working directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `workdir` | `PathLike` | Working directory path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setWorkdir('/app') +``` + +###### Implementation of + +`TemplateBuilder`.`setWorkdir` + +### skipCache() + +```ts +skipCache(): this +``` + +Skip cache for all subsequent build instructions from this point. + +###### Returns + +`this` + +###### Example + +```ts +Template().skipCache().fromPythonImage('3') +``` + +###### Implementation of + +`TemplateBuilder`.`skipCache` + +### ~~aliasExists()~~ + +```ts +static aliasExists(alias: string, options?: ConnectionOpts): Promise +``` + +Check if a template with the given alias exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `alias` | `string` | Template alias to check | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`boolean`\> + +True if the alias exists, false otherwise + +###### Deprecated + +Use `exists` instead. + +###### Example + +```ts +const exists = await Template.aliasExists('my-python-env') +if (exists) { + console.log('Template exists!') +} +``` + +### assignTags() + +```ts +static assignTags( + targetName: string, + tags: string | string[], +options?: ConnectionOpts): Promise +``` + +Assign tag(s) to an existing template build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `targetName` | `string` | Template name in 'name:tag' format (the source build to tag from) | +| `tags` | `string` \| `string`[] | Tag or tags to assign | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`TemplateTagInfo`\> + +Tag info with buildId and assigned tags + +###### Example + +```ts +// Assign a single tag +await Template.assignTags('my-template:v1.0', 'production') + +// Assign multiple tags +await Template.assignTags('my-template:v1.0', ['production', 'stable']) +``` + +### build() + +###### Call Signature + +```ts +static build( + template: TemplateClass, + name: string, +options?: Omit): Promise +``` + +Build and deploy a template to E2B infrastructure. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `name` | `string` | Template name in 'name' or 'name:tag' format | +| `options`? | `Omit`\<`BuildOptions`, `"alias"`\> | Optional build configuration options | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Example + +```ts +const template = Template().fromPythonImage('3') + +// Build with single tag in name +await Template.build(template, 'my-python-env:v1.0') + +// Build with multiple tags +await Template.build(template, 'my-python-env', { tags: ['v1.0', 'stable'] }) +``` + +###### Call Signature + +```ts +static build(template: TemplateClass, options: BuildOptions): Promise +``` + +Build and deploy a template to E2B infrastructure. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `options` | `BuildOptions` | Build configuration options with alias (deprecated) | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Deprecated + +Use the overload with `name` parameter instead. + +###### Example + +```ts +// Deprecated: +await Template.build(template, { alias: 'my-python-env' }) + +// Use instead: +await Template.build(template, 'my-python-env:v1.0') +``` + +### buildInBackground() + +###### Call Signature + +```ts +static buildInBackground( + template: TemplateClass, + name: string, +options?: Omit): Promise +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `name` | `string` | Template name in 'name' or 'name:tag' format | +| `options`? | `Omit`\<`BuildOptions`, `"alias"`\> | Optional build configuration options | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Example + +```ts +const template = Template().fromPythonImage('3') + +// Build with single tag in name +const data = await Template.buildInBackground(template, 'my-python-env:v1.0') + +// Build with multiple tags +const data = await Template.buildInBackground(template, 'my-python-env', { tags: ['v1.0', 'stable'] }) +``` + +###### Call Signature + +```ts +static buildInBackground(template: TemplateClass, options: BuildOptions): Promise +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `options` | `BuildOptions` | Build configuration options with alias (deprecated) | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Deprecated + +Use the overload with `name` parameter instead. + +###### Example + +```ts +// Deprecated: +await Template.buildInBackground(template, { alias: 'my-python-env' }) + +// Use instead: +await Template.buildInBackground(template, 'my-python-env:v1.0') +``` + +### exists() + +```ts +static exists(name: string, options?: ConnectionOpts): Promise +``` + +Check if a template with the given name exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Template name to check | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`boolean`\> + +True if the name exists, false otherwise + +###### Example + +```ts +const exists = await Template.exists('my-python-env') +if (exists) { + console.log('Template exists!') +} +``` + +### getBuildStatus() + +```ts +static getBuildStatus(data: Pick, options?: GetBuildStatusOptions): Promise +``` + +Get the status of a build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `data` | `Pick`\<`BuildInfo`, `"buildId"` \| `"templateId"`\> | Build identifiers | +| `options`? | `GetBuildStatusOptions` | Authentication options | + +###### Returns + +`Promise`\<`TemplateBuildStatusResponse`\> + +###### Example + +```ts +const status = await Template.getBuildStatus(data, { logsOffset: 0 }) +``` + +### getTags() + +```ts +static getTags(templateId: string, options?: ConnectionOpts): Promise +``` + +Get all tags for a template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `templateId` | `string` | Template ID or name | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`TemplateTag`[]\> + +Array of tag details including tag name, buildId, and creation date + +###### Example + +```ts +const tags = await Template.getTags('my-template') +for (const tag of tags) { + console.log(`Tag: ${tag.tag}, Build: ${tag.buildId}, Created: ${tag.createdAt}`) +} +``` + +### removeTags() + +```ts +static removeTags( + name: string, + tags: string | string[], +options?: ConnectionOpts): Promise +``` + +Remove tag(s) from a template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Template name | +| `tags` | `string` \| `string`[] | Tag or tags to remove | +| `options`? | `ConnectionOpts` | Authentication options | + +###### Returns + +`Promise`\<`void`\> + +###### Example + +```ts +// Remove a single tag +await Template.removeTags('my-template', 'production') + +// Remove multiple tags from a template +await Template.removeTags('my-template', ['production', 'staging']) +``` + +### toDockerfile() + +```ts +static toDockerfile(template: TemplateClass): string +``` + +Convert a template to Dockerfile format. +Note: Templates based on other E2B templates cannot be converted to Dockerfile. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to convert | + +###### Returns + +`string` + +Dockerfile string representation + +###### Throws + +Error if the template is based on another E2B template + +### toJSON() + +```ts +static toJSON(template: TemplateClass, computeHashes: boolean): Promise +``` + +Convert a template to JSON representation. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `template` | `TemplateClass` | `undefined` | The template to convert | +| `computeHashes` | `boolean` | `true` | Whether to compute file hashes for cache invalidation | + +###### Returns + +`Promise`\<`string`\> + +JSON string representation of the template + +## Interfaces + +### TemplateBuilder + +Main builder state for constructing templates. +Provides methods for customizing the template environment. + +#### Methods + +### addMcpServer() + +```ts +addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder +``` + +Install MCP servers using mcp-gateway. +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | + +###### Returns + +`TemplateBuilder` + +###### Throws + +If the base template is not mcp-gateway + +###### Example + +```ts +template.addMcpServer('exa') +template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) +``` + +### aptInstall() + +```ts +aptInstall(packages: string | string[], options?: object): TemplateBuilder +``` + +Install Debian/Ubuntu packages using apt-get. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages` | `string` \| `string`[] | Package name(s) | +| `options`? | \{ `fixMissing`: `boolean`; `noInstallRecommends`: `boolean`; \} | - | +| `options.fixMissing`? | `boolean` | - | +| `options.noInstallRecommends`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.aptInstall('vim') +template.aptInstall(['git', 'curl', 'wget']) +template.aptInstall(['vim'], { noInstallRecommends: true }) +template.aptInstall(['vim'], { fixMissing: true }) +``` + +### betaDevContainerPrebuild() + +```ts +betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder +``` + +Prebuild a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') +``` + +### betaSetDevContainerStart() + +```ts +betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal +``` + +Start a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .startDevcontainer('/my-devcontainer') + +// Prebuild and start +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') + // Other instructions... + .betaSetDevContainerStart('/my-devcontainer') +``` + +### bunInstall() + +```ts +bunInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Bun packages using bun. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | \{ `dev`: `boolean`; `g`: `boolean`; \} | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.bunInstall('express') +template.bunInstall(['lodash', 'axios']) +template.bunInstall('tsx', { g: true }) +template.bunInstall('typescript', { dev: true }) +template.bunInstall() // Installs from package.json +``` + +### copy() + +```ts +copy( + src: PathLike | PathLike[], + dest: PathLike, + options?: object): TemplateBuilder +``` + +Copy files or directories into the template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` \| `PathLike`[] | Source path(s) | +| `dest` | `PathLike` | Destination path | +| `options`? | \{ `forceUpload`: `true`; `mode`: `number`; `resolveSymlinks`: `boolean`; `user`: `string`; \} | Copy options | +| `options.forceUpload`? | `true` | - | +| `options.mode`? | `number` | - | +| `options.resolveSymlinks`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copy('requirements.txt', '/home/user/') +template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) +``` + +### copyItems() + +```ts +copyItems(items: CopyItem[]): TemplateBuilder +``` + +Copy multiple items with individual options. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `items` | `CopyItem`[] | Array of copy items | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copyItems([ + { src: 'app.ts', dest: '/app/' }, + { src: 'config.ts', dest: '/app/', mode: 0o644 } +]) +``` + +### gitClone() + +```ts +gitClone( + url: string, + path?: PathLike, + options?: object): TemplateBuilder +``` + +Clone a Git repository. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | Repository URL | +| `path`? | `PathLike` | Optional destination path | +| `options`? | \{ `branch`: `string`; `depth`: `number`; `user`: `string`; \} | Clone options | +| `options.branch`? | `string` | - | +| `options.depth`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.gitClone('https://github.com/user/repo.git', '/app/repo') +template.gitClone('https://github.com/user/repo.git', undefined, { + branch: 'main', + depth: 1 +}) +template.gitClone('https://github.com/user/repo.git', '/app/repo', { + user: 'root' +}) +``` + +### makeDir() + +```ts +makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Create directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | +| `options`? | \{ `mode`: `number`; `user`: `string`; \} | Directory options | +| `options.mode`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeDir('/app/data', { mode: 0o755 }) +template.makeDir(['/app/logs', '/app/cache']) +template.makeDir('/app/data', { mode: 0o755, user: 'root' }) +``` + +### makeSymlink() + +```ts +makeSymlink( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Create a symbolic link. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path (target) | +| `dest` | `PathLike` | Destination path (symlink location) | +| `options`? | \{ `force`: `boolean`; `user`: `string`; \} | Symlink options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeSymlink('/usr/bin/python3', '/usr/bin/python') +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) +``` + +### npmInstall() + +```ts +npmInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Node.js packages using npm. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | \{ `dev`: `boolean`; `g`: `boolean`; \} | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.npmInstall('express') +template.npmInstall(['lodash', 'axios']) +template.npmInstall('tsx', { g: true }) +template.npmInstall('typescript', { dev: true }) +template.npmInstall() // Installs from package.json +``` + +### pipInstall() + +```ts +pipInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Python packages using pip. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | +| `options`? | \{ `g`: `boolean`; \} | Install options | +| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.pipInstall('numpy') // Installs globally (default) +template.pipInstall(['pandas', 'scikit-learn']) +template.pipInstall('numpy', { g: false }) // Install for user only +template.pipInstall() // Installs from current directory +``` + +### remove() + +```ts +remove(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Remove files or directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | +| `options`? | \{ `force`: `boolean`; `recursive`: `boolean`; `user`: `string`; \} | Remove options | +| `options.force`? | `boolean` | - | +| `options.recursive`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.remove('/tmp/cache', { recursive: true, force: true }) +template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) +``` + +### rename() + +```ts +rename( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Rename or move a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path | +| `dest` | `PathLike` | Destination path | +| `options`? | \{ `force`: `boolean`; `user`: `string`; \} | Rename options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) +``` + +### runCmd() + +###### Call Signature + +```ts +runCmd(command: string, options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `command` | `string` | Command string | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### Call Signature + +```ts +runCmd(commands: string[], options?: object): TemplateBuilder +``` + +Run multiple shell commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commands` | `string`[] | Array of command strings | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Call Signature + +```ts +runCmd(commandOrCommands: string | string[], options?: object): TemplateBuilder +``` + +Run command(s). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commandOrCommands` | `string` \| `string`[] | Command or commands | +| `options`? | \{ `user`: `string`; \} | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +### setEnvs() + +```ts +setEnvs(envs: Record): TemplateBuilder +``` + +Set environment variables. +Note: Environment variables defined here are available only during template build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `envs` | `Record`\<`string`, `string`\> | Environment variables | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) +``` + +### setReadyCmd() + +```ts +setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set or update the ready check command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setReadyCmd('curl http://localhost:8000/health') + +// Using ReadyCmd helpers +import { waitForPort, waitForFile, waitForProcess } from 'e2b' + +template.setReadyCmd(waitForPort(3000)) + +template.setReadyCmd(waitForFile('/tmp/ready')) + +template.setReadyCmd(waitForProcess('nginx')) +``` + +### setStartCmd() + +```ts +setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set the start command and ready check. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `startCommand` | `string` | Command to run on startup | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setStartCmd( + 'node app.js', + 'curl http://localhost:8000/health' +) + +// Using ReadyCmd helpers +import { waitForPort, waitForURL } from 'e2b' + +template.setStartCmd( + 'python -m http.server 8000', + waitForPort(8000) +) + +template.setStartCmd( + 'npm start', + waitForURL('http://localhost:3000/health', 200) +) +``` + +### setUser() + +```ts +setUser(user: string): TemplateBuilder +``` + +Set the user for subsequent commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `user` | `string` | Username | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setUser('root') +``` + +### setWorkdir() + +```ts +setWorkdir(workdir: PathLike): TemplateBuilder +``` + +Set the working directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `workdir` | `PathLike` | Working directory path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setWorkdir('/app') +``` + +### skipCache() + +```ts +skipCache(): this +``` + +Skip cache for all subsequent build instructions from this point. + +###### Returns + +`this` + +###### Example + +```ts +template.skipCache().runCmd('apt-get update') +``` + +## Type Aliases + +### BuildInfo + +```ts +type BuildInfo = object; +``` + +Information about a built template. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `alias` | `string` | First alias from the build (for backward compatibility). **Deprecated** Use `name` instead. | +| `buildId` | `string` | Build identifier. | +| `name` | `string` | Name of the template. | +| `tags` | `string`[] | Tags assigned to this build. | +| `templateId` | `string` | Template identifier. | + +*** + +### BuildOptions + +```ts +type BuildOptions = ConnectionOpts & BasicBuildOptions; +``` + +Options for building a template with authentication. + +*** + +### BuildStatusReason + +```ts +type BuildStatusReason = object; +``` + +Reason for the current build status (typically for errors). + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `logEntries` | `LogEntry`[] | Log entries related to the status reason. | +| `message` | `string` | Message with the status reason. | +| `step`? | `string` | Step that failed. | + +*** + +### CopyItem + +```ts +type CopyItem = object; +``` + +Configuration for a single file/directory copy operation. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `dest` | `PathLike` | +| `forceUpload`? | `true` | +| `mode`? | `number` | +| `resolveSymlinks`? | `boolean` | +| `src` | `PathLike` \| `PathLike`[] | +| `user`? | `string` | + +*** + +### GetBuildStatusOptions + +```ts +type GetBuildStatusOptions = ConnectionOpts & object; +``` + +Options for getting build status. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `logsOffset`? | `number` | + +*** + +### McpServerName + +```ts +type McpServerName = keyof McpServer; +``` + +MCP server names that can be installed. + +*** + +### TemplateBuildStatus + +```ts +type TemplateBuildStatus = "building" | "waiting" | "ready" | "error"; +``` + +Status of a template build. + +*** + +### TemplateBuildStatusResponse + +```ts +type TemplateBuildStatusResponse = object; +``` + +Response from getting build status. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `buildID` | `string` | Build identifier. | +| `logEntries` | `LogEntry`[] | Build log entries. | +| `logs` | `string`[] | Build logs (raw strings). **Deprecated** Use `logEntries` instead. | +| `reason`? | `BuildStatusReason` | Reason for the current status (typically for errors). | +| `status` | `TemplateBuildStatus` | Current status of the build. | +| `templateID` | `string` | Template identifier. | + +*** + +### TemplateClass + +```ts +type TemplateClass = TemplateBuilder | TemplateFinal; +``` + +Type representing a template in any state (builder or final). + +*** + +### TemplateTag + +```ts +type TemplateTag = object; +``` + +Detailed information about a single template tag. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `buildId` | `string` | Build identifier associated with this tag. | +| `createdAt` | `Date` | When this tag was assigned. | +| `tag` | `string` | Name of the tag. | + +*** + +### TemplateTagInfo + +```ts +type TemplateTagInfo = object; +``` + +Information about assigned template tags. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `buildId` | `string` | Build identifier associated with this tag. | +| `tags` | `string`[] | Assigned tags of the template. | + +## Functions + +### Template() + +```ts +function Template(options?: TemplateOptions): TemplateFromImage +``` + +Create a new E2B template builder instance. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options`? | `TemplateOptions` | Optional configuration for the template builder | + +#### Returns + +`TemplateFromImage` + +A new template builder instance + +#### Example + +```ts +import { Template } from 'e2b' + +const template = Template() + .fromPythonImage('3') + .copy('requirements.txt', '/app/') + .pipInstall() + +await Template.build(template, 'my-python-app:v1.0') +``` diff --git a/docs/sdk-reference/js-sdk/v2.18.0/volume.mdx b/docs/sdk-reference/js-sdk/v2.18.0/volume.mdx new file mode 100644 index 00000000..a1487601 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.18.0/volume.mdx @@ -0,0 +1,621 @@ +--- +sidebarTitle: "Volume" +--- + +### VolumeFileType + +File type enum. + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `DIRECTORY` | `"directory"` | +| `FILE` | `"file"` | +| `SYMLINK` | `"symlink"` | +| `UNKNOWN` | `"unknown"` | + +## Classes + +### Volume + +Module for interacting with E2B volumes. + +Create a `Volume` instance to interact with a volume by its ID, +or use the static methods to manage volumes. + +#### Constructors + +```ts +new Volume( + volumeId: string, + name: string, + token: string, + domain?: string, + debug?: boolean): Volume +``` + +Create a local Volume instance with no API call. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `volumeId` | `string` | volume ID. | +| `name` | `string` | volume name. | +| `token` | `string` | volume auth token. | +| `domain`? | `string` | domain for the volume API. | +| `debug`? | `boolean` | whether to use debug mode. | + +###### Returns + +`Volume` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `debug?` | `readonly` | `boolean` | Whether to use debug mode (connects to local volume API server). | +| `domain?` | `readonly` | `string` | Domain used for constructing the volume API URL. | +| `name` | `readonly` | `string` | Volume name. | +| `token` | `readonly` | `string` | Volume auth token. | +| `volumeId` | `readonly` | `string` | Volume ID. | + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: VolumeApiOpts): Promise +``` + +Check whether a file or directory exists. + +Uses getInfo under the hood. Returns `true` if the path exists, +`false` if it does not (404). Other errors are rethrown. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file or directory. | +| `opts`? | `VolumeApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the path exists, `false` otherwise. + +### getInfo() + +```ts +getInfo(path: string, opts?: VolumeApiOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file or directory. | +| `opts`? | `VolumeApiOpts` | connection options. | + +###### Returns + +`Promise`\<`VolumeEntryStat`\> + +information about the entry. + +### list() + +```ts +list(path: string, opts?: VolumeApiOpts & object): Promise +``` + +List directory contents. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `VolumeApiOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`VolumeEntryStat`[]\> + +list of entries in the directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: VolumeMetadataOptions & object & VolumeApiOpts): Promise +``` + +Create a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory to create. | +| `opts`? | `VolumeMetadataOptions` & `object` & `VolumeApiOpts` | connection options. | + +###### Returns + +`Promise`\<`VolumeEntryStat`\> + +### readFile() + +###### Call Signature + +```ts +readFile(path: string, opts?: VolumeApiOpts & 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`? | `VolumeApiOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### Call Signature + +```ts +readFile(path: string, opts?: VolumeApiOpts & 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`? | `VolumeApiOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +file content as `Uint8Array` + +###### Call Signature + +```ts +readFile(path: string, opts?: VolumeApiOpts & 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`? | `VolumeApiOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### Call Signature + +```ts +readFile(path: string, opts?: VolumeApiOpts & 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`? | `VolumeApiOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: VolumeApiOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file or directory to remove. | +| `opts`? | `VolumeApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### updateMetadata() + +```ts +updateMetadata( + path: string, + metadata: VolumeMetadataOptions, +opts?: VolumeApiOpts): Promise +``` + +Update file or directory metadata. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file or directory. | +| `metadata` | `VolumeMetadataOptions` | metadata to update (uid, gid, mode). | +| `opts`? | `VolumeApiOpts` | connection options. | + +###### Returns + +`Promise`\<`VolumeEntryStat`\> + +updated entry information. + +### writeFile() + +```ts +writeFile( + path: string, + data: + | string + | ArrayBuffer + | Blob + | ReadableStream>, +opts?: VolumeMetadataOptions & object & VolumeApiOpts): 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. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `data` | \| `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `VolumeMetadataOptions` & `object` & `VolumeApiOpts` | connection options. | + +###### Returns + +`Promise`\<`VolumeEntryStat`\> + +information about the written file + +### connect() + +```ts +static connect(volumeId: string, opts?: ConnectionOpts): Promise +``` + +Connect to an existing volume by ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `volumeId` | `string` | volume ID. | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`Volume`\> + +Volume instance. + +### create() + +```ts +static create(name: string, opts?: ConnectionOpts): Promise +``` + +Create a new volume. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | name of the volume. | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`Volume`\> + +new Volume instance. + +### destroy() + +```ts +static destroy(volumeId: string, opts?: ConnectionOpts): Promise +``` + +Destroy a volume. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `volumeId` | `string` | volume ID. | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +### getInfo() + +```ts +static getInfo(volumeId: string, opts?: ConnectionOpts): Promise +``` + +Get volume information. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `volumeId` | `string` | volume ID. | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`VolumeAndToken`\> + +volume information. + +### list() + +```ts +static list(opts?: ConnectionOpts): Promise +``` + +List all volumes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`VolumeInfo`[]\> + +list of volume information. + +*** + +### VolumeConnectionConfig + +#### Constructors + +```ts +new VolumeConnectionConfig(volume: Volume, opts?: VolumeApiOpts): VolumeConnectionConfig +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `volume` | `Volume` | +| `opts`? | `VolumeApiOpts` | + +###### Returns + +`VolumeConnectionConfig` + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `apiUrl` | `readonly` | `string` | +| `debug` | `readonly` | `boolean` | +| `domain` | `readonly` | `string` | +| `headers?` | `readonly` | `Record`\<`string`, `string`\> | +| `logger?` | `readonly` | `Logger` | +| `requestTimeoutMs?` | `readonly` | `number` | +| `token?` | `readonly` | `string` | + +#### Methods + +### getSignal() + +```ts +getSignal(requestTimeoutMs?: number): undefined | AbortSignal +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `requestTimeoutMs`? | `number` | + +###### Returns + +`undefined` \| `AbortSignal` + +## Interfaces + +### VolumeApiOpts + +#### Properties + +### domain? + +```ts +optional domain: string; +``` + +Domain to use for the volume API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.app` + +### 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. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### token? + +```ts +optional token: string; +``` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +## Type Aliases + +### VolumeAndToken + +```ts +type VolumeAndToken = VolumeInfo & object; +``` + +Information about a volume and its auth token. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `token` | `string` | Volume auth token. | + +*** + +### VolumeEntryStat + +```ts +type VolumeEntryStat = Omit & object; +``` + +Volume entry stat with dates converted to Date objects. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `atime` | `Date` | Access time as a Date object. | +| `ctime` | `Date` | Creation time as a Date object. | +| `mtime` | `Date` | Modification time as a Date object. | +| `type` | `VolumeFileType` | File type. | + +*** + +### VolumeInfo + +```ts +type VolumeInfo = object; +``` + +Information about a volume. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Volume name. | +| `volumeId` | `string` | Volume ID. | + +*** + +### VolumeMetadataOptions + +```ts +type VolumeMetadataOptions = object; +``` + +Options for updating file metadata. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `gid`? | `number` | Group ID of the file or directory. | +| `mode`? | `number` | Mode of the file or directory. | +| `uid`? | `number` | User ID of the file or directory. | + +*** + +### VolumeWriteOptions + +```ts +type VolumeWriteOptions = VolumeMetadataOptions & object; +``` + +Options for file and directory operations. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `force`? | `boolean` | For makeDir: Create parent directories if they don't exist. For writeFile: Force overwrite of an existing file. | diff --git a/docs/sdk-reference/python-sdk/v2.17.0/exceptions.mdx b/docs/sdk-reference/python-sdk/v2.17.0/exceptions.mdx new file mode 100644 index 00000000..8be3b68a --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.17.0/exceptions.mdx @@ -0,0 +1,160 @@ +--- +sidebarTitle: "Exceptions" +--- + + + + + + +## SandboxException + +```python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + + +## TimeoutException + +```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 +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + + +## NotEnoughSpaceException + +```python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + + +## NotFoundException + +```python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + +.. deprecated:: + Use :class:`FileNotFoundException` or :class:`SandboxNotFoundException` instead. + This class will be removed in the next major version. + + + +## FileNotFoundException + +```python +class FileNotFoundException(NotFoundException) +``` + +Raised when a file or directory is not found inside a sandbox. + + + +## SandboxNotFoundException + +```python +class SandboxNotFoundException(NotFoundException) +``` + +Raised when a sandbox is not found (e.g. it doesn't exist or is no longer running). + + + +## AuthenticationException + +```python +class AuthenticationException(Exception) +``` + +Raised when authentication fails. + + + +## GitAuthException + +```python +class GitAuthException(AuthenticationException) +``` + +Raised when git authentication fails. + + + +## GitUpstreamException + +```python +class GitUpstreamException(SandboxException) +``` + +Raised when git upstream tracking is missing. + + + +## TemplateException + +```python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + + +## RateLimitException + +```python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + + + +## BuildException + +```python +class BuildException(Exception) +``` + +Raised when the build fails. + + + +## FileUploadException + +```python +class FileUploadException(BuildException) +``` + +Raised when the file upload fails. diff --git a/docs/sdk-reference/python-sdk/v2.17.0/logger.mdx b/docs/sdk-reference/python-sdk/v2.17.0/logger.mdx new file mode 100644 index 00000000..16f9c54e --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.17.0/logger.mdx @@ -0,0 +1,105 @@ +--- +sidebarTitle: "Logger" +--- + + + + + + +## LogEntry + +```python +@dataclass +class LogEntry() +``` + +Represents a single log entry from the template build process. + + + +## LogEntryStart + +```python +@dataclass +class LogEntryStart(LogEntry) +``` + +Special log entry indicating the start of a build process. + + + +## LogEntryEnd + +```python +@dataclass +class LogEntryEnd(LogEntry) +``` + +Special log entry indicating the end of a build process. + + + +### TIMER\_UPDATE\_INTERVAL\_MS + +Default minimum log level to display. + + + +### DEFAULT\_LEVEL + +Colored labels for each log level. + + + +### levels + +Numeric ordering of log levels for comparison (lower = less severe). + + + +### set\_interval + +```python +def set_interval(func, interval) +``` + +Returns a stop function that can be called to cancel the interval. + +Similar to JavaScript's setInterval. + +**Arguments**: + +- `func`: Function to execute at each interval +- `interval`: Interval duration in **seconds** + +**Returns**: + +Stop function that can be called to cancel the interval + + + +### default\_build\_logger + +```python +def default_build_logger( + min_level: Optional[LogEntryLevel] = None +) -> Callable[[LogEntry], None] +``` + +Create a default build logger with animated timer display. + +**Arguments**: + +- `min_level`: Minimum log level to display (default: 'info') + +**Returns**: + +Logger function that accepts LogEntry instances +Example +```python +from e2b import Template, default_build_logger + +template = Template().from_python_image() + +``` diff --git a/docs/sdk-reference/python-sdk/v2.17.0/readycmd.mdx b/docs/sdk-reference/python-sdk/v2.17.0/readycmd.mdx new file mode 100644 index 00000000..b4083b62 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.17.0/readycmd.mdx @@ -0,0 +1,167 @@ +--- +sidebarTitle: "Readycmd" +--- + + + + + + +## ReadyCmd + +```python +class ReadyCmd() +``` + +Wrapper class for ready check commands. + + + +### wait\_for\_port + +```python +def wait_for_port(port: int) +``` + +Wait for a port to be listening. + +Uses `ss` command to check if a port is open and listening. + +**Arguments**: + +- `port`: Port number to wait for + +**Returns**: + +ReadyCmd that checks for the port +Example +```python +from e2b import Template, wait_for_port + +template = ( + Template() + .from_python_image() + .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) +) +``` + + + +### wait\_for\_url + +```python +def wait_for_url(url: str, status_code: int = 200) +``` + +Wait for a URL to return a specific HTTP status code. + +Uses `curl` to make HTTP requests and check the response status. + +**Arguments**: + +- `url`: URL to check (e.g., 'http://localhost:3000/health') +- `status_code`: Expected HTTP status code (default: 200) + +**Returns**: + +ReadyCmd that checks the URL +Example +```python +from e2b import Template, wait_for_url + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) +) +``` + + + +### wait\_for\_process + +```python +def wait_for_process(process_name: str) +``` + +Wait for a process with a specific name to be running. + +Uses `pgrep` to check if a process exists. + +**Arguments**: + +- `process_name`: Name of the process to wait for + +**Returns**: + +ReadyCmd that checks for the process +Example +```python +from e2b import Template, wait_for_process + +template = ( + Template() + .from_base_image() + .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) +) +``` + + + +### wait\_for\_file + +```python +def wait_for_file(filename: str) +``` + +Wait for a file to exist. + +Uses shell test command to check file existence. + +**Arguments**: + +- `filename`: Path to the file to wait for + +**Returns**: + +ReadyCmd that checks for the file +Example +```python +from e2b import Template, wait_for_file + +template = ( + Template() + .from_base_image() + .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) +) +``` + + + +### wait\_for\_timeout + +```python +def wait_for_timeout(timeout: int) +``` + +Wait for a specified timeout before considering the sandbox ready. + +Uses `sleep` command to wait for a fixed duration. + +**Arguments**: + +- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) + +**Returns**: + +ReadyCmd that waits for the specified duration +Example +```python +from e2b import Template, wait_for_timeout + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds +) +``` diff --git a/docs/sdk-reference/python-sdk/v2.17.0/sandbox_async.mdx b/docs/sdk-reference/python-sdk/v2.17.0/sandbox_async.mdx new file mode 100644 index 00000000..a21bda09 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.17.0/sandbox_async.mdx @@ -0,0 +1,2282 @@ +--- +sidebarTitle: "Sandbox Async" +--- + + + + + + +## AsyncSandbox + +```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](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### git + +```python +@property +def git() -> Git +``` + +Module for running git operations in the sandbox. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```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 +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + + +### create + +```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: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + network: Optional[SandboxNetworkOpts] = None, + lifecycle: Optional[SandboxLifecycle] = None, + **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`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. +- `mcp`: MCP server to enable in the sandbox +- `network`: Sandbox network configuration +- `lifecycle`: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` (default) or ``"pause"``; ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout="pause"``). Example: ``{"on_timeout": "pause", "auto_resume": True}`` + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```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** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await sandbox.pause() + +same_sandbox = await sandbox.connect() +``` + + + +### connect + +```python +@overload +@staticmethod +async def connect(sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> "AsyncSandbox" +``` + +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** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await AsyncSandbox.pause(sandbox.sandbox_id) + +same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id) +``` + + + +### connect + +```python +@class_method_variant("_cls_connect_sandbox") +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** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await sandbox.pause() + +same_sandbox = await sandbox.connect() +``` + + + +### kill + +```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 +@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 +@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 +@overload +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +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 +@overload +@staticmethod +async def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +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 +@class_method_variant("_cls_set_timeout") +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +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 +@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 +@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 +@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 +@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 +@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 +@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 +@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, + mcp: Optional[McpServer] = None, + **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`. +- `mcp`: MCP server to enable in the sandbox + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### pause + +```python +@overload +async def pause(**opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### pause + +```python +@overload +@staticmethod +async def pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### pause + +```python +@class_method_variant("_cls_pause") +async def pause(**opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### beta\_pause + +```python +@class_method_variant("_cls_pause") +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +:deprecated: Use `pause()` instead. + + + +### create\_snapshot + +```python +@overload +async def create_snapshot(**opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshot_id` with `AsyncSandbox.create(snapshot_id)` to create a new sandbox from the snapshot. + +**Returns**: + +Snapshot information including the snapshot ID + + + +### create\_snapshot + +```python +@overload +@staticmethod +async def create_snapshot(sandbox_id: str, + **opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot from the sandbox specified by sandbox ID. + +The sandbox will be paused while the snapshot is being created. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Snapshot information including the snapshot ID + + + +### create\_snapshot + +```python +@class_method_variant("_cls_create_snapshot") +async def create_snapshot(**opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshot_id` with `AsyncSandbox.create(snapshot_id)` to create a new sandbox from the snapshot. + +**Returns**: + +Snapshot information including the snapshot ID + + + +### list\_snapshots + +```python +@overload +def list_snapshots(limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSnapshotPaginator +``` + +List snapshots for this sandbox. + +**Arguments**: + +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### list\_snapshots + +```python +@overload +@staticmethod +def list_snapshots(sandbox_id: Optional[str] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSnapshotPaginator +``` + +List all snapshots. + +**Arguments**: + +- `sandbox_id`: Filter snapshots by source sandbox ID +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### list\_snapshots + +```python +@class_method_variant("_cls_list_snapshots") +def list_snapshots(limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSnapshotPaginator +``` + +List snapshots for this sandbox. + +**Arguments**: + +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### delete\_snapshot + +```python +@staticmethod +async def delete_snapshot(snapshot_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Delete a snapshot. + +**Arguments**: + +- `snapshot_id`: Snapshot ID + +**Returns**: + +`True` if the snapshot was deleted, `False` if it was not found + + + +### get\_mcp\_token + +```python +async def get_mcp_token() -> Optional[str] +``` + +Get the MCP token for the sandbox. + +**Returns**: + +MCP token for the sandbox, or None if MCP is not enabled. + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxBase) +``` + + + +### list + +```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 + + + + + + + + + +## AsyncSandboxPaginator + +```python +class AsyncSandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python +paginator = AsyncSandbox.list() + +while paginator.has_next: + sandboxes = await paginator.next_items() + print(sandboxes) +``` + + + +### next\_items + +```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 + + + +## AsyncSnapshotPaginator + +```python +class AsyncSnapshotPaginator(SnapshotPaginatorBase) +``` + +Paginator for listing snapshots. + +**Example**: + +```python +paginator = AsyncSandbox.list_snapshots() + +while paginator.has_next: + snapshots = await paginator.next_items() + print(snapshots) +``` + + + +### next\_items + +```python +async def next_items() -> List[SnapshotInfo] +``` + +Returns the next page of snapshots. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of snapshots + + + + + + +## Git + +```python +class Git() +``` + +Async module for running git operations in the sandbox. + + + +### \_\_init\_\_ + +```python +def __init__(commands: Commands) -> None +``` + +Create a Git helper bound to the sandbox command runner. + +**Arguments**: + +- `commands`: Command runner used to execute git commands + + + +### clone + +```python +async def clone(url: str, + path: Optional[str] = None, + branch: Optional[str] = None, + depth: Optional[int] = None, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None, + dangerously_store_credentials: bool = False) +``` + +Clone a git repository into the sandbox. + +**Arguments**: + +- `url`: Git repository URL +- `path`: Destination path for the clone +- `branch`: Branch to check out +- `depth`: If set, perform a shallow clone with this depth +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** +- `dangerously_store_credentials`: Store credentials in the cloned repository when True + +**Returns**: + +Command result from the command runner + + + +### init + +```python +async def init(path: str, + bare: bool = False, + initial_branch: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Initialize a new git repository. + +**Arguments**: + +- `path`: Destination path for the repository +- `bare`: Create a bare repository when True +- `initial_branch`: Initial branch name (for example, "main") +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### remote\_add + +```python +async def remote_add(path: str, + name: str, + url: str, + fetch: bool = False, + overwrite: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Add (or update) a remote for a repository. + +**Arguments**: + +- `path`: Repository path +- `name`: Remote name (for example, "origin") +- `url`: Remote URL +- `fetch`: Fetch the remote after adding it when True +- `overwrite`: Overwrite the remote URL if it already exists when True +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### remote\_get + +```python +async def remote_get(path: str, + name: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Optional[str] +``` + +Get the URL for a git remote. + +Returns `None` when the remote does not exist. + +**Arguments**: + +- `path`: Repository path +- `name`: Remote name (for example, "origin") +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Remote URL if present, otherwise `None` + + + +### status + +```python +async def status(path: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> GitStatus +``` + +Get repository status information. + +**Arguments**: + +- `path`: Repository path +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Parsed git status + + + +### branches + +```python +async def branches(path: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> GitBranches +``` + +List branches in a repository. + +**Arguments**: + +- `path`: Repository path +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Parsed branch list + + + +### create\_branch + +```python +async def create_branch(path: str, + branch: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Create and check out a new branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to create +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### checkout\_branch + +```python +async def checkout_branch(path: str, + branch: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Check out an existing branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to check out +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### delete\_branch + +```python +async def delete_branch(path: str, + branch: str, + force: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Delete a branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to delete +- `force`: Force deletion with `-D` when `True` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### add + +```python +async def add(path: str, + files: Optional[List[str]] = None, + all: bool = True, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Stage files for commit. + +**Arguments**: + +- `path`: Repository path +- `files`: Files to add; when omitted, adds the current directory +- `all`: When `True` and `files` is omitted, stage all changes +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### commit + +```python +async def commit(path: str, + message: str, + author_name: Optional[str] = None, + author_email: Optional[str] = None, + allow_empty: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Create a commit in the repository. + +**Arguments**: + +- `path`: Repository path +- `message`: Commit message +- `author_name`: Commit author name +- `author_email`: Commit author email +- `allow_empty`: Allow empty commits when `True` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### reset + +```python +async def reset(path: str, + mode: Optional[str] = None, + target: Optional[str] = None, + paths: Optional[List[str]] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Reset the current HEAD to a specified state. + +**Arguments**: + +- `path`: Repository path +- `mode`: Reset mode (soft, mixed, hard, merge, keep) +- `target`: Commit, branch, or ref to reset to (defaults to HEAD) +- `paths`: Paths to reset +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### restore + +```python +async def restore(path: str, + paths: List[str], + staged: Optional[bool] = None, + worktree: Optional[bool] = None, + source: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Restore working tree files or unstage changes. + +**Arguments**: + +- `path`: Repository path +- `paths`: Paths to restore (use ["."] for all) +- `staged`: When True, restore the index (unstage) +- `worktree`: When True, restore working tree files +- `source`: Restore from the given source (commit, branch, or ref) +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### push + +```python +async def push(path: str, + remote: Optional[str] = None, + branch: Optional[str] = None, + set_upstream: bool = True, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Push commits to a remote. + +**Arguments**: + +- `path`: Repository path +- `remote`: Remote name, e.g. `origin` +- `branch`: Branch name to push +- `set_upstream`: Set upstream tracking when `True` +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### pull + +```python +async def pull(path: str, + remote: Optional[str] = None, + branch: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Pull changes from a remote. + +**Arguments**: + +- `path`: Repository path +- `remote`: Remote name, e.g. `origin` +- `branch`: Branch name to pull +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### set\_config + +```python +async def set_config(key: str, + value: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Set a git config value. + +Use `scope="local"` together with `path` to configure a specific repository. + +**Arguments**: + +- `key`: Git config key (e.g. `pull.rebase`) +- `value`: Git config value +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### get\_config + +```python +async def get_config(key: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Optional[str] +``` + +Get a git config value. + +Returns `None` when the key is not set in the requested scope. + +**Arguments**: + +- `key`: Git config key (e.g. `pull.rebase`) +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Config value if present, otherwise `None` + + + +### dangerously\_authenticate + +```python +async def dangerously_authenticate(username: str, + password: str, + host: str = "github.com", + protocol: str = "https", + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Dangerously authenticate git globally via the credential helper. + +This persists credentials in the credential store and may be accessable to agents running on the sandbox. +Prefer short-lived credentials when possible. + +**Arguments**: + +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `host`: Host to authenticate for, defaults to `github.com` +- `protocol`: Protocol to authenticate for, defaults to `https` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### configure\_user + +```python +async def configure_user(name: str, + email: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Configure git user name and email. + +**Arguments**: + +- `name`: Git user name +- `email`: Git user email +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + + + + +## AsyncWatchHandle + +```python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + + +### stop + +```python +async def stop() +``` + +Stop watching the directory. + + + + + + +## Filesystem + +```python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Optional[Username] = None, + 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 +@overload +async def read(path: str, + format: Literal["bytes"], + user: Optional[Username] = None, + 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 +@overload +async def read( + path: str, + format: Literal["stream"], + user: Optional[Username] = None, + 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 +async def write(path: str, + data: Union[str, bytes, IO], + user: Optional[Username] = None, + 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 +async def write_files( + files: List[WriteEntry], + user: Optional[Username] = None, + 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 +async def list(path: str, + depth: Optional[int] = 1, + user: Optional[Username] = None, + 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 +async def exists(path: str, + user: Optional[Username] = None, + 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 +async def get_info(path: str, + user: Optional[Username] = None, + 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 +async def remove(path: str, + user: Optional[Username] = None, + 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 +async def rename(old_path: str, + new_path: str, + user: Optional[Username] = None, + 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 +async def make_dir(path: str, + user: Optional[Username] = None, + 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 +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Optional[Username] = None, + 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 +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### stdout + +```python +@property +def stdout() +``` + +Command stdout output. + + + +### stderr + +```python +@property +def stderr() +``` + +Command stderr output. + + + +### error + +```python +@property +def error() +``` + +Command execution error message. + + + +### exit\_code + +```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 +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 +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 +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 +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```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 +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 +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Optional[Username] = None, + 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 + + + +### connect + +```python +async def connect( + pid: int, + on_data: OutputHandler[PtyOutput], + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Connect to a running PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY to connect to. You can get the list of running PTYs using `sandbox.pty.list()`. +- `on_data`: Callback to handle PTY data +- `timeout`: Timeout for the PTY connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```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 +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```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 +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 +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 +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + stdin: Optional[bool] = 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 +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `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 +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + stdin: Optional[bool] = 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 +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `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 +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 diff --git a/docs/sdk-reference/python-sdk/v2.17.0/sandbox_sync.mdx b/docs/sdk-reference/python-sdk/v2.17.0/sandbox_sync.mdx new file mode 100644 index 00000000..916a8e62 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.17.0/sandbox_sync.mdx @@ -0,0 +1,2235 @@ +--- +sidebarTitle: "Sandbox Sync" +--- + + + + + + +## Sandbox + +```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](https://e2b.dev/docs). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import Sandbox + +sandbox = Sandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### git + +```python +@property +def git() -> Git +``` + +Module for running git operations in the sandbox. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +:deprecated: This constructor is deprecated + +Use `Sandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```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 +sandbox = Sandbox.create() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + + +### create + +```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, + mcp: Optional[McpServer] = None, + network: Optional[SandboxNetworkOpts] = None, + lifecycle: Optional[SandboxLifecycle] = None, + **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`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. +- `mcp`: MCP server to enable in the sandbox +- `network`: Sandbox network configuration +- `lifecycle`: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` (default) or ``"pause"``; ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout="pause"``). Example: ``{"on_timeout": "pause", "auto_resume": True}`` + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```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** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +sandbox.pause() + +same_sandbox = sandbox.connect() + + + +### connect + +```python +@overload +@staticmethod +def connect(sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> "Sandbox" +``` + +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**. +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +Sandbox.pause(sandbox.sandbox_id) + +same_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + + +### connect + +```python +@class_method_variant("_cls_connect_sandbox") +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**. +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +sandbox.pause() + +same_sandbox = sandbox.connect() +``` + + + +### kill + +```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 +@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 +@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 +@overload +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +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 +@overload +@staticmethod +def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +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 +@class_method_variant("_cls_set_timeout") +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +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 +@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 +@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 +@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 +@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 +@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 +@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 +@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, + mcp: Optional[McpServer] = None, + **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`. +- `mcp`: MCP server to enable in the sandbox + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### pause + +```python +@overload +def pause(**opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox. + + + +### pause + +```python +@overload +@staticmethod +def pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + + + +### pause + +```python +@class_method_variant("_cls_pause") +def pause(**opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### beta\_pause + +```python +@class_method_variant("_cls_pause") +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +:deprecated: Use `pause()` instead. + + + +### create\_snapshot + +```python +@overload +def create_snapshot(**opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshot_id` with `Sandbox.create(snapshot_id)` to create a new sandbox from the snapshot. + +**Returns**: + +Snapshot information including the snapshot ID + + + +### create\_snapshot + +```python +@overload +@staticmethod +def create_snapshot(sandbox_id: str, + **opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot from the sandbox specified by sandbox ID. + +The sandbox will be paused while the snapshot is being created. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Snapshot information including the snapshot ID + + + +### create\_snapshot + +```python +@class_method_variant("_cls_create_snapshot") +def create_snapshot(**opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshot_id` with `Sandbox.create(snapshot_id)` to create a new sandbox from the snapshot. + +**Returns**: + +Snapshot information including the snapshot ID + + + +### list\_snapshots + +```python +@overload +def list_snapshots(limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SnapshotPaginator +``` + +List snapshots for this sandbox. + +**Arguments**: + +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### list\_snapshots + +```python +@overload +@staticmethod +def list_snapshots(sandbox_id: Optional[str] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SnapshotPaginator +``` + +List all snapshots. + +**Arguments**: + +- `sandbox_id`: Filter snapshots by source sandbox ID +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### list\_snapshots + +```python +@class_method_variant("_cls_list_snapshots") +def list_snapshots(limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SnapshotPaginator +``` + +List snapshots for this sandbox. + +**Arguments**: + +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### delete\_snapshot + +```python +@staticmethod +def delete_snapshot(snapshot_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Delete a snapshot. + +**Arguments**: + +- `snapshot_id`: Snapshot ID + +**Returns**: + +`True` if the snapshot was deleted, `False` if it was not found + + + +### get\_mcp\_token + +```python +def get_mcp_token() -> Optional[str] +``` + +Get the MCP token for the sandbox. + +**Returns**: + +MCP token for the sandbox, or None if MCP is not enabled. + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxBase) +``` + + + +### list + +```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 + + + + + + +## SandboxPaginator + +```python +class SandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python +paginator = Sandbox.list() + +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) +``` + + + +### next\_items + +```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 + + + +## SnapshotPaginator + +```python +class SnapshotPaginator(SnapshotPaginatorBase) +``` + +Paginator for listing snapshots. + +**Example**: + +```python +paginator = Sandbox.list_snapshots() + +while paginator.has_next: + snapshots = paginator.next_items() + print(snapshots) +``` + + + +### next\_items + +```python +def next_items() -> List[SnapshotInfo] +``` + +Returns the next page of snapshots. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of snapshots + + + + + + +## Git + +```python +class Git() +``` + +Module for running git operations in the sandbox. + + + +### \_\_init\_\_ + +```python +def __init__(commands: Commands) -> None +``` + +Create a Git helper bound to the sandbox command runner. + +**Arguments**: + +- `commands`: Command runner used to execute git commands + + + +### clone + +```python +def clone(url: str, + path: Optional[str] = None, + branch: Optional[str] = None, + depth: Optional[int] = None, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None, + dangerously_store_credentials: bool = False) +``` + +Clone a git repository into the sandbox. + +**Arguments**: + +- `url`: Git repository URL +- `path`: Destination path for the clone +- `branch`: Branch to check out +- `depth`: If set, perform a shallow clone with this depth +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** +- `dangerously_store_credentials`: Store credentials in the cloned repository when True + +**Returns**: + +Command result from the command runner + + + +### init + +```python +def init(path: str, + bare: bool = False, + initial_branch: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Initialize a new git repository. + +**Arguments**: + +- `path`: Destination path for the repository +- `bare`: Create a bare repository when True +- `initial_branch`: Initial branch name (for example, "main") +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### remote\_add + +```python +def remote_add(path: str, + name: str, + url: str, + fetch: bool = False, + overwrite: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Add (or update) a remote for a repository. + +**Arguments**: + +- `path`: Repository path +- `name`: Remote name (for example, "origin") +- `url`: Remote URL +- `fetch`: Fetch the remote after adding it when True +- `overwrite`: Overwrite the remote URL if it already exists when True +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### remote\_get + +```python +def remote_get(path: str, + name: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Optional[str] +``` + +Get the URL for a git remote. + +Returns `None` when the remote does not exist. + +**Arguments**: + +- `path`: Repository path +- `name`: Remote name (for example, "origin") +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Remote URL if present, otherwise `None` + + + +### status + +```python +def status(path: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> GitStatus +``` + +Get repository status information. + +**Arguments**: + +- `path`: Repository path +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Parsed git status + + + +### branches + +```python +def branches(path: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> GitBranches +``` + +List branches in a repository. + +**Arguments**: + +- `path`: Repository path +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Parsed branch list + + + +### create\_branch + +```python +def create_branch(path: str, + branch: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Create and check out a new branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to create +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### checkout\_branch + +```python +def checkout_branch(path: str, + branch: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Check out an existing branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to check out +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### delete\_branch + +```python +def delete_branch(path: str, + branch: str, + force: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Delete a branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to delete +- `force`: Force deletion with `-D` when `True` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### add + +```python +def add(path: str, + files: Optional[List[str]] = None, + all: bool = True, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Stage files for commit. + +**Arguments**: + +- `path`: Repository path +- `files`: Files to add; when omitted, adds the current directory +- `all`: When `True` and `files` is omitted, stage all changes +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### commit + +```python +def commit(path: str, + message: str, + author_name: Optional[str] = None, + author_email: Optional[str] = None, + allow_empty: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Create a commit in the repository. + +**Arguments**: + +- `path`: Repository path +- `message`: Commit message +- `author_name`: Commit author name +- `author_email`: Commit author email +- `allow_empty`: Allow empty commits when `True` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### reset + +```python +def reset(path: str, + mode: Optional[str] = None, + target: Optional[str] = None, + paths: Optional[List[str]] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Reset the current HEAD to a specified state. + +**Arguments**: + +- `path`: Repository path +- `mode`: Reset mode (soft, mixed, hard, merge, keep) +- `target`: Commit, branch, or ref to reset to (defaults to HEAD) +- `paths`: Paths to reset +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### restore + +```python +def restore(path: str, + paths: List[str], + staged: Optional[bool] = None, + worktree: Optional[bool] = None, + source: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Restore working tree files or unstage changes. + +**Arguments**: + +- `path`: Repository path +- `paths`: Paths to restore (use ["."] for all) +- `staged`: When True, restore the index (unstage) +- `worktree`: When True, restore working tree files +- `source`: Restore from the given source (commit, branch, or ref) +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### push + +```python +def push(path: str, + remote: Optional[str] = None, + branch: Optional[str] = None, + set_upstream: bool = True, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Push commits to a remote. + +**Arguments**: + +- `path`: Repository path +- `remote`: Remote name, e.g. `origin` +- `branch`: Branch name to push +- `set_upstream`: Set upstream tracking when `True` +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### pull + +```python +def pull(path: str, + remote: Optional[str] = None, + branch: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Pull changes from a remote. + +**Arguments**: + +- `path`: Repository path +- `remote`: Remote name, e.g. `origin` +- `branch`: Branch name to pull +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### set\_config + +```python +def set_config(key: str, + value: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Set a git config value. + +Use `scope="local"` together with `path` to configure a specific repository. + +**Arguments**: + +- `key`: Git config key (e.g. `pull.rebase`) +- `value`: Git config value +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### get\_config + +```python +def get_config(key: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Optional[str] +``` + +Get a git config value. + +Returns `None` when the key is not set in the requested scope. + +**Arguments**: + +- `key`: Git config key (e.g. `pull.rebase`) +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Config value if present, otherwise `None` + + + +### dangerously\_authenticate + +```python +def dangerously_authenticate(username: str, + password: str, + host: str = "github.com", + protocol: str = "https", + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Dangerously authenticate git globally via the credential helper. + +This persists credentials in the credential store and may be accessable to agents running on the sandbox. +Prefer short-lived credentials when possible. + +**Arguments**: + +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `host`: Host to authenticate for, defaults to `github.com` +- `protocol`: Protocol to authenticate for, defaults to `https` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### configure\_user + +```python +def configure_user(name: str, + email: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Configure git user name and email. + +**Arguments**: + +- `name`: Git user name +- `email`: Git user email +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + + + + +## WatchHandle + +```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 +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 +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 +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Optional[Username] = None, + 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 +@overload +def read(path: str, + format: Literal["bytes"], + user: Optional[Username] = None, + 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 +@overload +def read(path: str, + format: Literal["stream"], + user: Optional[Username] = None, + 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 +def write(path: str, + data: Union[str, bytes, IO], + user: Optional[Username] = None, + 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 +def write_files(files: List[WriteEntry], + user: Optional[Username] = None, + 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 +def list(path: str, + depth: Optional[int] = 1, + user: Optional[Username] = None, + 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 +def exists(path: str, + user: Optional[Username] = None, + 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 +def get_info(path: str, + user: Optional[Username] = None, + 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 +def remove(path: str, + user: Optional[Username] = None, + 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 +def rename(old_path: str, + new_path: str, + user: Optional[Username] = None, + 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 +def make_dir(path: str, + user: Optional[Username] = None, + 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 +def watch_dir(path: str, + user: Optional[Username] = None, + 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 +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### \_\_iter\_\_ + +```python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + + +### disconnect + +```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 +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 +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + + + +## Pty + +```python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```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 +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 +def create(size: PtySize, + user: Optional[Username] = None, + 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 + + + +### connect + +```python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Connect to a running PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY to connect to. You can get the list of running PTYs using `sandbox.pty.list()`. +- `timeout`: Timeout for the PTY connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```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 +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```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 +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 +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 +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + stdin: Optional[bool] = 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 +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `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 +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + stdin: Optional[bool] = 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 +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `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 +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 diff --git a/docs/sdk-reference/python-sdk/v2.17.0/template.mdx b/docs/sdk-reference/python-sdk/v2.17.0/template.mdx new file mode 100644 index 00000000..6f7ddfa5 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.17.0/template.mdx @@ -0,0 +1,1924 @@ +--- +sidebarTitle: "Template" +--- + + + + + + +## TemplateBuilder + +```python +class TemplateBuilder() +``` + +Builder class for adding instructions to an E2B template. + +All methods return self to allow method chaining. + + + +### copy + +```python +def copy(src: Union[Union[str, Path], List[Union[str, Path]]], + dest: Union[str, Path], + force_upload: Optional[Literal[True]] = None, + user: Optional[str] = None, + mode: Optional[int] = None, + resolve_symlinks: Optional[bool] = None) -> "TemplateBuilder" +``` + +Copy files or directories from the local filesystem into the template. + +**Arguments**: + +- `src`: Source file(s) or directory path(s) to copy +- `dest`: Destination path in the template +- `force_upload`: Force upload even if files are cached +- `user`: User and optionally group (user:group) to own the files +- `mode`: File permissions in octal format (e.g., 0o755) +- `resolve_symlinks`: Whether to resolve symlinks + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.copy('requirements.txt', '/home/user/') +template.copy(['app.py', 'config.py'], '/app/', mode=0o755) +``` + + + +### copy\_items + +```python +def copy_items(items: List[CopyItem]) -> "TemplateBuilder" +``` + +Copy multiple files or directories using a list of copy items. + +**Arguments**: + +- `items`: List of CopyItem dictionaries with src, dest, and optional parameters + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.copy_items([ + {'src': 'app.py', 'dest': '/app/'}, + {'src': 'config.py', 'dest': '/app/', 'mode': 0o644} +]) +``` + + + +### remove + +```python +def remove(path: Union[Union[str, Path], List[Union[str, Path]]], + force: bool = False, + recursive: bool = False, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Remove files or directories in the template. + +**Arguments**: + +- `path`: File(s) or directory path(s) to remove +- `force`: Force removal without prompting +- `recursive`: Remove directories recursively +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.remove('/tmp/cache', recursive=True, force=True) +template.remove('/tmp/cache', recursive=True, force=True, user='root') +``` + + + +### rename + +```python +def rename(src: Union[str, Path], + dest: Union[str, Path], + force: bool = False, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Rename or move a file or directory in the template. + +**Arguments**: + +- `src`: Source path +- `dest`: Destination path +- `force`: Force rename without prompting +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', user='root') +``` + + + +### make\_dir + +```python +def make_dir(path: Union[Union[str, Path], List[Union[str, Path]]], + mode: Optional[int] = None, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Create directory(ies) in the template. + +**Arguments**: + +- `path`: Directory path(s) to create +- `mode`: Directory permissions in octal format (e.g., 0o755) +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.make_dir('/app/data', mode=0o755) +template.make_dir(['/app/logs', '/app/cache']) +template.make_dir('/app/data', mode=0o755, user='root') +``` + + + +### make\_symlink + +```python +def make_symlink(src: Union[str, Path], + dest: Union[str, Path], + user: Optional[str] = None, + force: bool = False) -> "TemplateBuilder" +``` + +Create a symbolic link in the template. + +**Arguments**: + +- `src`: Source path (target of the symlink) +- `dest`: Destination path (location of the symlink) +- `user`: User to run the command as +- `force`: Force symlink without prompting + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.make_symlink('/usr/bin/python3', '/usr/bin/python') +template.make_symlink('/usr/bin/python3', '/usr/bin/python', user='root') +template.make_symlink('/usr/bin/python3', '/usr/bin/python', force=True) +``` + + + +### run\_cmd + +```python +def run_cmd(command: Union[str, List[str]], + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Run a shell command during template build. + +**Arguments**: + +- `command`: Command string or list of commands to run (joined with &&) +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.run_cmd('apt-get update') +template.run_cmd(['pip install numpy', 'pip install pandas']) +template.run_cmd('apt-get install vim', user='root') +``` + + + +### set\_workdir + +```python +def set_workdir(workdir: Union[str, Path]) -> "TemplateBuilder" +``` + +Set the working directory for subsequent commands in the template. + +**Arguments**: + +- `workdir`: Path to set as the working directory + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_workdir('/app') +``` + + + +### set\_user + +```python +def set_user(user: str) -> "TemplateBuilder" +``` + +Set the user for subsequent commands in the template. + +**Arguments**: + +- `user`: Username to set + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_user('root') +``` + + + +### pip\_install + +```python +def pip_install(packages: Optional[Union[str, List[str]]] = None, + g: bool = True) -> "TemplateBuilder" +``` + +Install Python packages using pip. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, runs 'pip install .' in the current directory +- `g`: Install packages globally (default: True). If False, installs for user only + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.pip_install('numpy') +template.pip_install(['pandas', 'scikit-learn']) +template.pip_install('numpy', g=False) # Install for user only +template.pip_install() # Installs from current directory +``` + + + +### npm\_install + +```python +def npm_install(packages: Optional[Union[str, List[str]]] = None, + g: Optional[bool] = False, + dev: Optional[bool] = False) -> "TemplateBuilder" +``` + +Install Node.js packages using npm. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, installs from package.json +- `g`: Install packages globally +- `dev`: Install packages as dev dependencies + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.npm_install('express') +template.npm_install(['lodash', 'axios']) +template.npm_install('typescript', g=True) +template.npm_install() # Installs from package.json +``` + + + +### bun\_install + +```python +def bun_install(packages: Optional[Union[str, List[str]]] = None, + g: Optional[bool] = False, + dev: Optional[bool] = False) -> "TemplateBuilder" +``` + +Install Bun packages using bun. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, installs from package.json +- `g`: Install packages globally +- `dev`: Install packages as dev dependencies + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.bun_install('express') +template.bun_install(['lodash', 'axios']) +template.bun_install('tsx', g=True) +template.bun_install('typescript', dev=True) +template.bun_install() // Installs from package.json +``` + + + +### apt\_install + +```python +def apt_install(packages: Union[str, List[str]], + no_install_recommends: bool = False, + fix_missing: bool = False) -> "TemplateBuilder" +``` + +Install system packages using apt-get. + +**Arguments**: + +- `packages`: Package name(s) to install +- `no_install_recommends`: Whether to install recommended packages +- `fix_missing`: Whether to fix missing packages + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.apt_install('vim') +template.apt_install(['git', 'curl', 'wget']) +template.apt_install('vim', fix_missing=True) +``` + + + +### add\_mcp\_server + +```python +def add_mcp_server(servers: Union[str, List[str]]) -> "TemplateBuilder" +``` + +Install MCP servers using mcp-gateway. + +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +**Arguments**: + +- `servers`: MCP server name(s) + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.add_mcp_server('exa') +template.add_mcp_server(['brave', 'firecrawl', 'duckduckgo']) +``` + + + +### git\_clone + +```python +def git_clone(url: str, + path: Optional[Union[str, Path]] = None, + branch: Optional[str] = None, + depth: Optional[int] = None, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Clone a git repository into the template. + +**Arguments**: + +- `url`: Git repository URL +- `path`: Destination path for the clone +- `branch`: Branch to clone +- `depth`: Clone depth for shallow clones +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.git_clone('https://github.com/user/repo.git', '/app/repo') +template.git_clone('https://github.com/user/repo.git', branch='main', depth=1) +template.git_clone('https://github.com/user/repo.git', '/app/repo', user='root') +``` + + + +### beta\_dev\_container\_prebuild + +```python +def beta_dev_container_prebuild( + devcontainer_directory: Union[str, Path]) -> "TemplateBuilder" +``` + +Prebuild a devcontainer from the specified directory during the build process. + +**Arguments**: + +- `devcontainer_directory`: Path to the devcontainer directory + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_dev_container_prebuild('/my-devcontainer') +``` + + + +### beta\_set\_dev\_container\_start + +```python +def beta_set_dev_container_start( + devcontainer_directory: Union[str, Path]) -> "TemplateFinal" +``` + +Start a devcontainer from the specified directory and set it as the start command. + +This method returns `TemplateFinal`, which means it must be the last method in the chain. + +**Arguments**: + +- `devcontainer_directory`: Path to the devcontainer directory + +**Returns**: + +`TemplateFinal` class +Example +```python +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_set_devcontainer_start('/my-devcontainer') + +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_dev_container_prebuild('/my-devcontainer') +template.beta_set_dev_container_start('/my-devcontainer') +``` + + + +### set\_envs + +```python +def set_envs(envs: Dict[str, str]) -> "TemplateBuilder" +``` + +Set environment variables. + +Note: Environment variables defined here are available only during template build. + +**Arguments**: + +- `envs`: Dictionary of environment variable names and values + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_envs({'NODE_ENV': 'production', 'PORT': '8080'}) +``` + + + +### skip\_cache + +```python +def skip_cache() -> "TemplateBuilder" +``` + +Skip cache for all subsequent build instructions from this point. + +Call this before any instruction to force it and all following layers +to be rebuilt, ignoring any cached layers. + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.skip_cache().run_cmd('apt-get update') +``` + + + +### set\_start\_cmd + +```python +def set_start_cmd(start_cmd: str, + ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" +``` + +Set the command to start when the sandbox launches and the ready check command. + +**Arguments**: + +- `start_cmd`: Command to run when the sandbox starts +- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready + +**Returns**: + +`TemplateFinal` class +Example +```python +template.set_start_cmd( + 'python app.py', + 'curl http://localhost:8000/health' +) + +from e2b import wait_for_port, wait_for_url + +template.set_start_cmd( + 'python -m http.server 8000', + wait_for_port(8000) +) + +template.set_start_cmd( + 'npm start', + wait_for_url('http://localhost:3000/health', 200) +) +``` + + + +### set\_ready\_cmd + +```python +def set_ready_cmd(ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" +``` + +Set the command to check if the sandbox is ready. + +**Arguments**: + +- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready + +**Returns**: + +`TemplateFinal` class +Example +```python +template.set_ready_cmd('curl http://localhost:8000/health') + +from e2b import wait_for_port, wait_for_file, wait_for_process + +template.set_ready_cmd(wait_for_port(3000)) + +template.set_ready_cmd(wait_for_file('/tmp/ready')) + +template.set_ready_cmd(wait_for_process('nginx')) +``` + + + +## TemplateFinal + +```python +class TemplateFinal() +``` + +Final template state after start/ready commands are set. + + + +## TemplateBase + +```python +class TemplateBase() +``` + +Base class for building E2B sandbox templates. + + + +### \_\_init\_\_ + +```python +def __init__(file_context_path: Optional[Union[str, Path]] = None, + file_ignore_patterns: Optional[List[str]] = None) +``` + +Create a new template builder instance. + +**Arguments**: + +- `file_context_path`: Base path for resolving relative file paths in copy operations +- `file_ignore_patterns`: List of glob patterns to ignore when copying files + + + +### skip\_cache + +```python +def skip_cache() -> "TemplateBase" +``` + +Skip cache for all subsequent build instructions from this point. + +**Returns**: + +`TemplateBase` class +Example +```python +template.skip_cache().from_python_image('3.11') +``` + + + +### from\_debian\_image + +```python +def from_debian_image(variant: str = "stable") -> TemplateBuilder +``` + +Start template from a Debian base image. + +**Arguments**: + +- `variant`: Debian image variant + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_debian_image('bookworm') +``` + + + +### from\_ubuntu\_image + +```python +def from_ubuntu_image(variant: str = "latest") -> TemplateBuilder +``` + +Start template from an Ubuntu base image. + +**Arguments**: + +- `variant`: Ubuntu image variant (default: 'latest') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_ubuntu_image('24.04') +``` + + + +### from\_python\_image + +```python +def from_python_image(version: str = "3") -> TemplateBuilder +``` + +Start template from a Python base image. + +**Arguments**: + +- `version`: Python version (default: '3') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_python_image('3') +``` + + + +### from\_node\_image + +```python +def from_node_image(variant: str = "lts") -> TemplateBuilder +``` + +Start template from a Node.js base image. + +**Arguments**: + +- `variant`: Node.js image variant (default: 'lts') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_node_image('24') +``` + + + +### from\_bun\_image + +```python +def from_bun_image(variant: str = "latest") -> TemplateBuilder +``` + +Start template from a Bun base image. + +**Arguments**: + +- `variant`: Bun image variant (default: 'latest') + +**Returns**: + +`TemplateBuilder` class + + + +### from\_base\_image + +```python +def from_base_image() -> TemplateBuilder +``` + +Start template from the E2B base image (e2bdev/base:latest). + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_base_image() +``` + + + +### from\_image + +```python +def from_image(image: str, + username: Optional[str] = None, + password: Optional[str] = None) -> TemplateBuilder +``` + +Start template from a Docker image. + +**Arguments**: + +- `image`: Docker image name (e.g., 'ubuntu:24.04') +- `username`: Username for private registry authentication +- `password`: Password for private registry authentication + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_image('python:3') + +Template().from_image('myregistry.com/myimage:latest', username='user', password='pass') +``` + + + +### from\_template + +```python +def from_template(template: str) -> TemplateBuilder +``` + +Start template from an existing E2B template. + +**Arguments**: + +- `template`: E2B template ID or alias + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_template('my-base-template') +``` + + + +### from\_dockerfile + +```python +def from_dockerfile(dockerfile_content_or_path: str) -> TemplateBuilder +``` + +Parse a Dockerfile and convert it to Template SDK format. + +**Arguments**: + +- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_dockerfile('Dockerfile') +Template().from_dockerfile('FROM python:3\nRUN pip install numpy') +``` + + + +### from\_aws\_registry + +```python +def from_aws_registry(image: str, access_key_id: str, secret_access_key: str, + region: str) -> TemplateBuilder +``` + +Start template from an AWS ECR registry image. + +**Arguments**: + +- `image`: Docker image name from AWS ECR +- `access_key_id`: AWS access key ID +- `secret_access_key`: AWS secret access key +- `region`: AWS region + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_aws_registry( + '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', + access_key_id='AKIA...', + secret_access_key='...', + region='us-west-2' +) +``` + + + +### from\_gcp\_registry + +```python +def from_gcp_registry( + image: str, service_account_json: Union[str, dict]) -> TemplateBuilder +``` + +Start template from a GCP Artifact Registry or Container Registry image. + +**Arguments**: + +- `image`: Docker image name from GCP registry +- `service_account_json`: Service account JSON string, dict, or path to JSON file + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_gcp_registry( + 'gcr.io/myproject/myimage:latest', + service_account_json='path/to/service-account.json' +) +``` + + + +### to\_json + +```python +@staticmethod +def to_json(template: "TemplateClass") -> str +``` + +Convert a template to JSON representation. + +**Arguments**: + +- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) + +**Returns**: + +JSON string representation of the template +Example +```python +template = Template().from_python_image('3').copy('app.py', '/app/') +json_str = TemplateBase.to_json(template) +``` + + + +### to\_dockerfile + +```python +@staticmethod +def to_dockerfile(template: "TemplateClass") -> str +``` + +Convert a template to Dockerfile format. + +Note: Templates based on other E2B templates cannot be converted to Dockerfile. + +**Arguments**: + +- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) + +**Raises**: + +- `ValueError`: If the template is based on another E2B template or has no base image +Example +```python +template = Template().from_python_image('3').copy('app.py', '/app/') +dockerfile = TemplateBase.to_dockerfile(template) +``` + +**Returns**: + +Dockerfile string representation + + + + + + +## LogEntry + +```python +@dataclass +class LogEntry() +``` + +Represents a single log entry from the template build process. + + + +## LogEntryStart + +```python +@dataclass +class LogEntryStart(LogEntry) +``` + +Special log entry indicating the start of a build process. + + + +## LogEntryEnd + +```python +@dataclass +class LogEntryEnd(LogEntry) +``` + +Special log entry indicating the end of a build process. + + + +### TIMER\_UPDATE\_INTERVAL\_MS + +Default minimum log level to display. + + + +### DEFAULT\_LEVEL + +Colored labels for each log level. + + + +### levels + +Numeric ordering of log levels for comparison (lower = less severe). + + + +### set\_interval + +```python +def set_interval(func, interval) +``` + +Returns a stop function that can be called to cancel the interval. + +Similar to JavaScript's setInterval. + +**Arguments**: + +- `func`: Function to execute at each interval +- `interval`: Interval duration in **seconds** + +**Returns**: + +Stop function that can be called to cancel the interval + + + +### default\_build\_logger + +```python +def default_build_logger( + min_level: Optional[LogEntryLevel] = None +) -> Callable[[LogEntry], None] +``` + +Create a default build logger with animated timer display. + +**Arguments**: + +- `min_level`: Minimum log level to display (default: 'info') + +**Returns**: + +Logger function that accepts LogEntry instances +Example +```python +from e2b import Template, default_build_logger + +template = Template().from_python_image() + +``` + + + + + + +### make\_traceback + +```python +def make_traceback( + caller_frame: Optional[FrameType]) -> Optional[TracebackType] +``` + +Create a TracebackType from a caller frame for error reporting. + +**Arguments**: + +- `caller_frame`: The caller's frame object, or None + +**Returns**: + +A TracebackType object for use with exception.with_traceback(), or None + + + +### validate\_relative\_path + +```python +def validate_relative_path(src: str, + stack_trace: Optional[TracebackType]) -> None +``` + +Validate that a source path for copy operations is a relative path that stays + +within the context directory. This prevents path traversal attacks and ensures +files are copied from within the expected directory. + +**Arguments**: + +- `src`: The source path to validate +- `stack_trace`: Optional stack trace for error reporting + +**Raises**: + +- `TemplateException`: If the path is absolute or escapes the context directory +Invalid paths: +- Absolute paths: /absolute/path, C:\Windows\path +- Parent directory escapes: ../foo, foo/../../bar, ./foo/../../../bar + +Valid paths: +- Simple relative: foo, foo/bar +- Current directory prefix: ./foo, ./foo/bar +- Internal parent refs that don't escape: foo/../bar (stays within context) + + + +### normalize\_build\_arguments + +```python +def normalize_build_arguments(name: Optional[str] = None, + alias: Optional[str] = None) -> str +``` + +Normalize build arguments from different parameter signatures. + +Handles string name or legacy alias parameter. + +**Arguments**: + +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. + +**Raises**: + +- `TemplateException`: If no template name is provided + +**Returns**: + +Normalized template name + + + +### read\_dockerignore + +```python +def read_dockerignore(context_path: str) -> List[str] +``` + +Read and parse a .dockerignore file. + +**Arguments**: + +- `context_path`: Directory path containing the .dockerignore file + +**Returns**: + +Array of ignore patterns (empty lines and comments are filtered out) + + + +### normalize\_path + +```python +def normalize_path(path: str) -> str +``` + +Normalize path separators to forward slashes for glob patterns (glob expects / even on Windows). + +**Arguments**: + +- `path`: The path to normalize + +**Returns**: + +The normalized path + + + +### get\_all\_files\_in\_path + +```python +def get_all_files_in_path(src: str, + context_path: str, + ignore_patterns: List[str], + include_directories: bool = True) -> List[str] +``` + +Get all files for a given path and ignore patterns. + +**Arguments**: + +- `src`: Path to the source directory +- `context_path`: Base directory for resolving relative paths +- `ignore_patterns`: Ignore patterns +- `include_directories`: Whether to include directories + +**Returns**: + +Array of files + + + +### calculate\_files\_hash + +```python +def calculate_files_hash(src: str, dest: str, context_path: str, + ignore_patterns: List[str], resolve_symlinks: bool, + stack_trace: Optional[TracebackType]) -> str +``` + +Calculate a hash of files being copied to detect changes for cache invalidation. + +The hash includes file content, metadata (mode, size), and relative paths. +Note: uid, gid, and mtime are excluded to ensure stable hashes across environments. + +**Arguments**: + +- `src`: Source path pattern for files to copy +- `dest`: Destination path where files will be copied +- `context_path`: Base directory for resolving relative paths +- `ignore_patterns`: Glob patterns to ignore +- `resolve_symlinks`: Whether to resolve symbolic links when hashing +- `stack_trace`: Optional stack trace for error reporting + +**Raises**: + +- `ValueError`: If no files match the source pattern + +**Returns**: + +Hex string hash of all files + + + +### tar\_file\_stream + +```python +def tar_file_stream(file_name: str, file_context_path: str, + ignore_patterns: List[str], + resolve_symlinks: bool) -> io.BytesIO +``` + +Create a tar stream of files matching a pattern. + +**Arguments**: + +- `file_name`: Glob pattern for files to include +- `file_context_path`: Base directory for resolving file paths +- `ignore_patterns`: Ignore patterns +- `resolve_symlinks`: Whether to resolve symbolic links + +**Returns**: + +Tar stream + + + +### strip\_ansi\_escape\_codes + +```python +def strip_ansi_escape_codes(text: str) -> str +``` + +Strip ANSI escape codes from a string. + +Source: https://github.com/chalk/ansi-regex/blob/main/index.js + +**Arguments**: + +- `text`: String with ANSI escape codes + +**Returns**: + +String without ANSI escape codes + + + +### get\_caller\_frame + +```python +def get_caller_frame(depth: int) -> Optional[FrameType] +``` + +Get the caller's stack frame at a specific depth. + +This is used to provide better error messages and debugging information +by tracking where template methods were called from in user code. + +**Arguments**: + +- `depth`: The depth of the stack trace to retrieve + +**Returns**: + +The caller frame, or None if not available + + + +### get\_caller\_directory + +```python +def get_caller_directory(depth: int) -> Optional[str] +``` + +Get the directory of the caller at a specific stack depth. + +This is used to determine the file_context_path when creating a template, +so file paths are resolved relative to the user's template file location. + +**Arguments**: + +- `depth`: The depth of the stack trace + +**Returns**: + +The caller's directory path, or None if not available + + + +### pad\_octal + +```python +def pad_octal(mode: int) -> str +``` + +Convert a numeric file mode to a zero-padded octal string. + +**Arguments**: + +- `mode`: File mode as a number (e.g., 493 for 0o755) + +**Returns**: + +Zero-padded 4-digit octal string (e.g., "0755") +Example +```python +pad_octal(0o755) # Returns "0755" +pad_octal(0o644) # Returns "0644" +``` + + + +### get\_build\_step\_index + +```python +def get_build_step_index(step: str, stack_traces_length: int) -> int +``` + +Get the array index for a build step based on its name. + +Special steps: +- BASE_STEP_NAME: Returns 0 (first step) +- FINALIZE_STEP_NAME: Returns the last index +- Numeric strings: Converted to number + +**Arguments**: + +- `step`: Build step name or number as string +- `stack_traces_length`: Total number of stack traces (used for FINALIZE_STEP_NAME) + +**Returns**: + +Index for the build step + + + +### read\_gcp\_service\_account\_json + +```python +def read_gcp_service_account_json(context_path: str, + path_or_content: Union[str, dict]) -> str +``` + +Read GCP service account JSON from a file or object. + +**Arguments**: + +- `context_path`: Base directory for resolving relative file paths +- `path_or_content`: Either a path to a JSON file or a service account object + +**Returns**: + +Service account JSON as a string + + + + + + +## DockerfFileFinalParserInterface + +```python +class DockerfFileFinalParserInterface(Protocol) +``` + +Protocol defining the final interface for Dockerfile parsing callbacks. + + + +## DockerfileParserInterface + +```python +class DockerfileParserInterface(Protocol) +``` + +Protocol defining the interface for Dockerfile parsing callbacks. + + + +### run\_cmd + +```python +def run_cmd(command: Union[str, List[str]], + user: Optional[str] = None) -> "DockerfileParserInterface" +``` + +Handle RUN instruction. + + + +### copy + +```python +def copy( + src: str, + dest: str, + force_upload: Optional[Literal[True]] = None, + user: Optional[str] = None, + mode: Optional[int] = None, + resolve_symlinks: Optional[bool] = None +) -> "DockerfileParserInterface" +``` + +Handle COPY instruction. + + + +### set\_workdir + +```python +def set_workdir(workdir: str) -> "DockerfileParserInterface" +``` + +Handle WORKDIR instruction. + + + +### set\_user + +```python +def set_user(user: str) -> "DockerfileParserInterface" +``` + +Handle USER instruction. + + + +### set\_envs + +```python +def set_envs(envs: Dict[str, str]) -> "DockerfileParserInterface" +``` + +Handle ENV instruction. + + + +### set\_start\_cmd + +```python +def set_start_cmd(start_cmd: str, + ready_cmd: str) -> "DockerfFileFinalParserInterface" +``` + +Handle CMD/ENTRYPOINT instruction. + + + +### parse\_dockerfile + +```python +def parse_dockerfile(dockerfile_content_or_path: str, + template_builder: DockerfileParserInterface) -> str +``` + +Parse a Dockerfile and convert it to Template SDK format. + +**Arguments**: + +- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file +- `template_builder`: Interface providing template builder methods + +**Raises**: + +- `ValueError`: If the Dockerfile is invalid or unsupported + +**Returns**: + +The base image from the Dockerfile + + + + + + +## TemplateBuildStatus + +```python +class TemplateBuildStatus(str, Enum) +``` + +Status of a template build. + + + +## BuildStatusReason + +```python +@dataclass +class BuildStatusReason() +``` + +Reason for the current build status (typically for errors). + + + +### message + +Message with the status reason. + + + +### step + +Step that failed. + + + +### log\_entries + +Log entries related to the status reason. + + + +## TemplateBuildStatusResponse + +```python +@dataclass +class TemplateBuildStatusResponse() +``` + +Response from getting build status. + + + +### build\_id + +Build identifier. + + + +### template\_id + +Template identifier. + + + +### status + +Current status of the build. + + + +### log\_entries + +Build log entries. + + + +### logs + +Build logs (raw strings). Deprecated: use log_entries instead. + + + +### reason + +Reason for the current status (typically for errors). + + + +## TemplateTagInfo + +```python +@dataclass +class TemplateTagInfo() +``` + +Information about assigned template tags. + + + +### build\_id + +Build identifier associated with this tag. + + + +### tags + +Assigned tags of the template. + + + +## TemplateTag + +```python +@dataclass +class TemplateTag() +``` + +Detailed information about a single template tag. + + + +### tag + +Name of the tag. + + + +### build\_id + +Build identifier associated with this tag. + + + +### created\_at + +When this tag was assigned. + + + +## InstructionType + +```python +class InstructionType(str, Enum) +``` + +Types of instructions that can be used in a template. + + + +## CopyItem + +```python +class CopyItem(TypedDict) +``` + +Configuration for a single file/directory copy operation. + + + +## Instruction + +```python +class Instruction(TypedDict) +``` + +Represents a single instruction in the template build process. + + + +## GenericDockerRegistry + +```python +class GenericDockerRegistry(TypedDict) +``` + +Configuration for a generic Docker registry with basic authentication. + + + +## AWSRegistry + +```python +class AWSRegistry(TypedDict) +``` + +Configuration for AWS Elastic Container Registry (ECR). + + + +## GCPRegistry + +```python +class GCPRegistry(TypedDict) +``` + +Configuration for Google Container Registry (GCR) or Artifact Registry. + + + +## TemplateType + +```python +class TemplateType(TypedDict) +``` + +Internal representation of a template for the E2B build API. + + + +## BuildInfo + +```python +@dataclass +class BuildInfo() +``` + +Information about a built template. + + + + +Special step name for the finalization phase of template building. +This is the last step that runs after all user-defined instructions. + + + +### FINALIZE\_STEP\_NAME + +Special step name for the base image phase of template building. +This is the first step that sets up the base image. + + + +### BASE\_STEP\_NAME + +Stack trace depth for capturing caller information. + +Depth levels: +1. TemplateClass +2. Caller method (e.g., copy(), from_image(), etc.) + +This depth is used to determine the original caller's location +for stack traces. + + + +### STACK\_TRACE\_DEPTH + +Default setting for whether to resolve symbolic links when copying files. +When False, symlinks are copied as symlinks rather than following them. + + + + + + +## ReadyCmd + +```python +class ReadyCmd() +``` + +Wrapper class for ready check commands. + + + +### wait\_for\_port + +```python +def wait_for_port(port: int) +``` + +Wait for a port to be listening. + +Uses `ss` command to check if a port is open and listening. + +**Arguments**: + +- `port`: Port number to wait for + +**Returns**: + +ReadyCmd that checks for the port +Example +```python +from e2b import Template, wait_for_port + +template = ( + Template() + .from_python_image() + .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) +) +``` + + + +### wait\_for\_url + +```python +def wait_for_url(url: str, status_code: int = 200) +``` + +Wait for a URL to return a specific HTTP status code. + +Uses `curl` to make HTTP requests and check the response status. + +**Arguments**: + +- `url`: URL to check (e.g., 'http://localhost:3000/health') +- `status_code`: Expected HTTP status code (default: 200) + +**Returns**: + +ReadyCmd that checks the URL +Example +```python +from e2b import Template, wait_for_url + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) +) +``` + + + +### wait\_for\_process + +```python +def wait_for_process(process_name: str) +``` + +Wait for a process with a specific name to be running. + +Uses `pgrep` to check if a process exists. + +**Arguments**: + +- `process_name`: Name of the process to wait for + +**Returns**: + +ReadyCmd that checks for the process +Example +```python +from e2b import Template, wait_for_process + +template = ( + Template() + .from_base_image() + .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) +) +``` + + + +### wait\_for\_file + +```python +def wait_for_file(filename: str) +``` + +Wait for a file to exist. + +Uses shell test command to check file existence. + +**Arguments**: + +- `filename`: Path to the file to wait for + +**Returns**: + +ReadyCmd that checks for the file +Example +```python +from e2b import Template, wait_for_file + +template = ( + Template() + .from_base_image() + .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) +) +``` + + + +### wait\_for\_timeout + +```python +def wait_for_timeout(timeout: int) +``` + +Wait for a specified timeout before considering the sandbox ready. + +Uses `sleep` command to wait for a fixed duration. + +**Arguments**: + +- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) + +**Returns**: + +ReadyCmd that waits for the specified duration +Example +```python +from e2b import Template, wait_for_timeout + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds +) +``` diff --git a/docs/sdk-reference/python-sdk/v2.17.0/template_async.mdx b/docs/sdk-reference/python-sdk/v2.17.0/template_async.mdx new file mode 100644 index 00000000..f75603fb --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.17.0/template_async.mdx @@ -0,0 +1,357 @@ +--- +sidebarTitle: "Template Async" +--- + + + + + + +## AsyncTemplate + +```python +class AsyncTemplate(TemplateBase) +``` + +Asynchronous template builder for E2B sandboxes. + + + +### build + +```python +@staticmethod +async def build(template: TemplateClass, + name: Optional[str] = None, + *, + alias: Optional[str] = None, + tags: Optional[List[str]] = None, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], None]] = None, + **opts: Unpack[ApiParams]) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure. + +**Arguments**: + +- `template`: The template to build +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. +- `tags`: Optional additional tags to assign to the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `on_build_logs`: Callback function to receive build logs during the build process +Example +```python +from e2b import AsyncTemplate + +template = ( + AsyncTemplate() + .from_python_image('3') + .copy('requirements.txt', '/home/user/') + .run_cmd('pip install -r /home/user/requirements.txt') +) + +await AsyncTemplate.build(template, 'my-python-env:v1.0') + +await AsyncTemplate.build(template, 'my-python-env', tags=['v1.1.0', 'stable']) +``` + + + +### build\_in\_background + +```python +@staticmethod +async def build_in_background(template: TemplateClass, + name: Optional[str] = None, + *, + alias: Optional[str] = None, + tags: Optional[List[str]] = None, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], + None]] = None, + **opts: Unpack[ApiParams]) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +**Arguments**: + +- `template`: The template to build +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. +- `tags`: Optional additional tags to assign to the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache + +**Returns**: + +BuildInfo containing the template ID and build ID +Example +```python +from e2b import AsyncTemplate + +template = ( + AsyncTemplate() + .from_python_image('3') + .run_cmd('echo "test"') + .set_start_cmd('echo "Hello"', 'sleep 1') +) + +build_info = await AsyncTemplate.build_in_background(template, 'my-python-env:v1.0') + +build_info = await AsyncTemplate.build_in_background(template, 'my-python-env', tags=['v1.1.0', 'stable']) +``` + + + +### get\_build\_status + +```python +@staticmethod +async def get_build_status(build_info: BuildInfo, + logs_offset: int = 0, + **opts: Unpack[ApiParams]) +``` + +Get the status of a build. + +**Arguments**: + +- `build_info`: Build identifiers returned from build_in_background +- `logs_offset`: Offset for fetching logs + +**Returns**: + +TemplateBuild containing the build status and logs +Example +```python +from e2b import AsyncTemplate + +build_info = await AsyncTemplate.build_in_background(template, alias='my-template') +status = await AsyncTemplate.get_build_status(build_info, logs_offset=0) +``` + + + +### exists + +```python +@staticmethod +async def exists(name: str, **opts: Unpack[ApiParams]) -> bool +``` + +Check if a template with the given name exists. + +**Arguments**: + +- `name`: Template name to check + +**Returns**: + +True if the name exists, False otherwise +Example +```python +from e2b import AsyncTemplate + +exists = await AsyncTemplate.exists('my-python-env') +if exists: + print('Template exists!') +``` + + + +### alias\_exists + +```python +@staticmethod +async def alias_exists(alias: str, **opts: Unpack[ApiParams]) -> bool +``` + +Check if a template with the given alias exists. + +Deprecated Use `exists` instead. + +**Arguments**: + +- `alias`: Template alias to check + +**Returns**: + +True if the alias exists, False otherwise +Example +```python +from e2b import AsyncTemplate + +exists = await AsyncTemplate.alias_exists('my-python-env') +if exists: + print('Template exists!') +``` + + + +### assign\_tags + +```python +@staticmethod +async def assign_tags(target_name: str, tags: Union[str, List[str]], + **opts: Unpack[ApiParams]) -> TemplateTagInfo +``` + +Assign tag(s) to an existing template build. + +**Arguments**: + +- `target_name`: Template name in 'name:tag' format (the source build to tag from) +- `tags`: Tag or tags to assign + +**Returns**: + +TemplateTagInfo with build_id and assigned tags +Example +```python +from e2b import AsyncTemplate + +result = await AsyncTemplate.assign_tags('my-template:v1.0', 'production') + +result = await AsyncTemplate.assign_tags('my-template:v1.0', ['production', 'stable']) +``` + + + +### remove\_tags + +```python +@staticmethod +async def remove_tags(name: str, tags: Union[str, List[str]], + **opts: Unpack[ApiParams]) -> None +``` + +Remove tag(s) from a template. + +**Arguments**: + +- `name`: Template name +- `tags`: Tag or tags to remove +Example +```python +from e2b import AsyncTemplate + +await AsyncTemplate.remove_tags('my-template', 'production') + +await AsyncTemplate.remove_tags('my-template', ['production', 'stable']) +``` + + + +### get\_tags + +```python +@staticmethod +async def get_tags(template_id: str, + **opts: Unpack[ApiParams]) -> List[TemplateTag] +``` + +Get all tags for a template. + +**Arguments**: + +- `template_id`: Template ID or name + +**Returns**: + +List of TemplateTag with tag name, build_id, and created_at +Example +```python +from e2b import AsyncTemplate + +tags = await AsyncTemplate.get_tags('my-template') +for tag in tags: + print(f"Tag: {tag.tag}, Build: {tag.build_id}, Created: {tag.created_at}") +``` + + + + + + +### check\_alias\_exists + +```python +async def check_alias_exists(client: AuthenticatedClient, alias: str) -> bool +``` + +Check if a template with the given alias exists. + +**Arguments**: + +- `client` - Authenticated API client +- `alias` - Template alias to check + + +**Returns**: + + True if the alias exists, False otherwise + + + +### assign\_tags + +```python +async def assign_tags(client: AuthenticatedClient, target_name: str, + tags: List[str]) -> TemplateTagInfo +``` + +Assign tag(s) to an existing template build. + +**Arguments**: + +- `client` - Authenticated API client +- `target_name` - Template name in 'name:tag' format (the source build to tag from) +- `tags` - Tags to assign + + +**Returns**: + + TemplateTagInfo with build_id and assigned tags + + + +### remove\_tags + +```python +async def remove_tags(client: AuthenticatedClient, name: str, + tags: List[str]) -> None +``` + +Remove tag(s) from a template. + +**Arguments**: + +- `client` - Authenticated API client +- `name` - Template name +- `tags` - List of tags to remove + + + +### get\_template\_tags + +```python +async def get_template_tags(client: AuthenticatedClient, + template_id: str) -> List[TemplateTag] +``` + +Get all tags for a template. + +**Arguments**: + +- `client` - Authenticated API client +- `template_id` - Template ID or name diff --git a/docs/sdk-reference/python-sdk/v2.17.0/template_sync.mdx b/docs/sdk-reference/python-sdk/v2.17.0/template_sync.mdx new file mode 100644 index 00000000..ff5cee37 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.17.0/template_sync.mdx @@ -0,0 +1,356 @@ +--- +sidebarTitle: "Template Sync" +--- + + + + + + +## Template + +```python +class Template(TemplateBase) +``` + +Synchronous template builder for E2B sandboxes. + + + +### build + +```python +@staticmethod +def build(template: TemplateClass, + name: Optional[str] = None, + *, + alias: Optional[str] = None, + tags: Optional[List[str]] = None, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], None]] = None, + **opts: Unpack[ApiParams]) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure. + +**Arguments**: + +- `template`: The template to build +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. +- `tags`: Optional additional tags to assign to the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `on_build_logs`: Callback function to receive build logs during the build process +Example +```python +from e2b import Template + +template = ( + Template() + .from_python_image('3') + .copy('requirements.txt', '/home/user/') + .run_cmd('pip install -r /home/user/requirements.txt') +) + +Template.build(template, 'my-python-env:v1.0') + +Template.build(template, 'my-python-env', tags=['v1.1.0', 'stable']) +``` + + + +### build\_in\_background + +```python +@staticmethod +def build_in_background(template: TemplateClass, + name: Optional[str] = None, + *, + alias: Optional[str] = None, + tags: Optional[List[str]] = None, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], + None]] = None, + **opts: Unpack[ApiParams]) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +**Arguments**: + +- `template`: The template to build +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. +- `tags`: Optional additional tags to assign to the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache + +**Returns**: + +BuildInfo containing the template ID and build ID +Example +```python +from e2b import Template + +template = ( + Template() + .from_python_image('3') + .run_cmd('echo "test"') + .set_start_cmd('echo "Hello"', 'sleep 1') +) + +build_info = Template.build_in_background(template, 'my-python-env:v1.0') + +build_info = Template.build_in_background(template, 'my-python-env', tags=['v1.1.0', 'stable']) +``` + + + +### get\_build\_status + +```python +@staticmethod +def get_build_status(build_info: BuildInfo, + logs_offset: int = 0, + **opts: Unpack[ApiParams]) +``` + +Get the status of a build. + +**Arguments**: + +- `build_info`: Build identifiers returned from build_in_background +- `logs_offset`: Offset for fetching logs + +**Returns**: + +TemplateBuild containing the build status and logs +Example +```python +from e2b import Template + +build_info = Template.build_in_background(template, alias='my-template') +status = Template.get_build_status(build_info, logs_offset=0) +``` + + + +### exists + +```python +@staticmethod +def exists(name: str, **opts: Unpack[ApiParams]) -> bool +``` + +Check if a template with the given name exists. + +**Arguments**: + +- `name`: Template name to check + +**Returns**: + +True if the name exists, False otherwise +Example +```python +from e2b import Template + +exists = Template.exists('my-python-env') +if exists: + print('Template exists!') +``` + + + +### alias\_exists + +```python +@staticmethod +def alias_exists(alias: str, **opts: Unpack[ApiParams]) -> bool +``` + +Check if a template with the given alias exists. + +Deprecated Use `exists` instead. + +**Arguments**: + +- `alias`: Template alias to check + +**Returns**: + +True if the alias exists, False otherwise +Example +```python +from e2b import Template + +exists = Template.alias_exists('my-python-env') +if exists: + print('Template exists!') +``` + + + +### assign\_tags + +```python +@staticmethod +def assign_tags(target_name: str, tags: Union[str, List[str]], + **opts: Unpack[ApiParams]) -> TemplateTagInfo +``` + +Assign tag(s) to an existing template build. + +**Arguments**: + +- `target_name`: Template name in 'name:tag' format (the source build to tag from) +- `tags`: Tag or tags to assign + +**Returns**: + +TemplateTagInfo with build_id and assigned tags +Example +```python +from e2b import Template + +result = Template.assign_tags('my-template:v1.0', 'production') + +result = Template.assign_tags('my-template:v1.0', ['production', 'stable']) +``` + + + +### remove\_tags + +```python +@staticmethod +def remove_tags(name: str, tags: Union[str, List[str]], + **opts: Unpack[ApiParams]) -> None +``` + +Remove tag(s) from a template. + +**Arguments**: + +- `name`: Template name +- `tags`: Tag or tags to remove +Example +```python +from e2b import Template + +Template.remove_tags('my-template', 'production') + +Template.remove_tags('my-template', ['production', 'stable']) +``` + + + +### get\_tags + +```python +@staticmethod +def get_tags(template_id: str, **opts: Unpack[ApiParams]) -> List[TemplateTag] +``` + +Get all tags for a template. + +**Arguments**: + +- `template_id`: Template ID or name + +**Returns**: + +List of TemplateTag with tag name, build_id, and created_at +Example +```python +from e2b import Template + +tags = Template.get_tags('my-template') +for tag in tags: + print(f"Tag: {tag.tag}, Build: {tag.build_id}, Created: {tag.created_at}") +``` + + + + + + +### check\_alias\_exists + +```python +def check_alias_exists(client: AuthenticatedClient, alias: str) -> bool +``` + +Check if a template with the given alias exists. + +**Arguments**: + +- `client` - Authenticated API client +- `alias` - Template alias to check + + +**Returns**: + + True if the alias exists, False otherwise + + + +### assign\_tags + +```python +def assign_tags(client: AuthenticatedClient, target_name: str, + tags: List[str]) -> TemplateTagInfo +``` + +Assign tag(s) to an existing template build. + +**Arguments**: + +- `client` - Authenticated API client +- `target_name` - Template name in 'name:tag' format (the source build to tag from) +- `tags` - Tags to assign + + +**Returns**: + + TemplateTagInfo with build_id and assigned tags + + + +### remove\_tags + +```python +def remove_tags(client: AuthenticatedClient, name: str, + tags: List[str]) -> None +``` + +Remove tag(s) from a template. + +**Arguments**: + +- `client` - Authenticated API client +- `name` - Template name +- `tags` - List of tags to remove + + + +### get\_template\_tags + +```python +def get_template_tags(client: AuthenticatedClient, + template_id: str) -> List[TemplateTag] +``` + +Get all tags for a template. + +**Arguments**: + +- `client` - Authenticated API client +- `template_id` - Template ID or name diff --git a/docs/sdk-reference/python-sdk/v2.18.0/exceptions.mdx b/docs/sdk-reference/python-sdk/v2.18.0/exceptions.mdx new file mode 100644 index 00000000..8be3b68a --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.18.0/exceptions.mdx @@ -0,0 +1,160 @@ +--- +sidebarTitle: "Exceptions" +--- + + + + + + +## SandboxException + +```python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + + +## TimeoutException + +```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 +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + + +## NotEnoughSpaceException + +```python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + + +## NotFoundException + +```python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + +.. deprecated:: + Use :class:`FileNotFoundException` or :class:`SandboxNotFoundException` instead. + This class will be removed in the next major version. + + + +## FileNotFoundException + +```python +class FileNotFoundException(NotFoundException) +``` + +Raised when a file or directory is not found inside a sandbox. + + + +## SandboxNotFoundException + +```python +class SandboxNotFoundException(NotFoundException) +``` + +Raised when a sandbox is not found (e.g. it doesn't exist or is no longer running). + + + +## AuthenticationException + +```python +class AuthenticationException(Exception) +``` + +Raised when authentication fails. + + + +## GitAuthException + +```python +class GitAuthException(AuthenticationException) +``` + +Raised when git authentication fails. + + + +## GitUpstreamException + +```python +class GitUpstreamException(SandboxException) +``` + +Raised when git upstream tracking is missing. + + + +## TemplateException + +```python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + + +## RateLimitException + +```python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + + + +## BuildException + +```python +class BuildException(Exception) +``` + +Raised when the build fails. + + + +## FileUploadException + +```python +class FileUploadException(BuildException) +``` + +Raised when the file upload fails. diff --git a/docs/sdk-reference/python-sdk/v2.18.0/logger.mdx b/docs/sdk-reference/python-sdk/v2.18.0/logger.mdx new file mode 100644 index 00000000..16f9c54e --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.18.0/logger.mdx @@ -0,0 +1,105 @@ +--- +sidebarTitle: "Logger" +--- + + + + + + +## LogEntry + +```python +@dataclass +class LogEntry() +``` + +Represents a single log entry from the template build process. + + + +## LogEntryStart + +```python +@dataclass +class LogEntryStart(LogEntry) +``` + +Special log entry indicating the start of a build process. + + + +## LogEntryEnd + +```python +@dataclass +class LogEntryEnd(LogEntry) +``` + +Special log entry indicating the end of a build process. + + + +### TIMER\_UPDATE\_INTERVAL\_MS + +Default minimum log level to display. + + + +### DEFAULT\_LEVEL + +Colored labels for each log level. + + + +### levels + +Numeric ordering of log levels for comparison (lower = less severe). + + + +### set\_interval + +```python +def set_interval(func, interval) +``` + +Returns a stop function that can be called to cancel the interval. + +Similar to JavaScript's setInterval. + +**Arguments**: + +- `func`: Function to execute at each interval +- `interval`: Interval duration in **seconds** + +**Returns**: + +Stop function that can be called to cancel the interval + + + +### default\_build\_logger + +```python +def default_build_logger( + min_level: Optional[LogEntryLevel] = None +) -> Callable[[LogEntry], None] +``` + +Create a default build logger with animated timer display. + +**Arguments**: + +- `min_level`: Minimum log level to display (default: 'info') + +**Returns**: + +Logger function that accepts LogEntry instances +Example +```python +from e2b import Template, default_build_logger + +template = Template().from_python_image() + +``` diff --git a/docs/sdk-reference/python-sdk/v2.18.0/readycmd.mdx b/docs/sdk-reference/python-sdk/v2.18.0/readycmd.mdx new file mode 100644 index 00000000..b4083b62 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.18.0/readycmd.mdx @@ -0,0 +1,167 @@ +--- +sidebarTitle: "Readycmd" +--- + + + + + + +## ReadyCmd + +```python +class ReadyCmd() +``` + +Wrapper class for ready check commands. + + + +### wait\_for\_port + +```python +def wait_for_port(port: int) +``` + +Wait for a port to be listening. + +Uses `ss` command to check if a port is open and listening. + +**Arguments**: + +- `port`: Port number to wait for + +**Returns**: + +ReadyCmd that checks for the port +Example +```python +from e2b import Template, wait_for_port + +template = ( + Template() + .from_python_image() + .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) +) +``` + + + +### wait\_for\_url + +```python +def wait_for_url(url: str, status_code: int = 200) +``` + +Wait for a URL to return a specific HTTP status code. + +Uses `curl` to make HTTP requests and check the response status. + +**Arguments**: + +- `url`: URL to check (e.g., 'http://localhost:3000/health') +- `status_code`: Expected HTTP status code (default: 200) + +**Returns**: + +ReadyCmd that checks the URL +Example +```python +from e2b import Template, wait_for_url + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) +) +``` + + + +### wait\_for\_process + +```python +def wait_for_process(process_name: str) +``` + +Wait for a process with a specific name to be running. + +Uses `pgrep` to check if a process exists. + +**Arguments**: + +- `process_name`: Name of the process to wait for + +**Returns**: + +ReadyCmd that checks for the process +Example +```python +from e2b import Template, wait_for_process + +template = ( + Template() + .from_base_image() + .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) +) +``` + + + +### wait\_for\_file + +```python +def wait_for_file(filename: str) +``` + +Wait for a file to exist. + +Uses shell test command to check file existence. + +**Arguments**: + +- `filename`: Path to the file to wait for + +**Returns**: + +ReadyCmd that checks for the file +Example +```python +from e2b import Template, wait_for_file + +template = ( + Template() + .from_base_image() + .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) +) +``` + + + +### wait\_for\_timeout + +```python +def wait_for_timeout(timeout: int) +``` + +Wait for a specified timeout before considering the sandbox ready. + +Uses `sleep` command to wait for a fixed duration. + +**Arguments**: + +- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) + +**Returns**: + +ReadyCmd that waits for the specified duration +Example +```python +from e2b import Template, wait_for_timeout + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds +) +``` diff --git a/docs/sdk-reference/python-sdk/v2.18.0/sandbox_async.mdx b/docs/sdk-reference/python-sdk/v2.18.0/sandbox_async.mdx new file mode 100644 index 00000000..a21bda09 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.18.0/sandbox_async.mdx @@ -0,0 +1,2282 @@ +--- +sidebarTitle: "Sandbox Async" +--- + + + + + + +## AsyncSandbox + +```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](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### git + +```python +@property +def git() -> Git +``` + +Module for running git operations in the sandbox. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```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 +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + + +### create + +```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: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + network: Optional[SandboxNetworkOpts] = None, + lifecycle: Optional[SandboxLifecycle] = None, + **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`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. +- `mcp`: MCP server to enable in the sandbox +- `network`: Sandbox network configuration +- `lifecycle`: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` (default) or ``"pause"``; ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout="pause"``). Example: ``{"on_timeout": "pause", "auto_resume": True}`` + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```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** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await sandbox.pause() + +same_sandbox = await sandbox.connect() +``` + + + +### connect + +```python +@overload +@staticmethod +async def connect(sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> "AsyncSandbox" +``` + +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** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await AsyncSandbox.pause(sandbox.sandbox_id) + +same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id) +``` + + + +### connect + +```python +@class_method_variant("_cls_connect_sandbox") +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** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await sandbox.pause() + +same_sandbox = await sandbox.connect() +``` + + + +### kill + +```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 +@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 +@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 +@overload +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +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 +@overload +@staticmethod +async def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +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 +@class_method_variant("_cls_set_timeout") +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +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 +@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 +@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 +@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 +@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 +@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 +@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 +@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, + mcp: Optional[McpServer] = None, + **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`. +- `mcp`: MCP server to enable in the sandbox + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### pause + +```python +@overload +async def pause(**opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### pause + +```python +@overload +@staticmethod +async def pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### pause + +```python +@class_method_variant("_cls_pause") +async def pause(**opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### beta\_pause + +```python +@class_method_variant("_cls_pause") +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +:deprecated: Use `pause()` instead. + + + +### create\_snapshot + +```python +@overload +async def create_snapshot(**opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshot_id` with `AsyncSandbox.create(snapshot_id)` to create a new sandbox from the snapshot. + +**Returns**: + +Snapshot information including the snapshot ID + + + +### create\_snapshot + +```python +@overload +@staticmethod +async def create_snapshot(sandbox_id: str, + **opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot from the sandbox specified by sandbox ID. + +The sandbox will be paused while the snapshot is being created. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Snapshot information including the snapshot ID + + + +### create\_snapshot + +```python +@class_method_variant("_cls_create_snapshot") +async def create_snapshot(**opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshot_id` with `AsyncSandbox.create(snapshot_id)` to create a new sandbox from the snapshot. + +**Returns**: + +Snapshot information including the snapshot ID + + + +### list\_snapshots + +```python +@overload +def list_snapshots(limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSnapshotPaginator +``` + +List snapshots for this sandbox. + +**Arguments**: + +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### list\_snapshots + +```python +@overload +@staticmethod +def list_snapshots(sandbox_id: Optional[str] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSnapshotPaginator +``` + +List all snapshots. + +**Arguments**: + +- `sandbox_id`: Filter snapshots by source sandbox ID +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### list\_snapshots + +```python +@class_method_variant("_cls_list_snapshots") +def list_snapshots(limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSnapshotPaginator +``` + +List snapshots for this sandbox. + +**Arguments**: + +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### delete\_snapshot + +```python +@staticmethod +async def delete_snapshot(snapshot_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Delete a snapshot. + +**Arguments**: + +- `snapshot_id`: Snapshot ID + +**Returns**: + +`True` if the snapshot was deleted, `False` if it was not found + + + +### get\_mcp\_token + +```python +async def get_mcp_token() -> Optional[str] +``` + +Get the MCP token for the sandbox. + +**Returns**: + +MCP token for the sandbox, or None if MCP is not enabled. + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxBase) +``` + + + +### list + +```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 + + + + + + + + + +## AsyncSandboxPaginator + +```python +class AsyncSandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python +paginator = AsyncSandbox.list() + +while paginator.has_next: + sandboxes = await paginator.next_items() + print(sandboxes) +``` + + + +### next\_items + +```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 + + + +## AsyncSnapshotPaginator + +```python +class AsyncSnapshotPaginator(SnapshotPaginatorBase) +``` + +Paginator for listing snapshots. + +**Example**: + +```python +paginator = AsyncSandbox.list_snapshots() + +while paginator.has_next: + snapshots = await paginator.next_items() + print(snapshots) +``` + + + +### next\_items + +```python +async def next_items() -> List[SnapshotInfo] +``` + +Returns the next page of snapshots. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of snapshots + + + + + + +## Git + +```python +class Git() +``` + +Async module for running git operations in the sandbox. + + + +### \_\_init\_\_ + +```python +def __init__(commands: Commands) -> None +``` + +Create a Git helper bound to the sandbox command runner. + +**Arguments**: + +- `commands`: Command runner used to execute git commands + + + +### clone + +```python +async def clone(url: str, + path: Optional[str] = None, + branch: Optional[str] = None, + depth: Optional[int] = None, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None, + dangerously_store_credentials: bool = False) +``` + +Clone a git repository into the sandbox. + +**Arguments**: + +- `url`: Git repository URL +- `path`: Destination path for the clone +- `branch`: Branch to check out +- `depth`: If set, perform a shallow clone with this depth +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** +- `dangerously_store_credentials`: Store credentials in the cloned repository when True + +**Returns**: + +Command result from the command runner + + + +### init + +```python +async def init(path: str, + bare: bool = False, + initial_branch: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Initialize a new git repository. + +**Arguments**: + +- `path`: Destination path for the repository +- `bare`: Create a bare repository when True +- `initial_branch`: Initial branch name (for example, "main") +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### remote\_add + +```python +async def remote_add(path: str, + name: str, + url: str, + fetch: bool = False, + overwrite: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Add (or update) a remote for a repository. + +**Arguments**: + +- `path`: Repository path +- `name`: Remote name (for example, "origin") +- `url`: Remote URL +- `fetch`: Fetch the remote after adding it when True +- `overwrite`: Overwrite the remote URL if it already exists when True +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### remote\_get + +```python +async def remote_get(path: str, + name: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Optional[str] +``` + +Get the URL for a git remote. + +Returns `None` when the remote does not exist. + +**Arguments**: + +- `path`: Repository path +- `name`: Remote name (for example, "origin") +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Remote URL if present, otherwise `None` + + + +### status + +```python +async def status(path: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> GitStatus +``` + +Get repository status information. + +**Arguments**: + +- `path`: Repository path +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Parsed git status + + + +### branches + +```python +async def branches(path: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> GitBranches +``` + +List branches in a repository. + +**Arguments**: + +- `path`: Repository path +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Parsed branch list + + + +### create\_branch + +```python +async def create_branch(path: str, + branch: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Create and check out a new branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to create +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### checkout\_branch + +```python +async def checkout_branch(path: str, + branch: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Check out an existing branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to check out +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### delete\_branch + +```python +async def delete_branch(path: str, + branch: str, + force: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Delete a branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to delete +- `force`: Force deletion with `-D` when `True` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### add + +```python +async def add(path: str, + files: Optional[List[str]] = None, + all: bool = True, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Stage files for commit. + +**Arguments**: + +- `path`: Repository path +- `files`: Files to add; when omitted, adds the current directory +- `all`: When `True` and `files` is omitted, stage all changes +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### commit + +```python +async def commit(path: str, + message: str, + author_name: Optional[str] = None, + author_email: Optional[str] = None, + allow_empty: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Create a commit in the repository. + +**Arguments**: + +- `path`: Repository path +- `message`: Commit message +- `author_name`: Commit author name +- `author_email`: Commit author email +- `allow_empty`: Allow empty commits when `True` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### reset + +```python +async def reset(path: str, + mode: Optional[str] = None, + target: Optional[str] = None, + paths: Optional[List[str]] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Reset the current HEAD to a specified state. + +**Arguments**: + +- `path`: Repository path +- `mode`: Reset mode (soft, mixed, hard, merge, keep) +- `target`: Commit, branch, or ref to reset to (defaults to HEAD) +- `paths`: Paths to reset +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### restore + +```python +async def restore(path: str, + paths: List[str], + staged: Optional[bool] = None, + worktree: Optional[bool] = None, + source: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Restore working tree files or unstage changes. + +**Arguments**: + +- `path`: Repository path +- `paths`: Paths to restore (use ["."] for all) +- `staged`: When True, restore the index (unstage) +- `worktree`: When True, restore working tree files +- `source`: Restore from the given source (commit, branch, or ref) +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### push + +```python +async def push(path: str, + remote: Optional[str] = None, + branch: Optional[str] = None, + set_upstream: bool = True, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Push commits to a remote. + +**Arguments**: + +- `path`: Repository path +- `remote`: Remote name, e.g. `origin` +- `branch`: Branch name to push +- `set_upstream`: Set upstream tracking when `True` +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### pull + +```python +async def pull(path: str, + remote: Optional[str] = None, + branch: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Pull changes from a remote. + +**Arguments**: + +- `path`: Repository path +- `remote`: Remote name, e.g. `origin` +- `branch`: Branch name to pull +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### set\_config + +```python +async def set_config(key: str, + value: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Set a git config value. + +Use `scope="local"` together with `path` to configure a specific repository. + +**Arguments**: + +- `key`: Git config key (e.g. `pull.rebase`) +- `value`: Git config value +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### get\_config + +```python +async def get_config(key: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Optional[str] +``` + +Get a git config value. + +Returns `None` when the key is not set in the requested scope. + +**Arguments**: + +- `key`: Git config key (e.g. `pull.rebase`) +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Config value if present, otherwise `None` + + + +### dangerously\_authenticate + +```python +async def dangerously_authenticate(username: str, + password: str, + host: str = "github.com", + protocol: str = "https", + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Dangerously authenticate git globally via the credential helper. + +This persists credentials in the credential store and may be accessable to agents running on the sandbox. +Prefer short-lived credentials when possible. + +**Arguments**: + +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `host`: Host to authenticate for, defaults to `github.com` +- `protocol`: Protocol to authenticate for, defaults to `https` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### configure\_user + +```python +async def configure_user(name: str, + email: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Configure git user name and email. + +**Arguments**: + +- `name`: Git user name +- `email`: Git user email +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + + + + +## AsyncWatchHandle + +```python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + + +### stop + +```python +async def stop() +``` + +Stop watching the directory. + + + + + + +## Filesystem + +```python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Optional[Username] = None, + 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 +@overload +async def read(path: str, + format: Literal["bytes"], + user: Optional[Username] = None, + 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 +@overload +async def read( + path: str, + format: Literal["stream"], + user: Optional[Username] = None, + 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 +async def write(path: str, + data: Union[str, bytes, IO], + user: Optional[Username] = None, + 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 +async def write_files( + files: List[WriteEntry], + user: Optional[Username] = None, + 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 +async def list(path: str, + depth: Optional[int] = 1, + user: Optional[Username] = None, + 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 +async def exists(path: str, + user: Optional[Username] = None, + 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 +async def get_info(path: str, + user: Optional[Username] = None, + 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 +async def remove(path: str, + user: Optional[Username] = None, + 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 +async def rename(old_path: str, + new_path: str, + user: Optional[Username] = None, + 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 +async def make_dir(path: str, + user: Optional[Username] = None, + 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 +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Optional[Username] = None, + 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 +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### stdout + +```python +@property +def stdout() +``` + +Command stdout output. + + + +### stderr + +```python +@property +def stderr() +``` + +Command stderr output. + + + +### error + +```python +@property +def error() +``` + +Command execution error message. + + + +### exit\_code + +```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 +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 +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 +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 +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```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 +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 +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Optional[Username] = None, + 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 + + + +### connect + +```python +async def connect( + pid: int, + on_data: OutputHandler[PtyOutput], + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Connect to a running PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY to connect to. You can get the list of running PTYs using `sandbox.pty.list()`. +- `on_data`: Callback to handle PTY data +- `timeout`: Timeout for the PTY connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```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 +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```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 +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 +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 +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + stdin: Optional[bool] = 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 +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `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 +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + stdin: Optional[bool] = 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 +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `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 +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 diff --git a/docs/sdk-reference/python-sdk/v2.18.0/sandbox_sync.mdx b/docs/sdk-reference/python-sdk/v2.18.0/sandbox_sync.mdx new file mode 100644 index 00000000..916a8e62 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.18.0/sandbox_sync.mdx @@ -0,0 +1,2235 @@ +--- +sidebarTitle: "Sandbox Sync" +--- + + + + + + +## Sandbox + +```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](https://e2b.dev/docs). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import Sandbox + +sandbox = Sandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### git + +```python +@property +def git() -> Git +``` + +Module for running git operations in the sandbox. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +:deprecated: This constructor is deprecated + +Use `Sandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```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 +sandbox = Sandbox.create() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + + +### create + +```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, + mcp: Optional[McpServer] = None, + network: Optional[SandboxNetworkOpts] = None, + lifecycle: Optional[SandboxLifecycle] = None, + **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`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. +- `mcp`: MCP server to enable in the sandbox +- `network`: Sandbox network configuration +- `lifecycle`: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` (default) or ``"pause"``; ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout="pause"``). Example: ``{"on_timeout": "pause", "auto_resume": True}`` + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```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** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +sandbox.pause() + +same_sandbox = sandbox.connect() + + + +### connect + +```python +@overload +@staticmethod +def connect(sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> "Sandbox" +``` + +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**. +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +Sandbox.pause(sandbox.sandbox_id) + +same_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + + +### connect + +```python +@class_method_variant("_cls_connect_sandbox") +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**. +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +sandbox.pause() + +same_sandbox = sandbox.connect() +``` + + + +### kill + +```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 +@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 +@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 +@overload +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +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 +@overload +@staticmethod +def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +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 +@class_method_variant("_cls_set_timeout") +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +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 +@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 +@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 +@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 +@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 +@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 +@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 +@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, + mcp: Optional[McpServer] = None, + **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`. +- `mcp`: MCP server to enable in the sandbox + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### pause + +```python +@overload +def pause(**opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox. + + + +### pause + +```python +@overload +@staticmethod +def pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + + + +### pause + +```python +@class_method_variant("_cls_pause") +def pause(**opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### beta\_pause + +```python +@class_method_variant("_cls_pause") +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +:deprecated: Use `pause()` instead. + + + +### create\_snapshot + +```python +@overload +def create_snapshot(**opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshot_id` with `Sandbox.create(snapshot_id)` to create a new sandbox from the snapshot. + +**Returns**: + +Snapshot information including the snapshot ID + + + +### create\_snapshot + +```python +@overload +@staticmethod +def create_snapshot(sandbox_id: str, + **opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot from the sandbox specified by sandbox ID. + +The sandbox will be paused while the snapshot is being created. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Snapshot information including the snapshot ID + + + +### create\_snapshot + +```python +@class_method_variant("_cls_create_snapshot") +def create_snapshot(**opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshot_id` with `Sandbox.create(snapshot_id)` to create a new sandbox from the snapshot. + +**Returns**: + +Snapshot information including the snapshot ID + + + +### list\_snapshots + +```python +@overload +def list_snapshots(limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SnapshotPaginator +``` + +List snapshots for this sandbox. + +**Arguments**: + +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### list\_snapshots + +```python +@overload +@staticmethod +def list_snapshots(sandbox_id: Optional[str] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SnapshotPaginator +``` + +List all snapshots. + +**Arguments**: + +- `sandbox_id`: Filter snapshots by source sandbox ID +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### list\_snapshots + +```python +@class_method_variant("_cls_list_snapshots") +def list_snapshots(limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SnapshotPaginator +``` + +List snapshots for this sandbox. + +**Arguments**: + +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### delete\_snapshot + +```python +@staticmethod +def delete_snapshot(snapshot_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Delete a snapshot. + +**Arguments**: + +- `snapshot_id`: Snapshot ID + +**Returns**: + +`True` if the snapshot was deleted, `False` if it was not found + + + +### get\_mcp\_token + +```python +def get_mcp_token() -> Optional[str] +``` + +Get the MCP token for the sandbox. + +**Returns**: + +MCP token for the sandbox, or None if MCP is not enabled. + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxBase) +``` + + + +### list + +```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 + + + + + + +## SandboxPaginator + +```python +class SandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python +paginator = Sandbox.list() + +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) +``` + + + +### next\_items + +```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 + + + +## SnapshotPaginator + +```python +class SnapshotPaginator(SnapshotPaginatorBase) +``` + +Paginator for listing snapshots. + +**Example**: + +```python +paginator = Sandbox.list_snapshots() + +while paginator.has_next: + snapshots = paginator.next_items() + print(snapshots) +``` + + + +### next\_items + +```python +def next_items() -> List[SnapshotInfo] +``` + +Returns the next page of snapshots. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of snapshots + + + + + + +## Git + +```python +class Git() +``` + +Module for running git operations in the sandbox. + + + +### \_\_init\_\_ + +```python +def __init__(commands: Commands) -> None +``` + +Create a Git helper bound to the sandbox command runner. + +**Arguments**: + +- `commands`: Command runner used to execute git commands + + + +### clone + +```python +def clone(url: str, + path: Optional[str] = None, + branch: Optional[str] = None, + depth: Optional[int] = None, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None, + dangerously_store_credentials: bool = False) +``` + +Clone a git repository into the sandbox. + +**Arguments**: + +- `url`: Git repository URL +- `path`: Destination path for the clone +- `branch`: Branch to check out +- `depth`: If set, perform a shallow clone with this depth +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** +- `dangerously_store_credentials`: Store credentials in the cloned repository when True + +**Returns**: + +Command result from the command runner + + + +### init + +```python +def init(path: str, + bare: bool = False, + initial_branch: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Initialize a new git repository. + +**Arguments**: + +- `path`: Destination path for the repository +- `bare`: Create a bare repository when True +- `initial_branch`: Initial branch name (for example, "main") +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### remote\_add + +```python +def remote_add(path: str, + name: str, + url: str, + fetch: bool = False, + overwrite: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Add (or update) a remote for a repository. + +**Arguments**: + +- `path`: Repository path +- `name`: Remote name (for example, "origin") +- `url`: Remote URL +- `fetch`: Fetch the remote after adding it when True +- `overwrite`: Overwrite the remote URL if it already exists when True +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### remote\_get + +```python +def remote_get(path: str, + name: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Optional[str] +``` + +Get the URL for a git remote. + +Returns `None` when the remote does not exist. + +**Arguments**: + +- `path`: Repository path +- `name`: Remote name (for example, "origin") +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Remote URL if present, otherwise `None` + + + +### status + +```python +def status(path: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> GitStatus +``` + +Get repository status information. + +**Arguments**: + +- `path`: Repository path +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Parsed git status + + + +### branches + +```python +def branches(path: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> GitBranches +``` + +List branches in a repository. + +**Arguments**: + +- `path`: Repository path +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Parsed branch list + + + +### create\_branch + +```python +def create_branch(path: str, + branch: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Create and check out a new branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to create +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### checkout\_branch + +```python +def checkout_branch(path: str, + branch: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Check out an existing branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to check out +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### delete\_branch + +```python +def delete_branch(path: str, + branch: str, + force: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Delete a branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to delete +- `force`: Force deletion with `-D` when `True` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### add + +```python +def add(path: str, + files: Optional[List[str]] = None, + all: bool = True, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Stage files for commit. + +**Arguments**: + +- `path`: Repository path +- `files`: Files to add; when omitted, adds the current directory +- `all`: When `True` and `files` is omitted, stage all changes +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### commit + +```python +def commit(path: str, + message: str, + author_name: Optional[str] = None, + author_email: Optional[str] = None, + allow_empty: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Create a commit in the repository. + +**Arguments**: + +- `path`: Repository path +- `message`: Commit message +- `author_name`: Commit author name +- `author_email`: Commit author email +- `allow_empty`: Allow empty commits when `True` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### reset + +```python +def reset(path: str, + mode: Optional[str] = None, + target: Optional[str] = None, + paths: Optional[List[str]] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Reset the current HEAD to a specified state. + +**Arguments**: + +- `path`: Repository path +- `mode`: Reset mode (soft, mixed, hard, merge, keep) +- `target`: Commit, branch, or ref to reset to (defaults to HEAD) +- `paths`: Paths to reset +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### restore + +```python +def restore(path: str, + paths: List[str], + staged: Optional[bool] = None, + worktree: Optional[bool] = None, + source: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Restore working tree files or unstage changes. + +**Arguments**: + +- `path`: Repository path +- `paths`: Paths to restore (use ["."] for all) +- `staged`: When True, restore the index (unstage) +- `worktree`: When True, restore working tree files +- `source`: Restore from the given source (commit, branch, or ref) +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### push + +```python +def push(path: str, + remote: Optional[str] = None, + branch: Optional[str] = None, + set_upstream: bool = True, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Push commits to a remote. + +**Arguments**: + +- `path`: Repository path +- `remote`: Remote name, e.g. `origin` +- `branch`: Branch name to push +- `set_upstream`: Set upstream tracking when `True` +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### pull + +```python +def pull(path: str, + remote: Optional[str] = None, + branch: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Pull changes from a remote. + +**Arguments**: + +- `path`: Repository path +- `remote`: Remote name, e.g. `origin` +- `branch`: Branch name to pull +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### set\_config + +```python +def set_config(key: str, + value: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Set a git config value. + +Use `scope="local"` together with `path` to configure a specific repository. + +**Arguments**: + +- `key`: Git config key (e.g. `pull.rebase`) +- `value`: Git config value +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### get\_config + +```python +def get_config(key: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Optional[str] +``` + +Get a git config value. + +Returns `None` when the key is not set in the requested scope. + +**Arguments**: + +- `key`: Git config key (e.g. `pull.rebase`) +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Config value if present, otherwise `None` + + + +### dangerously\_authenticate + +```python +def dangerously_authenticate(username: str, + password: str, + host: str = "github.com", + protocol: str = "https", + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Dangerously authenticate git globally via the credential helper. + +This persists credentials in the credential store and may be accessable to agents running on the sandbox. +Prefer short-lived credentials when possible. + +**Arguments**: + +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `host`: Host to authenticate for, defaults to `github.com` +- `protocol`: Protocol to authenticate for, defaults to `https` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### configure\_user + +```python +def configure_user(name: str, + email: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Configure git user name and email. + +**Arguments**: + +- `name`: Git user name +- `email`: Git user email +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + + + + +## WatchHandle + +```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 +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 +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 +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Optional[Username] = None, + 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 +@overload +def read(path: str, + format: Literal["bytes"], + user: Optional[Username] = None, + 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 +@overload +def read(path: str, + format: Literal["stream"], + user: Optional[Username] = None, + 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 +def write(path: str, + data: Union[str, bytes, IO], + user: Optional[Username] = None, + 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 +def write_files(files: List[WriteEntry], + user: Optional[Username] = None, + 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 +def list(path: str, + depth: Optional[int] = 1, + user: Optional[Username] = None, + 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 +def exists(path: str, + user: Optional[Username] = None, + 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 +def get_info(path: str, + user: Optional[Username] = None, + 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 +def remove(path: str, + user: Optional[Username] = None, + 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 +def rename(old_path: str, + new_path: str, + user: Optional[Username] = None, + 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 +def make_dir(path: str, + user: Optional[Username] = None, + 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 +def watch_dir(path: str, + user: Optional[Username] = None, + 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 +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### \_\_iter\_\_ + +```python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + + +### disconnect + +```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 +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 +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + + + +## Pty + +```python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```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 +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 +def create(size: PtySize, + user: Optional[Username] = None, + 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 + + + +### connect + +```python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Connect to a running PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY to connect to. You can get the list of running PTYs using `sandbox.pty.list()`. +- `timeout`: Timeout for the PTY connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```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 +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```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 +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 +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 +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + stdin: Optional[bool] = 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 +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `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 +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + stdin: Optional[bool] = 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 +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `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 +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 diff --git a/docs/sdk-reference/python-sdk/v2.18.0/template.mdx b/docs/sdk-reference/python-sdk/v2.18.0/template.mdx new file mode 100644 index 00000000..6f7ddfa5 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.18.0/template.mdx @@ -0,0 +1,1924 @@ +--- +sidebarTitle: "Template" +--- + + + + + + +## TemplateBuilder + +```python +class TemplateBuilder() +``` + +Builder class for adding instructions to an E2B template. + +All methods return self to allow method chaining. + + + +### copy + +```python +def copy(src: Union[Union[str, Path], List[Union[str, Path]]], + dest: Union[str, Path], + force_upload: Optional[Literal[True]] = None, + user: Optional[str] = None, + mode: Optional[int] = None, + resolve_symlinks: Optional[bool] = None) -> "TemplateBuilder" +``` + +Copy files or directories from the local filesystem into the template. + +**Arguments**: + +- `src`: Source file(s) or directory path(s) to copy +- `dest`: Destination path in the template +- `force_upload`: Force upload even if files are cached +- `user`: User and optionally group (user:group) to own the files +- `mode`: File permissions in octal format (e.g., 0o755) +- `resolve_symlinks`: Whether to resolve symlinks + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.copy('requirements.txt', '/home/user/') +template.copy(['app.py', 'config.py'], '/app/', mode=0o755) +``` + + + +### copy\_items + +```python +def copy_items(items: List[CopyItem]) -> "TemplateBuilder" +``` + +Copy multiple files or directories using a list of copy items. + +**Arguments**: + +- `items`: List of CopyItem dictionaries with src, dest, and optional parameters + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.copy_items([ + {'src': 'app.py', 'dest': '/app/'}, + {'src': 'config.py', 'dest': '/app/', 'mode': 0o644} +]) +``` + + + +### remove + +```python +def remove(path: Union[Union[str, Path], List[Union[str, Path]]], + force: bool = False, + recursive: bool = False, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Remove files or directories in the template. + +**Arguments**: + +- `path`: File(s) or directory path(s) to remove +- `force`: Force removal without prompting +- `recursive`: Remove directories recursively +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.remove('/tmp/cache', recursive=True, force=True) +template.remove('/tmp/cache', recursive=True, force=True, user='root') +``` + + + +### rename + +```python +def rename(src: Union[str, Path], + dest: Union[str, Path], + force: bool = False, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Rename or move a file or directory in the template. + +**Arguments**: + +- `src`: Source path +- `dest`: Destination path +- `force`: Force rename without prompting +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', user='root') +``` + + + +### make\_dir + +```python +def make_dir(path: Union[Union[str, Path], List[Union[str, Path]]], + mode: Optional[int] = None, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Create directory(ies) in the template. + +**Arguments**: + +- `path`: Directory path(s) to create +- `mode`: Directory permissions in octal format (e.g., 0o755) +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.make_dir('/app/data', mode=0o755) +template.make_dir(['/app/logs', '/app/cache']) +template.make_dir('/app/data', mode=0o755, user='root') +``` + + + +### make\_symlink + +```python +def make_symlink(src: Union[str, Path], + dest: Union[str, Path], + user: Optional[str] = None, + force: bool = False) -> "TemplateBuilder" +``` + +Create a symbolic link in the template. + +**Arguments**: + +- `src`: Source path (target of the symlink) +- `dest`: Destination path (location of the symlink) +- `user`: User to run the command as +- `force`: Force symlink without prompting + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.make_symlink('/usr/bin/python3', '/usr/bin/python') +template.make_symlink('/usr/bin/python3', '/usr/bin/python', user='root') +template.make_symlink('/usr/bin/python3', '/usr/bin/python', force=True) +``` + + + +### run\_cmd + +```python +def run_cmd(command: Union[str, List[str]], + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Run a shell command during template build. + +**Arguments**: + +- `command`: Command string or list of commands to run (joined with &&) +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.run_cmd('apt-get update') +template.run_cmd(['pip install numpy', 'pip install pandas']) +template.run_cmd('apt-get install vim', user='root') +``` + + + +### set\_workdir + +```python +def set_workdir(workdir: Union[str, Path]) -> "TemplateBuilder" +``` + +Set the working directory for subsequent commands in the template. + +**Arguments**: + +- `workdir`: Path to set as the working directory + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_workdir('/app') +``` + + + +### set\_user + +```python +def set_user(user: str) -> "TemplateBuilder" +``` + +Set the user for subsequent commands in the template. + +**Arguments**: + +- `user`: Username to set + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_user('root') +``` + + + +### pip\_install + +```python +def pip_install(packages: Optional[Union[str, List[str]]] = None, + g: bool = True) -> "TemplateBuilder" +``` + +Install Python packages using pip. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, runs 'pip install .' in the current directory +- `g`: Install packages globally (default: True). If False, installs for user only + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.pip_install('numpy') +template.pip_install(['pandas', 'scikit-learn']) +template.pip_install('numpy', g=False) # Install for user only +template.pip_install() # Installs from current directory +``` + + + +### npm\_install + +```python +def npm_install(packages: Optional[Union[str, List[str]]] = None, + g: Optional[bool] = False, + dev: Optional[bool] = False) -> "TemplateBuilder" +``` + +Install Node.js packages using npm. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, installs from package.json +- `g`: Install packages globally +- `dev`: Install packages as dev dependencies + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.npm_install('express') +template.npm_install(['lodash', 'axios']) +template.npm_install('typescript', g=True) +template.npm_install() # Installs from package.json +``` + + + +### bun\_install + +```python +def bun_install(packages: Optional[Union[str, List[str]]] = None, + g: Optional[bool] = False, + dev: Optional[bool] = False) -> "TemplateBuilder" +``` + +Install Bun packages using bun. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, installs from package.json +- `g`: Install packages globally +- `dev`: Install packages as dev dependencies + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.bun_install('express') +template.bun_install(['lodash', 'axios']) +template.bun_install('tsx', g=True) +template.bun_install('typescript', dev=True) +template.bun_install() // Installs from package.json +``` + + + +### apt\_install + +```python +def apt_install(packages: Union[str, List[str]], + no_install_recommends: bool = False, + fix_missing: bool = False) -> "TemplateBuilder" +``` + +Install system packages using apt-get. + +**Arguments**: + +- `packages`: Package name(s) to install +- `no_install_recommends`: Whether to install recommended packages +- `fix_missing`: Whether to fix missing packages + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.apt_install('vim') +template.apt_install(['git', 'curl', 'wget']) +template.apt_install('vim', fix_missing=True) +``` + + + +### add\_mcp\_server + +```python +def add_mcp_server(servers: Union[str, List[str]]) -> "TemplateBuilder" +``` + +Install MCP servers using mcp-gateway. + +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +**Arguments**: + +- `servers`: MCP server name(s) + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.add_mcp_server('exa') +template.add_mcp_server(['brave', 'firecrawl', 'duckduckgo']) +``` + + + +### git\_clone + +```python +def git_clone(url: str, + path: Optional[Union[str, Path]] = None, + branch: Optional[str] = None, + depth: Optional[int] = None, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Clone a git repository into the template. + +**Arguments**: + +- `url`: Git repository URL +- `path`: Destination path for the clone +- `branch`: Branch to clone +- `depth`: Clone depth for shallow clones +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.git_clone('https://github.com/user/repo.git', '/app/repo') +template.git_clone('https://github.com/user/repo.git', branch='main', depth=1) +template.git_clone('https://github.com/user/repo.git', '/app/repo', user='root') +``` + + + +### beta\_dev\_container\_prebuild + +```python +def beta_dev_container_prebuild( + devcontainer_directory: Union[str, Path]) -> "TemplateBuilder" +``` + +Prebuild a devcontainer from the specified directory during the build process. + +**Arguments**: + +- `devcontainer_directory`: Path to the devcontainer directory + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_dev_container_prebuild('/my-devcontainer') +``` + + + +### beta\_set\_dev\_container\_start + +```python +def beta_set_dev_container_start( + devcontainer_directory: Union[str, Path]) -> "TemplateFinal" +``` + +Start a devcontainer from the specified directory and set it as the start command. + +This method returns `TemplateFinal`, which means it must be the last method in the chain. + +**Arguments**: + +- `devcontainer_directory`: Path to the devcontainer directory + +**Returns**: + +`TemplateFinal` class +Example +```python +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_set_devcontainer_start('/my-devcontainer') + +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_dev_container_prebuild('/my-devcontainer') +template.beta_set_dev_container_start('/my-devcontainer') +``` + + + +### set\_envs + +```python +def set_envs(envs: Dict[str, str]) -> "TemplateBuilder" +``` + +Set environment variables. + +Note: Environment variables defined here are available only during template build. + +**Arguments**: + +- `envs`: Dictionary of environment variable names and values + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_envs({'NODE_ENV': 'production', 'PORT': '8080'}) +``` + + + +### skip\_cache + +```python +def skip_cache() -> "TemplateBuilder" +``` + +Skip cache for all subsequent build instructions from this point. + +Call this before any instruction to force it and all following layers +to be rebuilt, ignoring any cached layers. + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.skip_cache().run_cmd('apt-get update') +``` + + + +### set\_start\_cmd + +```python +def set_start_cmd(start_cmd: str, + ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" +``` + +Set the command to start when the sandbox launches and the ready check command. + +**Arguments**: + +- `start_cmd`: Command to run when the sandbox starts +- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready + +**Returns**: + +`TemplateFinal` class +Example +```python +template.set_start_cmd( + 'python app.py', + 'curl http://localhost:8000/health' +) + +from e2b import wait_for_port, wait_for_url + +template.set_start_cmd( + 'python -m http.server 8000', + wait_for_port(8000) +) + +template.set_start_cmd( + 'npm start', + wait_for_url('http://localhost:3000/health', 200) +) +``` + + + +### set\_ready\_cmd + +```python +def set_ready_cmd(ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" +``` + +Set the command to check if the sandbox is ready. + +**Arguments**: + +- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready + +**Returns**: + +`TemplateFinal` class +Example +```python +template.set_ready_cmd('curl http://localhost:8000/health') + +from e2b import wait_for_port, wait_for_file, wait_for_process + +template.set_ready_cmd(wait_for_port(3000)) + +template.set_ready_cmd(wait_for_file('/tmp/ready')) + +template.set_ready_cmd(wait_for_process('nginx')) +``` + + + +## TemplateFinal + +```python +class TemplateFinal() +``` + +Final template state after start/ready commands are set. + + + +## TemplateBase + +```python +class TemplateBase() +``` + +Base class for building E2B sandbox templates. + + + +### \_\_init\_\_ + +```python +def __init__(file_context_path: Optional[Union[str, Path]] = None, + file_ignore_patterns: Optional[List[str]] = None) +``` + +Create a new template builder instance. + +**Arguments**: + +- `file_context_path`: Base path for resolving relative file paths in copy operations +- `file_ignore_patterns`: List of glob patterns to ignore when copying files + + + +### skip\_cache + +```python +def skip_cache() -> "TemplateBase" +``` + +Skip cache for all subsequent build instructions from this point. + +**Returns**: + +`TemplateBase` class +Example +```python +template.skip_cache().from_python_image('3.11') +``` + + + +### from\_debian\_image + +```python +def from_debian_image(variant: str = "stable") -> TemplateBuilder +``` + +Start template from a Debian base image. + +**Arguments**: + +- `variant`: Debian image variant + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_debian_image('bookworm') +``` + + + +### from\_ubuntu\_image + +```python +def from_ubuntu_image(variant: str = "latest") -> TemplateBuilder +``` + +Start template from an Ubuntu base image. + +**Arguments**: + +- `variant`: Ubuntu image variant (default: 'latest') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_ubuntu_image('24.04') +``` + + + +### from\_python\_image + +```python +def from_python_image(version: str = "3") -> TemplateBuilder +``` + +Start template from a Python base image. + +**Arguments**: + +- `version`: Python version (default: '3') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_python_image('3') +``` + + + +### from\_node\_image + +```python +def from_node_image(variant: str = "lts") -> TemplateBuilder +``` + +Start template from a Node.js base image. + +**Arguments**: + +- `variant`: Node.js image variant (default: 'lts') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_node_image('24') +``` + + + +### from\_bun\_image + +```python +def from_bun_image(variant: str = "latest") -> TemplateBuilder +``` + +Start template from a Bun base image. + +**Arguments**: + +- `variant`: Bun image variant (default: 'latest') + +**Returns**: + +`TemplateBuilder` class + + + +### from\_base\_image + +```python +def from_base_image() -> TemplateBuilder +``` + +Start template from the E2B base image (e2bdev/base:latest). + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_base_image() +``` + + + +### from\_image + +```python +def from_image(image: str, + username: Optional[str] = None, + password: Optional[str] = None) -> TemplateBuilder +``` + +Start template from a Docker image. + +**Arguments**: + +- `image`: Docker image name (e.g., 'ubuntu:24.04') +- `username`: Username for private registry authentication +- `password`: Password for private registry authentication + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_image('python:3') + +Template().from_image('myregistry.com/myimage:latest', username='user', password='pass') +``` + + + +### from\_template + +```python +def from_template(template: str) -> TemplateBuilder +``` + +Start template from an existing E2B template. + +**Arguments**: + +- `template`: E2B template ID or alias + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_template('my-base-template') +``` + + + +### from\_dockerfile + +```python +def from_dockerfile(dockerfile_content_or_path: str) -> TemplateBuilder +``` + +Parse a Dockerfile and convert it to Template SDK format. + +**Arguments**: + +- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_dockerfile('Dockerfile') +Template().from_dockerfile('FROM python:3\nRUN pip install numpy') +``` + + + +### from\_aws\_registry + +```python +def from_aws_registry(image: str, access_key_id: str, secret_access_key: str, + region: str) -> TemplateBuilder +``` + +Start template from an AWS ECR registry image. + +**Arguments**: + +- `image`: Docker image name from AWS ECR +- `access_key_id`: AWS access key ID +- `secret_access_key`: AWS secret access key +- `region`: AWS region + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_aws_registry( + '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', + access_key_id='AKIA...', + secret_access_key='...', + region='us-west-2' +) +``` + + + +### from\_gcp\_registry + +```python +def from_gcp_registry( + image: str, service_account_json: Union[str, dict]) -> TemplateBuilder +``` + +Start template from a GCP Artifact Registry or Container Registry image. + +**Arguments**: + +- `image`: Docker image name from GCP registry +- `service_account_json`: Service account JSON string, dict, or path to JSON file + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_gcp_registry( + 'gcr.io/myproject/myimage:latest', + service_account_json='path/to/service-account.json' +) +``` + + + +### to\_json + +```python +@staticmethod +def to_json(template: "TemplateClass") -> str +``` + +Convert a template to JSON representation. + +**Arguments**: + +- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) + +**Returns**: + +JSON string representation of the template +Example +```python +template = Template().from_python_image('3').copy('app.py', '/app/') +json_str = TemplateBase.to_json(template) +``` + + + +### to\_dockerfile + +```python +@staticmethod +def to_dockerfile(template: "TemplateClass") -> str +``` + +Convert a template to Dockerfile format. + +Note: Templates based on other E2B templates cannot be converted to Dockerfile. + +**Arguments**: + +- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) + +**Raises**: + +- `ValueError`: If the template is based on another E2B template or has no base image +Example +```python +template = Template().from_python_image('3').copy('app.py', '/app/') +dockerfile = TemplateBase.to_dockerfile(template) +``` + +**Returns**: + +Dockerfile string representation + + + + + + +## LogEntry + +```python +@dataclass +class LogEntry() +``` + +Represents a single log entry from the template build process. + + + +## LogEntryStart + +```python +@dataclass +class LogEntryStart(LogEntry) +``` + +Special log entry indicating the start of a build process. + + + +## LogEntryEnd + +```python +@dataclass +class LogEntryEnd(LogEntry) +``` + +Special log entry indicating the end of a build process. + + + +### TIMER\_UPDATE\_INTERVAL\_MS + +Default minimum log level to display. + + + +### DEFAULT\_LEVEL + +Colored labels for each log level. + + + +### levels + +Numeric ordering of log levels for comparison (lower = less severe). + + + +### set\_interval + +```python +def set_interval(func, interval) +``` + +Returns a stop function that can be called to cancel the interval. + +Similar to JavaScript's setInterval. + +**Arguments**: + +- `func`: Function to execute at each interval +- `interval`: Interval duration in **seconds** + +**Returns**: + +Stop function that can be called to cancel the interval + + + +### default\_build\_logger + +```python +def default_build_logger( + min_level: Optional[LogEntryLevel] = None +) -> Callable[[LogEntry], None] +``` + +Create a default build logger with animated timer display. + +**Arguments**: + +- `min_level`: Minimum log level to display (default: 'info') + +**Returns**: + +Logger function that accepts LogEntry instances +Example +```python +from e2b import Template, default_build_logger + +template = Template().from_python_image() + +``` + + + + + + +### make\_traceback + +```python +def make_traceback( + caller_frame: Optional[FrameType]) -> Optional[TracebackType] +``` + +Create a TracebackType from a caller frame for error reporting. + +**Arguments**: + +- `caller_frame`: The caller's frame object, or None + +**Returns**: + +A TracebackType object for use with exception.with_traceback(), or None + + + +### validate\_relative\_path + +```python +def validate_relative_path(src: str, + stack_trace: Optional[TracebackType]) -> None +``` + +Validate that a source path for copy operations is a relative path that stays + +within the context directory. This prevents path traversal attacks and ensures +files are copied from within the expected directory. + +**Arguments**: + +- `src`: The source path to validate +- `stack_trace`: Optional stack trace for error reporting + +**Raises**: + +- `TemplateException`: If the path is absolute or escapes the context directory +Invalid paths: +- Absolute paths: /absolute/path, C:\Windows\path +- Parent directory escapes: ../foo, foo/../../bar, ./foo/../../../bar + +Valid paths: +- Simple relative: foo, foo/bar +- Current directory prefix: ./foo, ./foo/bar +- Internal parent refs that don't escape: foo/../bar (stays within context) + + + +### normalize\_build\_arguments + +```python +def normalize_build_arguments(name: Optional[str] = None, + alias: Optional[str] = None) -> str +``` + +Normalize build arguments from different parameter signatures. + +Handles string name or legacy alias parameter. + +**Arguments**: + +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. + +**Raises**: + +- `TemplateException`: If no template name is provided + +**Returns**: + +Normalized template name + + + +### read\_dockerignore + +```python +def read_dockerignore(context_path: str) -> List[str] +``` + +Read and parse a .dockerignore file. + +**Arguments**: + +- `context_path`: Directory path containing the .dockerignore file + +**Returns**: + +Array of ignore patterns (empty lines and comments are filtered out) + + + +### normalize\_path + +```python +def normalize_path(path: str) -> str +``` + +Normalize path separators to forward slashes for glob patterns (glob expects / even on Windows). + +**Arguments**: + +- `path`: The path to normalize + +**Returns**: + +The normalized path + + + +### get\_all\_files\_in\_path + +```python +def get_all_files_in_path(src: str, + context_path: str, + ignore_patterns: List[str], + include_directories: bool = True) -> List[str] +``` + +Get all files for a given path and ignore patterns. + +**Arguments**: + +- `src`: Path to the source directory +- `context_path`: Base directory for resolving relative paths +- `ignore_patterns`: Ignore patterns +- `include_directories`: Whether to include directories + +**Returns**: + +Array of files + + + +### calculate\_files\_hash + +```python +def calculate_files_hash(src: str, dest: str, context_path: str, + ignore_patterns: List[str], resolve_symlinks: bool, + stack_trace: Optional[TracebackType]) -> str +``` + +Calculate a hash of files being copied to detect changes for cache invalidation. + +The hash includes file content, metadata (mode, size), and relative paths. +Note: uid, gid, and mtime are excluded to ensure stable hashes across environments. + +**Arguments**: + +- `src`: Source path pattern for files to copy +- `dest`: Destination path where files will be copied +- `context_path`: Base directory for resolving relative paths +- `ignore_patterns`: Glob patterns to ignore +- `resolve_symlinks`: Whether to resolve symbolic links when hashing +- `stack_trace`: Optional stack trace for error reporting + +**Raises**: + +- `ValueError`: If no files match the source pattern + +**Returns**: + +Hex string hash of all files + + + +### tar\_file\_stream + +```python +def tar_file_stream(file_name: str, file_context_path: str, + ignore_patterns: List[str], + resolve_symlinks: bool) -> io.BytesIO +``` + +Create a tar stream of files matching a pattern. + +**Arguments**: + +- `file_name`: Glob pattern for files to include +- `file_context_path`: Base directory for resolving file paths +- `ignore_patterns`: Ignore patterns +- `resolve_symlinks`: Whether to resolve symbolic links + +**Returns**: + +Tar stream + + + +### strip\_ansi\_escape\_codes + +```python +def strip_ansi_escape_codes(text: str) -> str +``` + +Strip ANSI escape codes from a string. + +Source: https://github.com/chalk/ansi-regex/blob/main/index.js + +**Arguments**: + +- `text`: String with ANSI escape codes + +**Returns**: + +String without ANSI escape codes + + + +### get\_caller\_frame + +```python +def get_caller_frame(depth: int) -> Optional[FrameType] +``` + +Get the caller's stack frame at a specific depth. + +This is used to provide better error messages and debugging information +by tracking where template methods were called from in user code. + +**Arguments**: + +- `depth`: The depth of the stack trace to retrieve + +**Returns**: + +The caller frame, or None if not available + + + +### get\_caller\_directory + +```python +def get_caller_directory(depth: int) -> Optional[str] +``` + +Get the directory of the caller at a specific stack depth. + +This is used to determine the file_context_path when creating a template, +so file paths are resolved relative to the user's template file location. + +**Arguments**: + +- `depth`: The depth of the stack trace + +**Returns**: + +The caller's directory path, or None if not available + + + +### pad\_octal + +```python +def pad_octal(mode: int) -> str +``` + +Convert a numeric file mode to a zero-padded octal string. + +**Arguments**: + +- `mode`: File mode as a number (e.g., 493 for 0o755) + +**Returns**: + +Zero-padded 4-digit octal string (e.g., "0755") +Example +```python +pad_octal(0o755) # Returns "0755" +pad_octal(0o644) # Returns "0644" +``` + + + +### get\_build\_step\_index + +```python +def get_build_step_index(step: str, stack_traces_length: int) -> int +``` + +Get the array index for a build step based on its name. + +Special steps: +- BASE_STEP_NAME: Returns 0 (first step) +- FINALIZE_STEP_NAME: Returns the last index +- Numeric strings: Converted to number + +**Arguments**: + +- `step`: Build step name or number as string +- `stack_traces_length`: Total number of stack traces (used for FINALIZE_STEP_NAME) + +**Returns**: + +Index for the build step + + + +### read\_gcp\_service\_account\_json + +```python +def read_gcp_service_account_json(context_path: str, + path_or_content: Union[str, dict]) -> str +``` + +Read GCP service account JSON from a file or object. + +**Arguments**: + +- `context_path`: Base directory for resolving relative file paths +- `path_or_content`: Either a path to a JSON file or a service account object + +**Returns**: + +Service account JSON as a string + + + + + + +## DockerfFileFinalParserInterface + +```python +class DockerfFileFinalParserInterface(Protocol) +``` + +Protocol defining the final interface for Dockerfile parsing callbacks. + + + +## DockerfileParserInterface + +```python +class DockerfileParserInterface(Protocol) +``` + +Protocol defining the interface for Dockerfile parsing callbacks. + + + +### run\_cmd + +```python +def run_cmd(command: Union[str, List[str]], + user: Optional[str] = None) -> "DockerfileParserInterface" +``` + +Handle RUN instruction. + + + +### copy + +```python +def copy( + src: str, + dest: str, + force_upload: Optional[Literal[True]] = None, + user: Optional[str] = None, + mode: Optional[int] = None, + resolve_symlinks: Optional[bool] = None +) -> "DockerfileParserInterface" +``` + +Handle COPY instruction. + + + +### set\_workdir + +```python +def set_workdir(workdir: str) -> "DockerfileParserInterface" +``` + +Handle WORKDIR instruction. + + + +### set\_user + +```python +def set_user(user: str) -> "DockerfileParserInterface" +``` + +Handle USER instruction. + + + +### set\_envs + +```python +def set_envs(envs: Dict[str, str]) -> "DockerfileParserInterface" +``` + +Handle ENV instruction. + + + +### set\_start\_cmd + +```python +def set_start_cmd(start_cmd: str, + ready_cmd: str) -> "DockerfFileFinalParserInterface" +``` + +Handle CMD/ENTRYPOINT instruction. + + + +### parse\_dockerfile + +```python +def parse_dockerfile(dockerfile_content_or_path: str, + template_builder: DockerfileParserInterface) -> str +``` + +Parse a Dockerfile and convert it to Template SDK format. + +**Arguments**: + +- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file +- `template_builder`: Interface providing template builder methods + +**Raises**: + +- `ValueError`: If the Dockerfile is invalid or unsupported + +**Returns**: + +The base image from the Dockerfile + + + + + + +## TemplateBuildStatus + +```python +class TemplateBuildStatus(str, Enum) +``` + +Status of a template build. + + + +## BuildStatusReason + +```python +@dataclass +class BuildStatusReason() +``` + +Reason for the current build status (typically for errors). + + + +### message + +Message with the status reason. + + + +### step + +Step that failed. + + + +### log\_entries + +Log entries related to the status reason. + + + +## TemplateBuildStatusResponse + +```python +@dataclass +class TemplateBuildStatusResponse() +``` + +Response from getting build status. + + + +### build\_id + +Build identifier. + + + +### template\_id + +Template identifier. + + + +### status + +Current status of the build. + + + +### log\_entries + +Build log entries. + + + +### logs + +Build logs (raw strings). Deprecated: use log_entries instead. + + + +### reason + +Reason for the current status (typically for errors). + + + +## TemplateTagInfo + +```python +@dataclass +class TemplateTagInfo() +``` + +Information about assigned template tags. + + + +### build\_id + +Build identifier associated with this tag. + + + +### tags + +Assigned tags of the template. + + + +## TemplateTag + +```python +@dataclass +class TemplateTag() +``` + +Detailed information about a single template tag. + + + +### tag + +Name of the tag. + + + +### build\_id + +Build identifier associated with this tag. + + + +### created\_at + +When this tag was assigned. + + + +## InstructionType + +```python +class InstructionType(str, Enum) +``` + +Types of instructions that can be used in a template. + + + +## CopyItem + +```python +class CopyItem(TypedDict) +``` + +Configuration for a single file/directory copy operation. + + + +## Instruction + +```python +class Instruction(TypedDict) +``` + +Represents a single instruction in the template build process. + + + +## GenericDockerRegistry + +```python +class GenericDockerRegistry(TypedDict) +``` + +Configuration for a generic Docker registry with basic authentication. + + + +## AWSRegistry + +```python +class AWSRegistry(TypedDict) +``` + +Configuration for AWS Elastic Container Registry (ECR). + + + +## GCPRegistry + +```python +class GCPRegistry(TypedDict) +``` + +Configuration for Google Container Registry (GCR) or Artifact Registry. + + + +## TemplateType + +```python +class TemplateType(TypedDict) +``` + +Internal representation of a template for the E2B build API. + + + +## BuildInfo + +```python +@dataclass +class BuildInfo() +``` + +Information about a built template. + + + + +Special step name for the finalization phase of template building. +This is the last step that runs after all user-defined instructions. + + + +### FINALIZE\_STEP\_NAME + +Special step name for the base image phase of template building. +This is the first step that sets up the base image. + + + +### BASE\_STEP\_NAME + +Stack trace depth for capturing caller information. + +Depth levels: +1. TemplateClass +2. Caller method (e.g., copy(), from_image(), etc.) + +This depth is used to determine the original caller's location +for stack traces. + + + +### STACK\_TRACE\_DEPTH + +Default setting for whether to resolve symbolic links when copying files. +When False, symlinks are copied as symlinks rather than following them. + + + + + + +## ReadyCmd + +```python +class ReadyCmd() +``` + +Wrapper class for ready check commands. + + + +### wait\_for\_port + +```python +def wait_for_port(port: int) +``` + +Wait for a port to be listening. + +Uses `ss` command to check if a port is open and listening. + +**Arguments**: + +- `port`: Port number to wait for + +**Returns**: + +ReadyCmd that checks for the port +Example +```python +from e2b import Template, wait_for_port + +template = ( + Template() + .from_python_image() + .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) +) +``` + + + +### wait\_for\_url + +```python +def wait_for_url(url: str, status_code: int = 200) +``` + +Wait for a URL to return a specific HTTP status code. + +Uses `curl` to make HTTP requests and check the response status. + +**Arguments**: + +- `url`: URL to check (e.g., 'http://localhost:3000/health') +- `status_code`: Expected HTTP status code (default: 200) + +**Returns**: + +ReadyCmd that checks the URL +Example +```python +from e2b import Template, wait_for_url + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) +) +``` + + + +### wait\_for\_process + +```python +def wait_for_process(process_name: str) +``` + +Wait for a process with a specific name to be running. + +Uses `pgrep` to check if a process exists. + +**Arguments**: + +- `process_name`: Name of the process to wait for + +**Returns**: + +ReadyCmd that checks for the process +Example +```python +from e2b import Template, wait_for_process + +template = ( + Template() + .from_base_image() + .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) +) +``` + + + +### wait\_for\_file + +```python +def wait_for_file(filename: str) +``` + +Wait for a file to exist. + +Uses shell test command to check file existence. + +**Arguments**: + +- `filename`: Path to the file to wait for + +**Returns**: + +ReadyCmd that checks for the file +Example +```python +from e2b import Template, wait_for_file + +template = ( + Template() + .from_base_image() + .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) +) +``` + + + +### wait\_for\_timeout + +```python +def wait_for_timeout(timeout: int) +``` + +Wait for a specified timeout before considering the sandbox ready. + +Uses `sleep` command to wait for a fixed duration. + +**Arguments**: + +- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) + +**Returns**: + +ReadyCmd that waits for the specified duration +Example +```python +from e2b import Template, wait_for_timeout + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds +) +``` diff --git a/docs/sdk-reference/python-sdk/v2.18.0/template_async.mdx b/docs/sdk-reference/python-sdk/v2.18.0/template_async.mdx new file mode 100644 index 00000000..f75603fb --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.18.0/template_async.mdx @@ -0,0 +1,357 @@ +--- +sidebarTitle: "Template Async" +--- + + + + + + +## AsyncTemplate + +```python +class AsyncTemplate(TemplateBase) +``` + +Asynchronous template builder for E2B sandboxes. + + + +### build + +```python +@staticmethod +async def build(template: TemplateClass, + name: Optional[str] = None, + *, + alias: Optional[str] = None, + tags: Optional[List[str]] = None, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], None]] = None, + **opts: Unpack[ApiParams]) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure. + +**Arguments**: + +- `template`: The template to build +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. +- `tags`: Optional additional tags to assign to the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `on_build_logs`: Callback function to receive build logs during the build process +Example +```python +from e2b import AsyncTemplate + +template = ( + AsyncTemplate() + .from_python_image('3') + .copy('requirements.txt', '/home/user/') + .run_cmd('pip install -r /home/user/requirements.txt') +) + +await AsyncTemplate.build(template, 'my-python-env:v1.0') + +await AsyncTemplate.build(template, 'my-python-env', tags=['v1.1.0', 'stable']) +``` + + + +### build\_in\_background + +```python +@staticmethod +async def build_in_background(template: TemplateClass, + name: Optional[str] = None, + *, + alias: Optional[str] = None, + tags: Optional[List[str]] = None, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], + None]] = None, + **opts: Unpack[ApiParams]) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +**Arguments**: + +- `template`: The template to build +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. +- `tags`: Optional additional tags to assign to the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache + +**Returns**: + +BuildInfo containing the template ID and build ID +Example +```python +from e2b import AsyncTemplate + +template = ( + AsyncTemplate() + .from_python_image('3') + .run_cmd('echo "test"') + .set_start_cmd('echo "Hello"', 'sleep 1') +) + +build_info = await AsyncTemplate.build_in_background(template, 'my-python-env:v1.0') + +build_info = await AsyncTemplate.build_in_background(template, 'my-python-env', tags=['v1.1.0', 'stable']) +``` + + + +### get\_build\_status + +```python +@staticmethod +async def get_build_status(build_info: BuildInfo, + logs_offset: int = 0, + **opts: Unpack[ApiParams]) +``` + +Get the status of a build. + +**Arguments**: + +- `build_info`: Build identifiers returned from build_in_background +- `logs_offset`: Offset for fetching logs + +**Returns**: + +TemplateBuild containing the build status and logs +Example +```python +from e2b import AsyncTemplate + +build_info = await AsyncTemplate.build_in_background(template, alias='my-template') +status = await AsyncTemplate.get_build_status(build_info, logs_offset=0) +``` + + + +### exists + +```python +@staticmethod +async def exists(name: str, **opts: Unpack[ApiParams]) -> bool +``` + +Check if a template with the given name exists. + +**Arguments**: + +- `name`: Template name to check + +**Returns**: + +True if the name exists, False otherwise +Example +```python +from e2b import AsyncTemplate + +exists = await AsyncTemplate.exists('my-python-env') +if exists: + print('Template exists!') +``` + + + +### alias\_exists + +```python +@staticmethod +async def alias_exists(alias: str, **opts: Unpack[ApiParams]) -> bool +``` + +Check if a template with the given alias exists. + +Deprecated Use `exists` instead. + +**Arguments**: + +- `alias`: Template alias to check + +**Returns**: + +True if the alias exists, False otherwise +Example +```python +from e2b import AsyncTemplate + +exists = await AsyncTemplate.alias_exists('my-python-env') +if exists: + print('Template exists!') +``` + + + +### assign\_tags + +```python +@staticmethod +async def assign_tags(target_name: str, tags: Union[str, List[str]], + **opts: Unpack[ApiParams]) -> TemplateTagInfo +``` + +Assign tag(s) to an existing template build. + +**Arguments**: + +- `target_name`: Template name in 'name:tag' format (the source build to tag from) +- `tags`: Tag or tags to assign + +**Returns**: + +TemplateTagInfo with build_id and assigned tags +Example +```python +from e2b import AsyncTemplate + +result = await AsyncTemplate.assign_tags('my-template:v1.0', 'production') + +result = await AsyncTemplate.assign_tags('my-template:v1.0', ['production', 'stable']) +``` + + + +### remove\_tags + +```python +@staticmethod +async def remove_tags(name: str, tags: Union[str, List[str]], + **opts: Unpack[ApiParams]) -> None +``` + +Remove tag(s) from a template. + +**Arguments**: + +- `name`: Template name +- `tags`: Tag or tags to remove +Example +```python +from e2b import AsyncTemplate + +await AsyncTemplate.remove_tags('my-template', 'production') + +await AsyncTemplate.remove_tags('my-template', ['production', 'stable']) +``` + + + +### get\_tags + +```python +@staticmethod +async def get_tags(template_id: str, + **opts: Unpack[ApiParams]) -> List[TemplateTag] +``` + +Get all tags for a template. + +**Arguments**: + +- `template_id`: Template ID or name + +**Returns**: + +List of TemplateTag with tag name, build_id, and created_at +Example +```python +from e2b import AsyncTemplate + +tags = await AsyncTemplate.get_tags('my-template') +for tag in tags: + print(f"Tag: {tag.tag}, Build: {tag.build_id}, Created: {tag.created_at}") +``` + + + + + + +### check\_alias\_exists + +```python +async def check_alias_exists(client: AuthenticatedClient, alias: str) -> bool +``` + +Check if a template with the given alias exists. + +**Arguments**: + +- `client` - Authenticated API client +- `alias` - Template alias to check + + +**Returns**: + + True if the alias exists, False otherwise + + + +### assign\_tags + +```python +async def assign_tags(client: AuthenticatedClient, target_name: str, + tags: List[str]) -> TemplateTagInfo +``` + +Assign tag(s) to an existing template build. + +**Arguments**: + +- `client` - Authenticated API client +- `target_name` - Template name in 'name:tag' format (the source build to tag from) +- `tags` - Tags to assign + + +**Returns**: + + TemplateTagInfo with build_id and assigned tags + + + +### remove\_tags + +```python +async def remove_tags(client: AuthenticatedClient, name: str, + tags: List[str]) -> None +``` + +Remove tag(s) from a template. + +**Arguments**: + +- `client` - Authenticated API client +- `name` - Template name +- `tags` - List of tags to remove + + + +### get\_template\_tags + +```python +async def get_template_tags(client: AuthenticatedClient, + template_id: str) -> List[TemplateTag] +``` + +Get all tags for a template. + +**Arguments**: + +- `client` - Authenticated API client +- `template_id` - Template ID or name diff --git a/docs/sdk-reference/python-sdk/v2.18.0/template_sync.mdx b/docs/sdk-reference/python-sdk/v2.18.0/template_sync.mdx new file mode 100644 index 00000000..ff5cee37 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.18.0/template_sync.mdx @@ -0,0 +1,356 @@ +--- +sidebarTitle: "Template Sync" +--- + + + + + + +## Template + +```python +class Template(TemplateBase) +``` + +Synchronous template builder for E2B sandboxes. + + + +### build + +```python +@staticmethod +def build(template: TemplateClass, + name: Optional[str] = None, + *, + alias: Optional[str] = None, + tags: Optional[List[str]] = None, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], None]] = None, + **opts: Unpack[ApiParams]) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure. + +**Arguments**: + +- `template`: The template to build +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. +- `tags`: Optional additional tags to assign to the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `on_build_logs`: Callback function to receive build logs during the build process +Example +```python +from e2b import Template + +template = ( + Template() + .from_python_image('3') + .copy('requirements.txt', '/home/user/') + .run_cmd('pip install -r /home/user/requirements.txt') +) + +Template.build(template, 'my-python-env:v1.0') + +Template.build(template, 'my-python-env', tags=['v1.1.0', 'stable']) +``` + + + +### build\_in\_background + +```python +@staticmethod +def build_in_background(template: TemplateClass, + name: Optional[str] = None, + *, + alias: Optional[str] = None, + tags: Optional[List[str]] = None, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], + None]] = None, + **opts: Unpack[ApiParams]) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +**Arguments**: + +- `template`: The template to build +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. +- `tags`: Optional additional tags to assign to the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache + +**Returns**: + +BuildInfo containing the template ID and build ID +Example +```python +from e2b import Template + +template = ( + Template() + .from_python_image('3') + .run_cmd('echo "test"') + .set_start_cmd('echo "Hello"', 'sleep 1') +) + +build_info = Template.build_in_background(template, 'my-python-env:v1.0') + +build_info = Template.build_in_background(template, 'my-python-env', tags=['v1.1.0', 'stable']) +``` + + + +### get\_build\_status + +```python +@staticmethod +def get_build_status(build_info: BuildInfo, + logs_offset: int = 0, + **opts: Unpack[ApiParams]) +``` + +Get the status of a build. + +**Arguments**: + +- `build_info`: Build identifiers returned from build_in_background +- `logs_offset`: Offset for fetching logs + +**Returns**: + +TemplateBuild containing the build status and logs +Example +```python +from e2b import Template + +build_info = Template.build_in_background(template, alias='my-template') +status = Template.get_build_status(build_info, logs_offset=0) +``` + + + +### exists + +```python +@staticmethod +def exists(name: str, **opts: Unpack[ApiParams]) -> bool +``` + +Check if a template with the given name exists. + +**Arguments**: + +- `name`: Template name to check + +**Returns**: + +True if the name exists, False otherwise +Example +```python +from e2b import Template + +exists = Template.exists('my-python-env') +if exists: + print('Template exists!') +``` + + + +### alias\_exists + +```python +@staticmethod +def alias_exists(alias: str, **opts: Unpack[ApiParams]) -> bool +``` + +Check if a template with the given alias exists. + +Deprecated Use `exists` instead. + +**Arguments**: + +- `alias`: Template alias to check + +**Returns**: + +True if the alias exists, False otherwise +Example +```python +from e2b import Template + +exists = Template.alias_exists('my-python-env') +if exists: + print('Template exists!') +``` + + + +### assign\_tags + +```python +@staticmethod +def assign_tags(target_name: str, tags: Union[str, List[str]], + **opts: Unpack[ApiParams]) -> TemplateTagInfo +``` + +Assign tag(s) to an existing template build. + +**Arguments**: + +- `target_name`: Template name in 'name:tag' format (the source build to tag from) +- `tags`: Tag or tags to assign + +**Returns**: + +TemplateTagInfo with build_id and assigned tags +Example +```python +from e2b import Template + +result = Template.assign_tags('my-template:v1.0', 'production') + +result = Template.assign_tags('my-template:v1.0', ['production', 'stable']) +``` + + + +### remove\_tags + +```python +@staticmethod +def remove_tags(name: str, tags: Union[str, List[str]], + **opts: Unpack[ApiParams]) -> None +``` + +Remove tag(s) from a template. + +**Arguments**: + +- `name`: Template name +- `tags`: Tag or tags to remove +Example +```python +from e2b import Template + +Template.remove_tags('my-template', 'production') + +Template.remove_tags('my-template', ['production', 'stable']) +``` + + + +### get\_tags + +```python +@staticmethod +def get_tags(template_id: str, **opts: Unpack[ApiParams]) -> List[TemplateTag] +``` + +Get all tags for a template. + +**Arguments**: + +- `template_id`: Template ID or name + +**Returns**: + +List of TemplateTag with tag name, build_id, and created_at +Example +```python +from e2b import Template + +tags = Template.get_tags('my-template') +for tag in tags: + print(f"Tag: {tag.tag}, Build: {tag.build_id}, Created: {tag.created_at}") +``` + + + + + + +### check\_alias\_exists + +```python +def check_alias_exists(client: AuthenticatedClient, alias: str) -> bool +``` + +Check if a template with the given alias exists. + +**Arguments**: + +- `client` - Authenticated API client +- `alias` - Template alias to check + + +**Returns**: + + True if the alias exists, False otherwise + + + +### assign\_tags + +```python +def assign_tags(client: AuthenticatedClient, target_name: str, + tags: List[str]) -> TemplateTagInfo +``` + +Assign tag(s) to an existing template build. + +**Arguments**: + +- `client` - Authenticated API client +- `target_name` - Template name in 'name:tag' format (the source build to tag from) +- `tags` - Tags to assign + + +**Returns**: + + TemplateTagInfo with build_id and assigned tags + + + +### remove\_tags + +```python +def remove_tags(client: AuthenticatedClient, name: str, + tags: List[str]) -> None +``` + +Remove tag(s) from a template. + +**Arguments**: + +- `client` - Authenticated API client +- `name` - Template name +- `tags` - List of tags to remove + + + +### get\_template\_tags + +```python +def get_template_tags(client: AuthenticatedClient, + template_id: str) -> List[TemplateTag] +``` + +Get all tags for a template. + +**Arguments**: + +- `client` - Authenticated API client +- `template_id` - Template ID or name diff --git a/docs/sdk-reference/python-sdk/v2.19.0/exceptions.mdx b/docs/sdk-reference/python-sdk/v2.19.0/exceptions.mdx new file mode 100644 index 00000000..9a290def --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.19.0/exceptions.mdx @@ -0,0 +1,172 @@ +--- +sidebarTitle: "Exceptions" +--- + + + + + + +## SandboxException + +```python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + + +## TimeoutException + +```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 +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + + +## NotEnoughSpaceException + +```python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + + +## NotFoundException + +```python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + +.. deprecated:: + Use :class:`FileNotFoundException` or :class:`SandboxNotFoundException` instead. + This class will be removed in the next major version. + + + +## FileNotFoundException + +```python +class FileNotFoundException(NotFoundException) +``` + +Raised when a file or directory is not found inside a sandbox. + + + +## SandboxNotFoundException + +```python +class SandboxNotFoundException(NotFoundException) +``` + +Raised when a sandbox is not found (e.g. it doesn't exist or is no longer running). + + + +## AuthenticationException + +```python +class AuthenticationException(Exception) +``` + +Raised when authentication fails. + + + +## GitAuthException + +```python +class GitAuthException(AuthenticationException) +``` + +Raised when git authentication fails. + + + +## GitUpstreamException + +```python +class GitUpstreamException(SandboxException) +``` + +Raised when git upstream tracking is missing. + + + +## TemplateException + +```python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + + +## RateLimitException + +```python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + + + +## BuildException + +```python +class BuildException(Exception) +``` + +Raised when the build fails. + + + +## FileUploadException + +```python +class FileUploadException(BuildException) +``` + +Raised when the file upload fails. + + + +## VolumeException + +```python +class VolumeException(Exception) +``` + +Base class for all volume errors. + +Raised when general volume errors occur. diff --git a/docs/sdk-reference/python-sdk/v2.19.0/logger.mdx b/docs/sdk-reference/python-sdk/v2.19.0/logger.mdx new file mode 100644 index 00000000..16f9c54e --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.19.0/logger.mdx @@ -0,0 +1,105 @@ +--- +sidebarTitle: "Logger" +--- + + + + + + +## LogEntry + +```python +@dataclass +class LogEntry() +``` + +Represents a single log entry from the template build process. + + + +## LogEntryStart + +```python +@dataclass +class LogEntryStart(LogEntry) +``` + +Special log entry indicating the start of a build process. + + + +## LogEntryEnd + +```python +@dataclass +class LogEntryEnd(LogEntry) +``` + +Special log entry indicating the end of a build process. + + + +### TIMER\_UPDATE\_INTERVAL\_MS + +Default minimum log level to display. + + + +### DEFAULT\_LEVEL + +Colored labels for each log level. + + + +### levels + +Numeric ordering of log levels for comparison (lower = less severe). + + + +### set\_interval + +```python +def set_interval(func, interval) +``` + +Returns a stop function that can be called to cancel the interval. + +Similar to JavaScript's setInterval. + +**Arguments**: + +- `func`: Function to execute at each interval +- `interval`: Interval duration in **seconds** + +**Returns**: + +Stop function that can be called to cancel the interval + + + +### default\_build\_logger + +```python +def default_build_logger( + min_level: Optional[LogEntryLevel] = None +) -> Callable[[LogEntry], None] +``` + +Create a default build logger with animated timer display. + +**Arguments**: + +- `min_level`: Minimum log level to display (default: 'info') + +**Returns**: + +Logger function that accepts LogEntry instances +Example +```python +from e2b import Template, default_build_logger + +template = Template().from_python_image() + +``` diff --git a/docs/sdk-reference/python-sdk/v2.19.0/readycmd.mdx b/docs/sdk-reference/python-sdk/v2.19.0/readycmd.mdx new file mode 100644 index 00000000..b4083b62 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.19.0/readycmd.mdx @@ -0,0 +1,167 @@ +--- +sidebarTitle: "Readycmd" +--- + + + + + + +## ReadyCmd + +```python +class ReadyCmd() +``` + +Wrapper class for ready check commands. + + + +### wait\_for\_port + +```python +def wait_for_port(port: int) +``` + +Wait for a port to be listening. + +Uses `ss` command to check if a port is open and listening. + +**Arguments**: + +- `port`: Port number to wait for + +**Returns**: + +ReadyCmd that checks for the port +Example +```python +from e2b import Template, wait_for_port + +template = ( + Template() + .from_python_image() + .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) +) +``` + + + +### wait\_for\_url + +```python +def wait_for_url(url: str, status_code: int = 200) +``` + +Wait for a URL to return a specific HTTP status code. + +Uses `curl` to make HTTP requests and check the response status. + +**Arguments**: + +- `url`: URL to check (e.g., 'http://localhost:3000/health') +- `status_code`: Expected HTTP status code (default: 200) + +**Returns**: + +ReadyCmd that checks the URL +Example +```python +from e2b import Template, wait_for_url + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) +) +``` + + + +### wait\_for\_process + +```python +def wait_for_process(process_name: str) +``` + +Wait for a process with a specific name to be running. + +Uses `pgrep` to check if a process exists. + +**Arguments**: + +- `process_name`: Name of the process to wait for + +**Returns**: + +ReadyCmd that checks for the process +Example +```python +from e2b import Template, wait_for_process + +template = ( + Template() + .from_base_image() + .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) +) +``` + + + +### wait\_for\_file + +```python +def wait_for_file(filename: str) +``` + +Wait for a file to exist. + +Uses shell test command to check file existence. + +**Arguments**: + +- `filename`: Path to the file to wait for + +**Returns**: + +ReadyCmd that checks for the file +Example +```python +from e2b import Template, wait_for_file + +template = ( + Template() + .from_base_image() + .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) +) +``` + + + +### wait\_for\_timeout + +```python +def wait_for_timeout(timeout: int) +``` + +Wait for a specified timeout before considering the sandbox ready. + +Uses `sleep` command to wait for a fixed duration. + +**Arguments**: + +- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) + +**Returns**: + +ReadyCmd that waits for the specified duration +Example +```python +from e2b import Template, wait_for_timeout + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds +) +``` diff --git a/docs/sdk-reference/python-sdk/v2.19.0/sandbox_async.mdx b/docs/sdk-reference/python-sdk/v2.19.0/sandbox_async.mdx new file mode 100644 index 00000000..805bbe22 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.19.0/sandbox_async.mdx @@ -0,0 +1,2286 @@ +--- +sidebarTitle: "Sandbox Async" +--- + + + + + + +## AsyncSandbox + +```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](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### git + +```python +@property +def git() -> Git +``` + +Module for running git operations in the sandbox. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```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 +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + + +### create + +```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: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + network: Optional[SandboxNetworkOpts] = None, + lifecycle: Optional[SandboxLifecycle] = None, + volume_mounts: Optional[SandboxAsyncVolumeMount] = None, + **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`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. +- `mcp`: MCP server to enable in the sandbox +- `network`: Sandbox network configuration +- `lifecycle`: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` (default) or ``"pause"``; ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout="pause"``). Example: ``{"on_timeout": "pause", "auto_resume": True}`` +- `volume_mounts`: Dictionary mapping mount paths to AsyncVolume instances or volume names + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```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** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await sandbox.pause() + +same_sandbox = await sandbox.connect() +``` + + + +### connect + +```python +@overload +@staticmethod +async def connect(sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> "AsyncSandbox" +``` + +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** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await AsyncSandbox.pause(sandbox.sandbox_id) + +same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id) +``` + + + +### connect + +```python +@class_method_variant("_cls_connect_sandbox") +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** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await sandbox.pause() + +same_sandbox = await sandbox.connect() +``` + + + +### kill + +```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 +@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 +@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 +@overload +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +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 +@overload +@staticmethod +async def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +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 +@class_method_variant("_cls_set_timeout") +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +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 +@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 +@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 +@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 +@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 +@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 +@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 +@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, + mcp: Optional[McpServer] = None, + volume_mounts: Optional[SandboxAsyncVolumeMount] = None, + **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`. +- `mcp`: MCP server to enable in the sandbox +- `volume_mounts`: Dictionary mapping mount paths to AsyncVolume instances or volume names + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### pause + +```python +@overload +async def pause(**opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### pause + +```python +@overload +@staticmethod +async def pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### pause + +```python +@class_method_variant("_cls_pause") +async def pause(**opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### beta\_pause + +```python +@class_method_variant("_cls_pause") +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +:deprecated: Use `pause()` instead. + + + +### create\_snapshot + +```python +@overload +async def create_snapshot(**opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshot_id` with `AsyncSandbox.create(snapshot_id)` to create a new sandbox from the snapshot. + +**Returns**: + +Snapshot information including the snapshot ID + + + +### create\_snapshot + +```python +@overload +@staticmethod +async def create_snapshot(sandbox_id: str, + **opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot from the sandbox specified by sandbox ID. + +The sandbox will be paused while the snapshot is being created. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Snapshot information including the snapshot ID + + + +### create\_snapshot + +```python +@class_method_variant("_cls_create_snapshot") +async def create_snapshot(**opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshot_id` with `AsyncSandbox.create(snapshot_id)` to create a new sandbox from the snapshot. + +**Returns**: + +Snapshot information including the snapshot ID + + + +### list\_snapshots + +```python +@overload +def list_snapshots(limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSnapshotPaginator +``` + +List snapshots for this sandbox. + +**Arguments**: + +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### list\_snapshots + +```python +@overload +@staticmethod +def list_snapshots(sandbox_id: Optional[str] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSnapshotPaginator +``` + +List all snapshots. + +**Arguments**: + +- `sandbox_id`: Filter snapshots by source sandbox ID +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### list\_snapshots + +```python +@class_method_variant("_cls_list_snapshots") +def list_snapshots(limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSnapshotPaginator +``` + +List snapshots for this sandbox. + +**Arguments**: + +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### delete\_snapshot + +```python +@staticmethod +async def delete_snapshot(snapshot_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Delete a snapshot. + +**Arguments**: + +- `snapshot_id`: Snapshot ID + +**Returns**: + +`True` if the snapshot was deleted, `False` if it was not found + + + +### get\_mcp\_token + +```python +async def get_mcp_token() -> Optional[str] +``` + +Get the MCP token for the sandbox. + +**Returns**: + +MCP token for the sandbox, or None if MCP is not enabled. + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxBase) +``` + + + +### list + +```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 + + + + + + + + + +## AsyncSandboxPaginator + +```python +class AsyncSandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python +paginator = AsyncSandbox.list() + +while paginator.has_next: + sandboxes = await paginator.next_items() + print(sandboxes) +``` + + + +### next\_items + +```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 + + + +## AsyncSnapshotPaginator + +```python +class AsyncSnapshotPaginator(SnapshotPaginatorBase) +``` + +Paginator for listing snapshots. + +**Example**: + +```python +paginator = AsyncSandbox.list_snapshots() + +while paginator.has_next: + snapshots = await paginator.next_items() + print(snapshots) +``` + + + +### next\_items + +```python +async def next_items() -> List[SnapshotInfo] +``` + +Returns the next page of snapshots. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of snapshots + + + + + + +## Git + +```python +class Git() +``` + +Async module for running git operations in the sandbox. + + + +### \_\_init\_\_ + +```python +def __init__(commands: Commands) -> None +``` + +Create a Git helper bound to the sandbox command runner. + +**Arguments**: + +- `commands`: Command runner used to execute git commands + + + +### clone + +```python +async def clone(url: str, + path: Optional[str] = None, + branch: Optional[str] = None, + depth: Optional[int] = None, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None, + dangerously_store_credentials: bool = False) +``` + +Clone a git repository into the sandbox. + +**Arguments**: + +- `url`: Git repository URL +- `path`: Destination path for the clone +- `branch`: Branch to check out +- `depth`: If set, perform a shallow clone with this depth +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** +- `dangerously_store_credentials`: Store credentials in the cloned repository when True + +**Returns**: + +Command result from the command runner + + + +### init + +```python +async def init(path: str, + bare: bool = False, + initial_branch: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Initialize a new git repository. + +**Arguments**: + +- `path`: Destination path for the repository +- `bare`: Create a bare repository when True +- `initial_branch`: Initial branch name (for example, "main") +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### remote\_add + +```python +async def remote_add(path: str, + name: str, + url: str, + fetch: bool = False, + overwrite: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Add (or update) a remote for a repository. + +**Arguments**: + +- `path`: Repository path +- `name`: Remote name (for example, "origin") +- `url`: Remote URL +- `fetch`: Fetch the remote after adding it when True +- `overwrite`: Overwrite the remote URL if it already exists when True +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### remote\_get + +```python +async def remote_get(path: str, + name: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Optional[str] +``` + +Get the URL for a git remote. + +Returns `None` when the remote does not exist. + +**Arguments**: + +- `path`: Repository path +- `name`: Remote name (for example, "origin") +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Remote URL if present, otherwise `None` + + + +### status + +```python +async def status(path: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> GitStatus +``` + +Get repository status information. + +**Arguments**: + +- `path`: Repository path +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Parsed git status + + + +### branches + +```python +async def branches(path: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> GitBranches +``` + +List branches in a repository. + +**Arguments**: + +- `path`: Repository path +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Parsed branch list + + + +### create\_branch + +```python +async def create_branch(path: str, + branch: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Create and check out a new branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to create +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### checkout\_branch + +```python +async def checkout_branch(path: str, + branch: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Check out an existing branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to check out +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### delete\_branch + +```python +async def delete_branch(path: str, + branch: str, + force: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Delete a branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to delete +- `force`: Force deletion with `-D` when `True` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### add + +```python +async def add(path: str, + files: Optional[List[str]] = None, + all: bool = True, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Stage files for commit. + +**Arguments**: + +- `path`: Repository path +- `files`: Files to add; when omitted, adds the current directory +- `all`: When `True` and `files` is omitted, stage all changes +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### commit + +```python +async def commit(path: str, + message: str, + author_name: Optional[str] = None, + author_email: Optional[str] = None, + allow_empty: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Create a commit in the repository. + +**Arguments**: + +- `path`: Repository path +- `message`: Commit message +- `author_name`: Commit author name +- `author_email`: Commit author email +- `allow_empty`: Allow empty commits when `True` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### reset + +```python +async def reset(path: str, + mode: Optional[str] = None, + target: Optional[str] = None, + paths: Optional[List[str]] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Reset the current HEAD to a specified state. + +**Arguments**: + +- `path`: Repository path +- `mode`: Reset mode (soft, mixed, hard, merge, keep) +- `target`: Commit, branch, or ref to reset to (defaults to HEAD) +- `paths`: Paths to reset +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### restore + +```python +async def restore(path: str, + paths: List[str], + staged: Optional[bool] = None, + worktree: Optional[bool] = None, + source: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Restore working tree files or unstage changes. + +**Arguments**: + +- `path`: Repository path +- `paths`: Paths to restore (use ["."] for all) +- `staged`: When True, restore the index (unstage) +- `worktree`: When True, restore working tree files +- `source`: Restore from the given source (commit, branch, or ref) +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### push + +```python +async def push(path: str, + remote: Optional[str] = None, + branch: Optional[str] = None, + set_upstream: bool = True, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Push commits to a remote. + +**Arguments**: + +- `path`: Repository path +- `remote`: Remote name, e.g. `origin` +- `branch`: Branch name to push +- `set_upstream`: Set upstream tracking when `True` +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### pull + +```python +async def pull(path: str, + remote: Optional[str] = None, + branch: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Pull changes from a remote. + +**Arguments**: + +- `path`: Repository path +- `remote`: Remote name, e.g. `origin` +- `branch`: Branch name to pull +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### set\_config + +```python +async def set_config(key: str, + value: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Set a git config value. + +Use `scope="local"` together with `path` to configure a specific repository. + +**Arguments**: + +- `key`: Git config key (e.g. `pull.rebase`) +- `value`: Git config value +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### get\_config + +```python +async def get_config(key: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Optional[str] +``` + +Get a git config value. + +Returns `None` when the key is not set in the requested scope. + +**Arguments**: + +- `key`: Git config key (e.g. `pull.rebase`) +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Config value if present, otherwise `None` + + + +### dangerously\_authenticate + +```python +async def dangerously_authenticate(username: str, + password: str, + host: str = "github.com", + protocol: str = "https", + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Dangerously authenticate git globally via the credential helper. + +This persists credentials in the credential store and may be accessable to agents running on the sandbox. +Prefer short-lived credentials when possible. + +**Arguments**: + +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `host`: Host to authenticate for, defaults to `github.com` +- `protocol`: Protocol to authenticate for, defaults to `https` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### configure\_user + +```python +async def configure_user(name: str, + email: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Configure git user name and email. + +**Arguments**: + +- `name`: Git user name +- `email`: Git user email +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + + + + +## AsyncWatchHandle + +```python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + + +### stop + +```python +async def stop() +``` + +Stop watching the directory. + + + + + + +## Filesystem + +```python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Optional[Username] = None, + 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 +@overload +async def read(path: str, + format: Literal["bytes"], + user: Optional[Username] = None, + 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 +@overload +async def read( + path: str, + format: Literal["stream"], + user: Optional[Username] = None, + 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 +async def write(path: str, + data: Union[str, bytes, IO], + user: Optional[Username] = None, + 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 +async def write_files( + files: List[WriteEntry], + user: Optional[Username] = None, + 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 +async def list(path: str, + depth: Optional[int] = 1, + user: Optional[Username] = None, + 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 +async def exists(path: str, + user: Optional[Username] = None, + 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 +async def get_info(path: str, + user: Optional[Username] = None, + 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 +async def remove(path: str, + user: Optional[Username] = None, + 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 +async def rename(old_path: str, + new_path: str, + user: Optional[Username] = None, + 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 +async def make_dir(path: str, + user: Optional[Username] = None, + 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 +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Optional[Username] = None, + 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 +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### stdout + +```python +@property +def stdout() +``` + +Command stdout output. + + + +### stderr + +```python +@property +def stderr() +``` + +Command stderr output. + + + +### error + +```python +@property +def error() +``` + +Command execution error message. + + + +### exit\_code + +```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 +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 +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 +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 +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```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 +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 +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Optional[Username] = None, + 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 + + + +### connect + +```python +async def connect( + pid: int, + on_data: OutputHandler[PtyOutput], + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Connect to a running PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY to connect to. You can get the list of running PTYs using `sandbox.pty.list()`. +- `on_data`: Callback to handle PTY data +- `timeout`: Timeout for the PTY connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```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 +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```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 +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 +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 +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + stdin: Optional[bool] = 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 +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `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 +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + stdin: Optional[bool] = 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 +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `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 +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 diff --git a/docs/sdk-reference/python-sdk/v2.19.0/sandbox_sync.mdx b/docs/sdk-reference/python-sdk/v2.19.0/sandbox_sync.mdx new file mode 100644 index 00000000..59e6a9cf --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.19.0/sandbox_sync.mdx @@ -0,0 +1,2239 @@ +--- +sidebarTitle: "Sandbox Sync" +--- + + + + + + +## Sandbox + +```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](https://e2b.dev/docs). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import Sandbox + +sandbox = Sandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### git + +```python +@property +def git() -> Git +``` + +Module for running git operations in the sandbox. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +:deprecated: This constructor is deprecated + +Use `Sandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```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 +sandbox = Sandbox.create() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + + +### create + +```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, + mcp: Optional[McpServer] = None, + network: Optional[SandboxNetworkOpts] = None, + lifecycle: Optional[SandboxLifecycle] = None, + volume_mounts: Optional[SandboxVolumeMount] = None, + **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`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. +- `mcp`: MCP server to enable in the sandbox +- `network`: Sandbox network configuration +- `lifecycle`: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` (default) or ``"pause"``; ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout="pause"``). Example: ``{"on_timeout": "pause", "auto_resume": True}`` +- `volume_mounts`: Dictionary mapping mount paths to Volume instances or volume names + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```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** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +sandbox.pause() + +same_sandbox = sandbox.connect() + + + +### connect + +```python +@overload +@staticmethod +def connect(sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> "Sandbox" +``` + +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**. +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +Sandbox.pause(sandbox.sandbox_id) + +same_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + + +### connect + +```python +@class_method_variant("_cls_connect_sandbox") +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**. +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +sandbox.pause() + +same_sandbox = sandbox.connect() +``` + + + +### kill + +```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 +@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 +@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 +@overload +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +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 +@overload +@staticmethod +def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +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 +@class_method_variant("_cls_set_timeout") +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +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 +@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 +@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 +@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 +@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 +@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 +@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 +@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, + mcp: Optional[McpServer] = None, + volume_mounts: Optional[SandboxVolumeMount] = None, + **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`. +- `mcp`: MCP server to enable in the sandbox +- `volume_mounts`: Dictionary mapping mount paths to Volume instances or volume names + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### pause + +```python +@overload +def pause(**opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox. + + + +### pause + +```python +@overload +@staticmethod +def pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + + + +### pause + +```python +@class_method_variant("_cls_pause") +def pause(**opts: Unpack[ApiParams]) -> None +``` + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### beta\_pause + +```python +@class_method_variant("_cls_pause") +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +:deprecated: Use `pause()` instead. + + + +### create\_snapshot + +```python +@overload +def create_snapshot(**opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshot_id` with `Sandbox.create(snapshot_id)` to create a new sandbox from the snapshot. + +**Returns**: + +Snapshot information including the snapshot ID + + + +### create\_snapshot + +```python +@overload +@staticmethod +def create_snapshot(sandbox_id: str, + **opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot from the sandbox specified by sandbox ID. + +The sandbox will be paused while the snapshot is being created. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Snapshot information including the snapshot ID + + + +### create\_snapshot + +```python +@class_method_variant("_cls_create_snapshot") +def create_snapshot(**opts: Unpack[ApiParams]) -> SnapshotInfo +``` + +Create a snapshot of the sandbox's current state. + +The sandbox will be paused while the snapshot is being created. +The snapshot can be used to create new sandboxes with the same filesystem and state. +Snapshots are persistent and survive sandbox deletion. + +Use the returned `snapshot_id` with `Sandbox.create(snapshot_id)` to create a new sandbox from the snapshot. + +**Returns**: + +Snapshot information including the snapshot ID + + + +### list\_snapshots + +```python +@overload +def list_snapshots(limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SnapshotPaginator +``` + +List snapshots for this sandbox. + +**Arguments**: + +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### list\_snapshots + +```python +@overload +@staticmethod +def list_snapshots(sandbox_id: Optional[str] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SnapshotPaginator +``` + +List all snapshots. + +**Arguments**: + +- `sandbox_id`: Filter snapshots by source sandbox ID +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### list\_snapshots + +```python +@class_method_variant("_cls_list_snapshots") +def list_snapshots(limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SnapshotPaginator +``` + +List snapshots for this sandbox. + +**Arguments**: + +- `limit`: Maximum number of snapshots to return per page +- `next_token`: Token for pagination + +**Returns**: + +Paginator for listing snapshots + + + +### delete\_snapshot + +```python +@staticmethod +def delete_snapshot(snapshot_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Delete a snapshot. + +**Arguments**: + +- `snapshot_id`: Snapshot ID + +**Returns**: + +`True` if the snapshot was deleted, `False` if it was not found + + + +### get\_mcp\_token + +```python +def get_mcp_token() -> Optional[str] +``` + +Get the MCP token for the sandbox. + +**Returns**: + +MCP token for the sandbox, or None if MCP is not enabled. + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxBase) +``` + + + +### list + +```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 + + + + + + +## SandboxPaginator + +```python +class SandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python +paginator = Sandbox.list() + +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) +``` + + + +### next\_items + +```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 + + + +## SnapshotPaginator + +```python +class SnapshotPaginator(SnapshotPaginatorBase) +``` + +Paginator for listing snapshots. + +**Example**: + +```python +paginator = Sandbox.list_snapshots() + +while paginator.has_next: + snapshots = paginator.next_items() + print(snapshots) +``` + + + +### next\_items + +```python +def next_items() -> List[SnapshotInfo] +``` + +Returns the next page of snapshots. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of snapshots + + + + + + +## Git + +```python +class Git() +``` + +Module for running git operations in the sandbox. + + + +### \_\_init\_\_ + +```python +def __init__(commands: Commands) -> None +``` + +Create a Git helper bound to the sandbox command runner. + +**Arguments**: + +- `commands`: Command runner used to execute git commands + + + +### clone + +```python +def clone(url: str, + path: Optional[str] = None, + branch: Optional[str] = None, + depth: Optional[int] = None, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None, + dangerously_store_credentials: bool = False) +``` + +Clone a git repository into the sandbox. + +**Arguments**: + +- `url`: Git repository URL +- `path`: Destination path for the clone +- `branch`: Branch to check out +- `depth`: If set, perform a shallow clone with this depth +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** +- `dangerously_store_credentials`: Store credentials in the cloned repository when True + +**Returns**: + +Command result from the command runner + + + +### init + +```python +def init(path: str, + bare: bool = False, + initial_branch: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Initialize a new git repository. + +**Arguments**: + +- `path`: Destination path for the repository +- `bare`: Create a bare repository when True +- `initial_branch`: Initial branch name (for example, "main") +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### remote\_add + +```python +def remote_add(path: str, + name: str, + url: str, + fetch: bool = False, + overwrite: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Add (or update) a remote for a repository. + +**Arguments**: + +- `path`: Repository path +- `name`: Remote name (for example, "origin") +- `url`: Remote URL +- `fetch`: Fetch the remote after adding it when True +- `overwrite`: Overwrite the remote URL if it already exists when True +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### remote\_get + +```python +def remote_get(path: str, + name: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Optional[str] +``` + +Get the URL for a git remote. + +Returns `None` when the remote does not exist. + +**Arguments**: + +- `path`: Repository path +- `name`: Remote name (for example, "origin") +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Remote URL if present, otherwise `None` + + + +### status + +```python +def status(path: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> GitStatus +``` + +Get repository status information. + +**Arguments**: + +- `path`: Repository path +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Parsed git status + + + +### branches + +```python +def branches(path: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> GitBranches +``` + +List branches in a repository. + +**Arguments**: + +- `path`: Repository path +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Parsed branch list + + + +### create\_branch + +```python +def create_branch(path: str, + branch: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Create and check out a new branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to create +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### checkout\_branch + +```python +def checkout_branch(path: str, + branch: str, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Check out an existing branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to check out +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### delete\_branch + +```python +def delete_branch(path: str, + branch: str, + force: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Delete a branch. + +**Arguments**: + +- `path`: Repository path +- `branch`: Branch name to delete +- `force`: Force deletion with `-D` when `True` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### add + +```python +def add(path: str, + files: Optional[List[str]] = None, + all: bool = True, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Stage files for commit. + +**Arguments**: + +- `path`: Repository path +- `files`: Files to add; when omitted, adds the current directory +- `all`: When `True` and `files` is omitted, stage all changes +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### commit + +```python +def commit(path: str, + message: str, + author_name: Optional[str] = None, + author_email: Optional[str] = None, + allow_empty: bool = False, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Create a commit in the repository. + +**Arguments**: + +- `path`: Repository path +- `message`: Commit message +- `author_name`: Commit author name +- `author_email`: Commit author email +- `allow_empty`: Allow empty commits when `True` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### reset + +```python +def reset(path: str, + mode: Optional[str] = None, + target: Optional[str] = None, + paths: Optional[List[str]] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Reset the current HEAD to a specified state. + +**Arguments**: + +- `path`: Repository path +- `mode`: Reset mode (soft, mixed, hard, merge, keep) +- `target`: Commit, branch, or ref to reset to (defaults to HEAD) +- `paths`: Paths to reset +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### restore + +```python +def restore(path: str, + paths: List[str], + staged: Optional[bool] = None, + worktree: Optional[bool] = None, + source: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Restore working tree files or unstage changes. + +**Arguments**: + +- `path`: Repository path +- `paths`: Paths to restore (use ["."] for all) +- `staged`: When True, restore the index (unstage) +- `worktree`: When True, restore working tree files +- `source`: Restore from the given source (commit, branch, or ref) +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### push + +```python +def push(path: str, + remote: Optional[str] = None, + branch: Optional[str] = None, + set_upstream: bool = True, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Push commits to a remote. + +**Arguments**: + +- `path`: Repository path +- `remote`: Remote name, e.g. `origin` +- `branch`: Branch name to push +- `set_upstream`: Set upstream tracking when `True` +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### pull + +```python +def pull(path: str, + remote: Optional[str] = None, + branch: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Pull changes from a remote. + +**Arguments**: + +- `path`: Repository path +- `remote`: Remote name, e.g. `origin` +- `branch`: Branch name to pull +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### set\_config + +```python +def set_config(key: str, + value: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Set a git config value. + +Use `scope="local"` together with `path` to configure a specific repository. + +**Arguments**: + +- `key`: Git config key (e.g. `pull.rebase`) +- `value`: Git config value +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### get\_config + +```python +def get_config(key: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Optional[str] +``` + +Get a git config value. + +Returns `None` when the key is not set in the requested scope. + +**Arguments**: + +- `key`: Git config key (e.g. `pull.rebase`) +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Config value if present, otherwise `None` + + + +### dangerously\_authenticate + +```python +def dangerously_authenticate(username: str, + password: str, + host: str = "github.com", + protocol: str = "https", + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Dangerously authenticate git globally via the credential helper. + +This persists credentials in the credential store and may be accessable to agents running on the sandbox. +Prefer short-lived credentials when possible. + +**Arguments**: + +- `username`: Username for HTTP(S) authentication +- `password`: Password or token for HTTP(S) authentication +- `host`: Host to authenticate for, defaults to `github.com` +- `protocol`: Protocol to authenticate for, defaults to `https` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + +### configure\_user + +```python +def configure_user(name: str, + email: str, + scope: str = "global", + path: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[str] = None, + cwd: Optional[str] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) +``` + +Configure git user name and email. + +**Arguments**: + +- `name`: Git user name +- `email`: Git user email +- `scope`: Config scope: `global`, `local`, or `system` +- `path`: Repository path required when `scope` is `local` +- `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** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Command result from the command runner + + + + + + +## WatchHandle + +```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 +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 +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 +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Optional[Username] = None, + 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 +@overload +def read(path: str, + format: Literal["bytes"], + user: Optional[Username] = None, + 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 +@overload +def read(path: str, + format: Literal["stream"], + user: Optional[Username] = None, + 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 +def write(path: str, + data: Union[str, bytes, IO], + user: Optional[Username] = None, + 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 +def write_files(files: List[WriteEntry], + user: Optional[Username] = None, + 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 +def list(path: str, + depth: Optional[int] = 1, + user: Optional[Username] = None, + 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 +def exists(path: str, + user: Optional[Username] = None, + 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 +def get_info(path: str, + user: Optional[Username] = None, + 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 +def remove(path: str, + user: Optional[Username] = None, + 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 +def rename(old_path: str, + new_path: str, + user: Optional[Username] = None, + 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 +def make_dir(path: str, + user: Optional[Username] = None, + 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 +def watch_dir(path: str, + user: Optional[Username] = None, + 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 +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### \_\_iter\_\_ + +```python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + + +### disconnect + +```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 +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 +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + + + +## Pty + +```python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```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 +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 +def create(size: PtySize, + user: Optional[Username] = None, + 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 + + + +### connect + +```python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Connect to a running PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY to connect to. You can get the list of running PTYs using `sandbox.pty.list()`. +- `timeout`: Timeout for the PTY connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```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 +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```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 +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 +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 +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + stdin: Optional[bool] = 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 +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `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 +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + stdin: Optional[bool] = 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 +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `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 +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 diff --git a/docs/sdk-reference/python-sdk/v2.19.0/template.mdx b/docs/sdk-reference/python-sdk/v2.19.0/template.mdx new file mode 100644 index 00000000..6f7ddfa5 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.19.0/template.mdx @@ -0,0 +1,1924 @@ +--- +sidebarTitle: "Template" +--- + + + + + + +## TemplateBuilder + +```python +class TemplateBuilder() +``` + +Builder class for adding instructions to an E2B template. + +All methods return self to allow method chaining. + + + +### copy + +```python +def copy(src: Union[Union[str, Path], List[Union[str, Path]]], + dest: Union[str, Path], + force_upload: Optional[Literal[True]] = None, + user: Optional[str] = None, + mode: Optional[int] = None, + resolve_symlinks: Optional[bool] = None) -> "TemplateBuilder" +``` + +Copy files or directories from the local filesystem into the template. + +**Arguments**: + +- `src`: Source file(s) or directory path(s) to copy +- `dest`: Destination path in the template +- `force_upload`: Force upload even if files are cached +- `user`: User and optionally group (user:group) to own the files +- `mode`: File permissions in octal format (e.g., 0o755) +- `resolve_symlinks`: Whether to resolve symlinks + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.copy('requirements.txt', '/home/user/') +template.copy(['app.py', 'config.py'], '/app/', mode=0o755) +``` + + + +### copy\_items + +```python +def copy_items(items: List[CopyItem]) -> "TemplateBuilder" +``` + +Copy multiple files or directories using a list of copy items. + +**Arguments**: + +- `items`: List of CopyItem dictionaries with src, dest, and optional parameters + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.copy_items([ + {'src': 'app.py', 'dest': '/app/'}, + {'src': 'config.py', 'dest': '/app/', 'mode': 0o644} +]) +``` + + + +### remove + +```python +def remove(path: Union[Union[str, Path], List[Union[str, Path]]], + force: bool = False, + recursive: bool = False, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Remove files or directories in the template. + +**Arguments**: + +- `path`: File(s) or directory path(s) to remove +- `force`: Force removal without prompting +- `recursive`: Remove directories recursively +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.remove('/tmp/cache', recursive=True, force=True) +template.remove('/tmp/cache', recursive=True, force=True, user='root') +``` + + + +### rename + +```python +def rename(src: Union[str, Path], + dest: Union[str, Path], + force: bool = False, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Rename or move a file or directory in the template. + +**Arguments**: + +- `src`: Source path +- `dest`: Destination path +- `force`: Force rename without prompting +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', user='root') +``` + + + +### make\_dir + +```python +def make_dir(path: Union[Union[str, Path], List[Union[str, Path]]], + mode: Optional[int] = None, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Create directory(ies) in the template. + +**Arguments**: + +- `path`: Directory path(s) to create +- `mode`: Directory permissions in octal format (e.g., 0o755) +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.make_dir('/app/data', mode=0o755) +template.make_dir(['/app/logs', '/app/cache']) +template.make_dir('/app/data', mode=0o755, user='root') +``` + + + +### make\_symlink + +```python +def make_symlink(src: Union[str, Path], + dest: Union[str, Path], + user: Optional[str] = None, + force: bool = False) -> "TemplateBuilder" +``` + +Create a symbolic link in the template. + +**Arguments**: + +- `src`: Source path (target of the symlink) +- `dest`: Destination path (location of the symlink) +- `user`: User to run the command as +- `force`: Force symlink without prompting + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.make_symlink('/usr/bin/python3', '/usr/bin/python') +template.make_symlink('/usr/bin/python3', '/usr/bin/python', user='root') +template.make_symlink('/usr/bin/python3', '/usr/bin/python', force=True) +``` + + + +### run\_cmd + +```python +def run_cmd(command: Union[str, List[str]], + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Run a shell command during template build. + +**Arguments**: + +- `command`: Command string or list of commands to run (joined with &&) +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.run_cmd('apt-get update') +template.run_cmd(['pip install numpy', 'pip install pandas']) +template.run_cmd('apt-get install vim', user='root') +``` + + + +### set\_workdir + +```python +def set_workdir(workdir: Union[str, Path]) -> "TemplateBuilder" +``` + +Set the working directory for subsequent commands in the template. + +**Arguments**: + +- `workdir`: Path to set as the working directory + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_workdir('/app') +``` + + + +### set\_user + +```python +def set_user(user: str) -> "TemplateBuilder" +``` + +Set the user for subsequent commands in the template. + +**Arguments**: + +- `user`: Username to set + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_user('root') +``` + + + +### pip\_install + +```python +def pip_install(packages: Optional[Union[str, List[str]]] = None, + g: bool = True) -> "TemplateBuilder" +``` + +Install Python packages using pip. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, runs 'pip install .' in the current directory +- `g`: Install packages globally (default: True). If False, installs for user only + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.pip_install('numpy') +template.pip_install(['pandas', 'scikit-learn']) +template.pip_install('numpy', g=False) # Install for user only +template.pip_install() # Installs from current directory +``` + + + +### npm\_install + +```python +def npm_install(packages: Optional[Union[str, List[str]]] = None, + g: Optional[bool] = False, + dev: Optional[bool] = False) -> "TemplateBuilder" +``` + +Install Node.js packages using npm. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, installs from package.json +- `g`: Install packages globally +- `dev`: Install packages as dev dependencies + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.npm_install('express') +template.npm_install(['lodash', 'axios']) +template.npm_install('typescript', g=True) +template.npm_install() # Installs from package.json +``` + + + +### bun\_install + +```python +def bun_install(packages: Optional[Union[str, List[str]]] = None, + g: Optional[bool] = False, + dev: Optional[bool] = False) -> "TemplateBuilder" +``` + +Install Bun packages using bun. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, installs from package.json +- `g`: Install packages globally +- `dev`: Install packages as dev dependencies + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.bun_install('express') +template.bun_install(['lodash', 'axios']) +template.bun_install('tsx', g=True) +template.bun_install('typescript', dev=True) +template.bun_install() // Installs from package.json +``` + + + +### apt\_install + +```python +def apt_install(packages: Union[str, List[str]], + no_install_recommends: bool = False, + fix_missing: bool = False) -> "TemplateBuilder" +``` + +Install system packages using apt-get. + +**Arguments**: + +- `packages`: Package name(s) to install +- `no_install_recommends`: Whether to install recommended packages +- `fix_missing`: Whether to fix missing packages + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.apt_install('vim') +template.apt_install(['git', 'curl', 'wget']) +template.apt_install('vim', fix_missing=True) +``` + + + +### add\_mcp\_server + +```python +def add_mcp_server(servers: Union[str, List[str]]) -> "TemplateBuilder" +``` + +Install MCP servers using mcp-gateway. + +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +**Arguments**: + +- `servers`: MCP server name(s) + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.add_mcp_server('exa') +template.add_mcp_server(['brave', 'firecrawl', 'duckduckgo']) +``` + + + +### git\_clone + +```python +def git_clone(url: str, + path: Optional[Union[str, Path]] = None, + branch: Optional[str] = None, + depth: Optional[int] = None, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Clone a git repository into the template. + +**Arguments**: + +- `url`: Git repository URL +- `path`: Destination path for the clone +- `branch`: Branch to clone +- `depth`: Clone depth for shallow clones +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.git_clone('https://github.com/user/repo.git', '/app/repo') +template.git_clone('https://github.com/user/repo.git', branch='main', depth=1) +template.git_clone('https://github.com/user/repo.git', '/app/repo', user='root') +``` + + + +### beta\_dev\_container\_prebuild + +```python +def beta_dev_container_prebuild( + devcontainer_directory: Union[str, Path]) -> "TemplateBuilder" +``` + +Prebuild a devcontainer from the specified directory during the build process. + +**Arguments**: + +- `devcontainer_directory`: Path to the devcontainer directory + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_dev_container_prebuild('/my-devcontainer') +``` + + + +### beta\_set\_dev\_container\_start + +```python +def beta_set_dev_container_start( + devcontainer_directory: Union[str, Path]) -> "TemplateFinal" +``` + +Start a devcontainer from the specified directory and set it as the start command. + +This method returns `TemplateFinal`, which means it must be the last method in the chain. + +**Arguments**: + +- `devcontainer_directory`: Path to the devcontainer directory + +**Returns**: + +`TemplateFinal` class +Example +```python +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_set_devcontainer_start('/my-devcontainer') + +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_dev_container_prebuild('/my-devcontainer') +template.beta_set_dev_container_start('/my-devcontainer') +``` + + + +### set\_envs + +```python +def set_envs(envs: Dict[str, str]) -> "TemplateBuilder" +``` + +Set environment variables. + +Note: Environment variables defined here are available only during template build. + +**Arguments**: + +- `envs`: Dictionary of environment variable names and values + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_envs({'NODE_ENV': 'production', 'PORT': '8080'}) +``` + + + +### skip\_cache + +```python +def skip_cache() -> "TemplateBuilder" +``` + +Skip cache for all subsequent build instructions from this point. + +Call this before any instruction to force it and all following layers +to be rebuilt, ignoring any cached layers. + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.skip_cache().run_cmd('apt-get update') +``` + + + +### set\_start\_cmd + +```python +def set_start_cmd(start_cmd: str, + ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" +``` + +Set the command to start when the sandbox launches and the ready check command. + +**Arguments**: + +- `start_cmd`: Command to run when the sandbox starts +- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready + +**Returns**: + +`TemplateFinal` class +Example +```python +template.set_start_cmd( + 'python app.py', + 'curl http://localhost:8000/health' +) + +from e2b import wait_for_port, wait_for_url + +template.set_start_cmd( + 'python -m http.server 8000', + wait_for_port(8000) +) + +template.set_start_cmd( + 'npm start', + wait_for_url('http://localhost:3000/health', 200) +) +``` + + + +### set\_ready\_cmd + +```python +def set_ready_cmd(ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" +``` + +Set the command to check if the sandbox is ready. + +**Arguments**: + +- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready + +**Returns**: + +`TemplateFinal` class +Example +```python +template.set_ready_cmd('curl http://localhost:8000/health') + +from e2b import wait_for_port, wait_for_file, wait_for_process + +template.set_ready_cmd(wait_for_port(3000)) + +template.set_ready_cmd(wait_for_file('/tmp/ready')) + +template.set_ready_cmd(wait_for_process('nginx')) +``` + + + +## TemplateFinal + +```python +class TemplateFinal() +``` + +Final template state after start/ready commands are set. + + + +## TemplateBase + +```python +class TemplateBase() +``` + +Base class for building E2B sandbox templates. + + + +### \_\_init\_\_ + +```python +def __init__(file_context_path: Optional[Union[str, Path]] = None, + file_ignore_patterns: Optional[List[str]] = None) +``` + +Create a new template builder instance. + +**Arguments**: + +- `file_context_path`: Base path for resolving relative file paths in copy operations +- `file_ignore_patterns`: List of glob patterns to ignore when copying files + + + +### skip\_cache + +```python +def skip_cache() -> "TemplateBase" +``` + +Skip cache for all subsequent build instructions from this point. + +**Returns**: + +`TemplateBase` class +Example +```python +template.skip_cache().from_python_image('3.11') +``` + + + +### from\_debian\_image + +```python +def from_debian_image(variant: str = "stable") -> TemplateBuilder +``` + +Start template from a Debian base image. + +**Arguments**: + +- `variant`: Debian image variant + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_debian_image('bookworm') +``` + + + +### from\_ubuntu\_image + +```python +def from_ubuntu_image(variant: str = "latest") -> TemplateBuilder +``` + +Start template from an Ubuntu base image. + +**Arguments**: + +- `variant`: Ubuntu image variant (default: 'latest') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_ubuntu_image('24.04') +``` + + + +### from\_python\_image + +```python +def from_python_image(version: str = "3") -> TemplateBuilder +``` + +Start template from a Python base image. + +**Arguments**: + +- `version`: Python version (default: '3') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_python_image('3') +``` + + + +### from\_node\_image + +```python +def from_node_image(variant: str = "lts") -> TemplateBuilder +``` + +Start template from a Node.js base image. + +**Arguments**: + +- `variant`: Node.js image variant (default: 'lts') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_node_image('24') +``` + + + +### from\_bun\_image + +```python +def from_bun_image(variant: str = "latest") -> TemplateBuilder +``` + +Start template from a Bun base image. + +**Arguments**: + +- `variant`: Bun image variant (default: 'latest') + +**Returns**: + +`TemplateBuilder` class + + + +### from\_base\_image + +```python +def from_base_image() -> TemplateBuilder +``` + +Start template from the E2B base image (e2bdev/base:latest). + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_base_image() +``` + + + +### from\_image + +```python +def from_image(image: str, + username: Optional[str] = None, + password: Optional[str] = None) -> TemplateBuilder +``` + +Start template from a Docker image. + +**Arguments**: + +- `image`: Docker image name (e.g., 'ubuntu:24.04') +- `username`: Username for private registry authentication +- `password`: Password for private registry authentication + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_image('python:3') + +Template().from_image('myregistry.com/myimage:latest', username='user', password='pass') +``` + + + +### from\_template + +```python +def from_template(template: str) -> TemplateBuilder +``` + +Start template from an existing E2B template. + +**Arguments**: + +- `template`: E2B template ID or alias + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_template('my-base-template') +``` + + + +### from\_dockerfile + +```python +def from_dockerfile(dockerfile_content_or_path: str) -> TemplateBuilder +``` + +Parse a Dockerfile and convert it to Template SDK format. + +**Arguments**: + +- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_dockerfile('Dockerfile') +Template().from_dockerfile('FROM python:3\nRUN pip install numpy') +``` + + + +### from\_aws\_registry + +```python +def from_aws_registry(image: str, access_key_id: str, secret_access_key: str, + region: str) -> TemplateBuilder +``` + +Start template from an AWS ECR registry image. + +**Arguments**: + +- `image`: Docker image name from AWS ECR +- `access_key_id`: AWS access key ID +- `secret_access_key`: AWS secret access key +- `region`: AWS region + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_aws_registry( + '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', + access_key_id='AKIA...', + secret_access_key='...', + region='us-west-2' +) +``` + + + +### from\_gcp\_registry + +```python +def from_gcp_registry( + image: str, service_account_json: Union[str, dict]) -> TemplateBuilder +``` + +Start template from a GCP Artifact Registry or Container Registry image. + +**Arguments**: + +- `image`: Docker image name from GCP registry +- `service_account_json`: Service account JSON string, dict, or path to JSON file + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_gcp_registry( + 'gcr.io/myproject/myimage:latest', + service_account_json='path/to/service-account.json' +) +``` + + + +### to\_json + +```python +@staticmethod +def to_json(template: "TemplateClass") -> str +``` + +Convert a template to JSON representation. + +**Arguments**: + +- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) + +**Returns**: + +JSON string representation of the template +Example +```python +template = Template().from_python_image('3').copy('app.py', '/app/') +json_str = TemplateBase.to_json(template) +``` + + + +### to\_dockerfile + +```python +@staticmethod +def to_dockerfile(template: "TemplateClass") -> str +``` + +Convert a template to Dockerfile format. + +Note: Templates based on other E2B templates cannot be converted to Dockerfile. + +**Arguments**: + +- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) + +**Raises**: + +- `ValueError`: If the template is based on another E2B template or has no base image +Example +```python +template = Template().from_python_image('3').copy('app.py', '/app/') +dockerfile = TemplateBase.to_dockerfile(template) +``` + +**Returns**: + +Dockerfile string representation + + + + + + +## LogEntry + +```python +@dataclass +class LogEntry() +``` + +Represents a single log entry from the template build process. + + + +## LogEntryStart + +```python +@dataclass +class LogEntryStart(LogEntry) +``` + +Special log entry indicating the start of a build process. + + + +## LogEntryEnd + +```python +@dataclass +class LogEntryEnd(LogEntry) +``` + +Special log entry indicating the end of a build process. + + + +### TIMER\_UPDATE\_INTERVAL\_MS + +Default minimum log level to display. + + + +### DEFAULT\_LEVEL + +Colored labels for each log level. + + + +### levels + +Numeric ordering of log levels for comparison (lower = less severe). + + + +### set\_interval + +```python +def set_interval(func, interval) +``` + +Returns a stop function that can be called to cancel the interval. + +Similar to JavaScript's setInterval. + +**Arguments**: + +- `func`: Function to execute at each interval +- `interval`: Interval duration in **seconds** + +**Returns**: + +Stop function that can be called to cancel the interval + + + +### default\_build\_logger + +```python +def default_build_logger( + min_level: Optional[LogEntryLevel] = None +) -> Callable[[LogEntry], None] +``` + +Create a default build logger with animated timer display. + +**Arguments**: + +- `min_level`: Minimum log level to display (default: 'info') + +**Returns**: + +Logger function that accepts LogEntry instances +Example +```python +from e2b import Template, default_build_logger + +template = Template().from_python_image() + +``` + + + + + + +### make\_traceback + +```python +def make_traceback( + caller_frame: Optional[FrameType]) -> Optional[TracebackType] +``` + +Create a TracebackType from a caller frame for error reporting. + +**Arguments**: + +- `caller_frame`: The caller's frame object, or None + +**Returns**: + +A TracebackType object for use with exception.with_traceback(), or None + + + +### validate\_relative\_path + +```python +def validate_relative_path(src: str, + stack_trace: Optional[TracebackType]) -> None +``` + +Validate that a source path for copy operations is a relative path that stays + +within the context directory. This prevents path traversal attacks and ensures +files are copied from within the expected directory. + +**Arguments**: + +- `src`: The source path to validate +- `stack_trace`: Optional stack trace for error reporting + +**Raises**: + +- `TemplateException`: If the path is absolute or escapes the context directory +Invalid paths: +- Absolute paths: /absolute/path, C:\Windows\path +- Parent directory escapes: ../foo, foo/../../bar, ./foo/../../../bar + +Valid paths: +- Simple relative: foo, foo/bar +- Current directory prefix: ./foo, ./foo/bar +- Internal parent refs that don't escape: foo/../bar (stays within context) + + + +### normalize\_build\_arguments + +```python +def normalize_build_arguments(name: Optional[str] = None, + alias: Optional[str] = None) -> str +``` + +Normalize build arguments from different parameter signatures. + +Handles string name or legacy alias parameter. + +**Arguments**: + +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. + +**Raises**: + +- `TemplateException`: If no template name is provided + +**Returns**: + +Normalized template name + + + +### read\_dockerignore + +```python +def read_dockerignore(context_path: str) -> List[str] +``` + +Read and parse a .dockerignore file. + +**Arguments**: + +- `context_path`: Directory path containing the .dockerignore file + +**Returns**: + +Array of ignore patterns (empty lines and comments are filtered out) + + + +### normalize\_path + +```python +def normalize_path(path: str) -> str +``` + +Normalize path separators to forward slashes for glob patterns (glob expects / even on Windows). + +**Arguments**: + +- `path`: The path to normalize + +**Returns**: + +The normalized path + + + +### get\_all\_files\_in\_path + +```python +def get_all_files_in_path(src: str, + context_path: str, + ignore_patterns: List[str], + include_directories: bool = True) -> List[str] +``` + +Get all files for a given path and ignore patterns. + +**Arguments**: + +- `src`: Path to the source directory +- `context_path`: Base directory for resolving relative paths +- `ignore_patterns`: Ignore patterns +- `include_directories`: Whether to include directories + +**Returns**: + +Array of files + + + +### calculate\_files\_hash + +```python +def calculate_files_hash(src: str, dest: str, context_path: str, + ignore_patterns: List[str], resolve_symlinks: bool, + stack_trace: Optional[TracebackType]) -> str +``` + +Calculate a hash of files being copied to detect changes for cache invalidation. + +The hash includes file content, metadata (mode, size), and relative paths. +Note: uid, gid, and mtime are excluded to ensure stable hashes across environments. + +**Arguments**: + +- `src`: Source path pattern for files to copy +- `dest`: Destination path where files will be copied +- `context_path`: Base directory for resolving relative paths +- `ignore_patterns`: Glob patterns to ignore +- `resolve_symlinks`: Whether to resolve symbolic links when hashing +- `stack_trace`: Optional stack trace for error reporting + +**Raises**: + +- `ValueError`: If no files match the source pattern + +**Returns**: + +Hex string hash of all files + + + +### tar\_file\_stream + +```python +def tar_file_stream(file_name: str, file_context_path: str, + ignore_patterns: List[str], + resolve_symlinks: bool) -> io.BytesIO +``` + +Create a tar stream of files matching a pattern. + +**Arguments**: + +- `file_name`: Glob pattern for files to include +- `file_context_path`: Base directory for resolving file paths +- `ignore_patterns`: Ignore patterns +- `resolve_symlinks`: Whether to resolve symbolic links + +**Returns**: + +Tar stream + + + +### strip\_ansi\_escape\_codes + +```python +def strip_ansi_escape_codes(text: str) -> str +``` + +Strip ANSI escape codes from a string. + +Source: https://github.com/chalk/ansi-regex/blob/main/index.js + +**Arguments**: + +- `text`: String with ANSI escape codes + +**Returns**: + +String without ANSI escape codes + + + +### get\_caller\_frame + +```python +def get_caller_frame(depth: int) -> Optional[FrameType] +``` + +Get the caller's stack frame at a specific depth. + +This is used to provide better error messages and debugging information +by tracking where template methods were called from in user code. + +**Arguments**: + +- `depth`: The depth of the stack trace to retrieve + +**Returns**: + +The caller frame, or None if not available + + + +### get\_caller\_directory + +```python +def get_caller_directory(depth: int) -> Optional[str] +``` + +Get the directory of the caller at a specific stack depth. + +This is used to determine the file_context_path when creating a template, +so file paths are resolved relative to the user's template file location. + +**Arguments**: + +- `depth`: The depth of the stack trace + +**Returns**: + +The caller's directory path, or None if not available + + + +### pad\_octal + +```python +def pad_octal(mode: int) -> str +``` + +Convert a numeric file mode to a zero-padded octal string. + +**Arguments**: + +- `mode`: File mode as a number (e.g., 493 for 0o755) + +**Returns**: + +Zero-padded 4-digit octal string (e.g., "0755") +Example +```python +pad_octal(0o755) # Returns "0755" +pad_octal(0o644) # Returns "0644" +``` + + + +### get\_build\_step\_index + +```python +def get_build_step_index(step: str, stack_traces_length: int) -> int +``` + +Get the array index for a build step based on its name. + +Special steps: +- BASE_STEP_NAME: Returns 0 (first step) +- FINALIZE_STEP_NAME: Returns the last index +- Numeric strings: Converted to number + +**Arguments**: + +- `step`: Build step name or number as string +- `stack_traces_length`: Total number of stack traces (used for FINALIZE_STEP_NAME) + +**Returns**: + +Index for the build step + + + +### read\_gcp\_service\_account\_json + +```python +def read_gcp_service_account_json(context_path: str, + path_or_content: Union[str, dict]) -> str +``` + +Read GCP service account JSON from a file or object. + +**Arguments**: + +- `context_path`: Base directory for resolving relative file paths +- `path_or_content`: Either a path to a JSON file or a service account object + +**Returns**: + +Service account JSON as a string + + + + + + +## DockerfFileFinalParserInterface + +```python +class DockerfFileFinalParserInterface(Protocol) +``` + +Protocol defining the final interface for Dockerfile parsing callbacks. + + + +## DockerfileParserInterface + +```python +class DockerfileParserInterface(Protocol) +``` + +Protocol defining the interface for Dockerfile parsing callbacks. + + + +### run\_cmd + +```python +def run_cmd(command: Union[str, List[str]], + user: Optional[str] = None) -> "DockerfileParserInterface" +``` + +Handle RUN instruction. + + + +### copy + +```python +def copy( + src: str, + dest: str, + force_upload: Optional[Literal[True]] = None, + user: Optional[str] = None, + mode: Optional[int] = None, + resolve_symlinks: Optional[bool] = None +) -> "DockerfileParserInterface" +``` + +Handle COPY instruction. + + + +### set\_workdir + +```python +def set_workdir(workdir: str) -> "DockerfileParserInterface" +``` + +Handle WORKDIR instruction. + + + +### set\_user + +```python +def set_user(user: str) -> "DockerfileParserInterface" +``` + +Handle USER instruction. + + + +### set\_envs + +```python +def set_envs(envs: Dict[str, str]) -> "DockerfileParserInterface" +``` + +Handle ENV instruction. + + + +### set\_start\_cmd + +```python +def set_start_cmd(start_cmd: str, + ready_cmd: str) -> "DockerfFileFinalParserInterface" +``` + +Handle CMD/ENTRYPOINT instruction. + + + +### parse\_dockerfile + +```python +def parse_dockerfile(dockerfile_content_or_path: str, + template_builder: DockerfileParserInterface) -> str +``` + +Parse a Dockerfile and convert it to Template SDK format. + +**Arguments**: + +- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file +- `template_builder`: Interface providing template builder methods + +**Raises**: + +- `ValueError`: If the Dockerfile is invalid or unsupported + +**Returns**: + +The base image from the Dockerfile + + + + + + +## TemplateBuildStatus + +```python +class TemplateBuildStatus(str, Enum) +``` + +Status of a template build. + + + +## BuildStatusReason + +```python +@dataclass +class BuildStatusReason() +``` + +Reason for the current build status (typically for errors). + + + +### message + +Message with the status reason. + + + +### step + +Step that failed. + + + +### log\_entries + +Log entries related to the status reason. + + + +## TemplateBuildStatusResponse + +```python +@dataclass +class TemplateBuildStatusResponse() +``` + +Response from getting build status. + + + +### build\_id + +Build identifier. + + + +### template\_id + +Template identifier. + + + +### status + +Current status of the build. + + + +### log\_entries + +Build log entries. + + + +### logs + +Build logs (raw strings). Deprecated: use log_entries instead. + + + +### reason + +Reason for the current status (typically for errors). + + + +## TemplateTagInfo + +```python +@dataclass +class TemplateTagInfo() +``` + +Information about assigned template tags. + + + +### build\_id + +Build identifier associated with this tag. + + + +### tags + +Assigned tags of the template. + + + +## TemplateTag + +```python +@dataclass +class TemplateTag() +``` + +Detailed information about a single template tag. + + + +### tag + +Name of the tag. + + + +### build\_id + +Build identifier associated with this tag. + + + +### created\_at + +When this tag was assigned. + + + +## InstructionType + +```python +class InstructionType(str, Enum) +``` + +Types of instructions that can be used in a template. + + + +## CopyItem + +```python +class CopyItem(TypedDict) +``` + +Configuration for a single file/directory copy operation. + + + +## Instruction + +```python +class Instruction(TypedDict) +``` + +Represents a single instruction in the template build process. + + + +## GenericDockerRegistry + +```python +class GenericDockerRegistry(TypedDict) +``` + +Configuration for a generic Docker registry with basic authentication. + + + +## AWSRegistry + +```python +class AWSRegistry(TypedDict) +``` + +Configuration for AWS Elastic Container Registry (ECR). + + + +## GCPRegistry + +```python +class GCPRegistry(TypedDict) +``` + +Configuration for Google Container Registry (GCR) or Artifact Registry. + + + +## TemplateType + +```python +class TemplateType(TypedDict) +``` + +Internal representation of a template for the E2B build API. + + + +## BuildInfo + +```python +@dataclass +class BuildInfo() +``` + +Information about a built template. + + + + +Special step name for the finalization phase of template building. +This is the last step that runs after all user-defined instructions. + + + +### FINALIZE\_STEP\_NAME + +Special step name for the base image phase of template building. +This is the first step that sets up the base image. + + + +### BASE\_STEP\_NAME + +Stack trace depth for capturing caller information. + +Depth levels: +1. TemplateClass +2. Caller method (e.g., copy(), from_image(), etc.) + +This depth is used to determine the original caller's location +for stack traces. + + + +### STACK\_TRACE\_DEPTH + +Default setting for whether to resolve symbolic links when copying files. +When False, symlinks are copied as symlinks rather than following them. + + + + + + +## ReadyCmd + +```python +class ReadyCmd() +``` + +Wrapper class for ready check commands. + + + +### wait\_for\_port + +```python +def wait_for_port(port: int) +``` + +Wait for a port to be listening. + +Uses `ss` command to check if a port is open and listening. + +**Arguments**: + +- `port`: Port number to wait for + +**Returns**: + +ReadyCmd that checks for the port +Example +```python +from e2b import Template, wait_for_port + +template = ( + Template() + .from_python_image() + .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) +) +``` + + + +### wait\_for\_url + +```python +def wait_for_url(url: str, status_code: int = 200) +``` + +Wait for a URL to return a specific HTTP status code. + +Uses `curl` to make HTTP requests and check the response status. + +**Arguments**: + +- `url`: URL to check (e.g., 'http://localhost:3000/health') +- `status_code`: Expected HTTP status code (default: 200) + +**Returns**: + +ReadyCmd that checks the URL +Example +```python +from e2b import Template, wait_for_url + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) +) +``` + + + +### wait\_for\_process + +```python +def wait_for_process(process_name: str) +``` + +Wait for a process with a specific name to be running. + +Uses `pgrep` to check if a process exists. + +**Arguments**: + +- `process_name`: Name of the process to wait for + +**Returns**: + +ReadyCmd that checks for the process +Example +```python +from e2b import Template, wait_for_process + +template = ( + Template() + .from_base_image() + .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) +) +``` + + + +### wait\_for\_file + +```python +def wait_for_file(filename: str) +``` + +Wait for a file to exist. + +Uses shell test command to check file existence. + +**Arguments**: + +- `filename`: Path to the file to wait for + +**Returns**: + +ReadyCmd that checks for the file +Example +```python +from e2b import Template, wait_for_file + +template = ( + Template() + .from_base_image() + .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) +) +``` + + + +### wait\_for\_timeout + +```python +def wait_for_timeout(timeout: int) +``` + +Wait for a specified timeout before considering the sandbox ready. + +Uses `sleep` command to wait for a fixed duration. + +**Arguments**: + +- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) + +**Returns**: + +ReadyCmd that waits for the specified duration +Example +```python +from e2b import Template, wait_for_timeout + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds +) +``` diff --git a/docs/sdk-reference/python-sdk/v2.19.0/template_async.mdx b/docs/sdk-reference/python-sdk/v2.19.0/template_async.mdx new file mode 100644 index 00000000..f75603fb --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.19.0/template_async.mdx @@ -0,0 +1,357 @@ +--- +sidebarTitle: "Template Async" +--- + + + + + + +## AsyncTemplate + +```python +class AsyncTemplate(TemplateBase) +``` + +Asynchronous template builder for E2B sandboxes. + + + +### build + +```python +@staticmethod +async def build(template: TemplateClass, + name: Optional[str] = None, + *, + alias: Optional[str] = None, + tags: Optional[List[str]] = None, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], None]] = None, + **opts: Unpack[ApiParams]) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure. + +**Arguments**: + +- `template`: The template to build +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. +- `tags`: Optional additional tags to assign to the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `on_build_logs`: Callback function to receive build logs during the build process +Example +```python +from e2b import AsyncTemplate + +template = ( + AsyncTemplate() + .from_python_image('3') + .copy('requirements.txt', '/home/user/') + .run_cmd('pip install -r /home/user/requirements.txt') +) + +await AsyncTemplate.build(template, 'my-python-env:v1.0') + +await AsyncTemplate.build(template, 'my-python-env', tags=['v1.1.0', 'stable']) +``` + + + +### build\_in\_background + +```python +@staticmethod +async def build_in_background(template: TemplateClass, + name: Optional[str] = None, + *, + alias: Optional[str] = None, + tags: Optional[List[str]] = None, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], + None]] = None, + **opts: Unpack[ApiParams]) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +**Arguments**: + +- `template`: The template to build +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. +- `tags`: Optional additional tags to assign to the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache + +**Returns**: + +BuildInfo containing the template ID and build ID +Example +```python +from e2b import AsyncTemplate + +template = ( + AsyncTemplate() + .from_python_image('3') + .run_cmd('echo "test"') + .set_start_cmd('echo "Hello"', 'sleep 1') +) + +build_info = await AsyncTemplate.build_in_background(template, 'my-python-env:v1.0') + +build_info = await AsyncTemplate.build_in_background(template, 'my-python-env', tags=['v1.1.0', 'stable']) +``` + + + +### get\_build\_status + +```python +@staticmethod +async def get_build_status(build_info: BuildInfo, + logs_offset: int = 0, + **opts: Unpack[ApiParams]) +``` + +Get the status of a build. + +**Arguments**: + +- `build_info`: Build identifiers returned from build_in_background +- `logs_offset`: Offset for fetching logs + +**Returns**: + +TemplateBuild containing the build status and logs +Example +```python +from e2b import AsyncTemplate + +build_info = await AsyncTemplate.build_in_background(template, alias='my-template') +status = await AsyncTemplate.get_build_status(build_info, logs_offset=0) +``` + + + +### exists + +```python +@staticmethod +async def exists(name: str, **opts: Unpack[ApiParams]) -> bool +``` + +Check if a template with the given name exists. + +**Arguments**: + +- `name`: Template name to check + +**Returns**: + +True if the name exists, False otherwise +Example +```python +from e2b import AsyncTemplate + +exists = await AsyncTemplate.exists('my-python-env') +if exists: + print('Template exists!') +``` + + + +### alias\_exists + +```python +@staticmethod +async def alias_exists(alias: str, **opts: Unpack[ApiParams]) -> bool +``` + +Check if a template with the given alias exists. + +Deprecated Use `exists` instead. + +**Arguments**: + +- `alias`: Template alias to check + +**Returns**: + +True if the alias exists, False otherwise +Example +```python +from e2b import AsyncTemplate + +exists = await AsyncTemplate.alias_exists('my-python-env') +if exists: + print('Template exists!') +``` + + + +### assign\_tags + +```python +@staticmethod +async def assign_tags(target_name: str, tags: Union[str, List[str]], + **opts: Unpack[ApiParams]) -> TemplateTagInfo +``` + +Assign tag(s) to an existing template build. + +**Arguments**: + +- `target_name`: Template name in 'name:tag' format (the source build to tag from) +- `tags`: Tag or tags to assign + +**Returns**: + +TemplateTagInfo with build_id and assigned tags +Example +```python +from e2b import AsyncTemplate + +result = await AsyncTemplate.assign_tags('my-template:v1.0', 'production') + +result = await AsyncTemplate.assign_tags('my-template:v1.0', ['production', 'stable']) +``` + + + +### remove\_tags + +```python +@staticmethod +async def remove_tags(name: str, tags: Union[str, List[str]], + **opts: Unpack[ApiParams]) -> None +``` + +Remove tag(s) from a template. + +**Arguments**: + +- `name`: Template name +- `tags`: Tag or tags to remove +Example +```python +from e2b import AsyncTemplate + +await AsyncTemplate.remove_tags('my-template', 'production') + +await AsyncTemplate.remove_tags('my-template', ['production', 'stable']) +``` + + + +### get\_tags + +```python +@staticmethod +async def get_tags(template_id: str, + **opts: Unpack[ApiParams]) -> List[TemplateTag] +``` + +Get all tags for a template. + +**Arguments**: + +- `template_id`: Template ID or name + +**Returns**: + +List of TemplateTag with tag name, build_id, and created_at +Example +```python +from e2b import AsyncTemplate + +tags = await AsyncTemplate.get_tags('my-template') +for tag in tags: + print(f"Tag: {tag.tag}, Build: {tag.build_id}, Created: {tag.created_at}") +``` + + + + + + +### check\_alias\_exists + +```python +async def check_alias_exists(client: AuthenticatedClient, alias: str) -> bool +``` + +Check if a template with the given alias exists. + +**Arguments**: + +- `client` - Authenticated API client +- `alias` - Template alias to check + + +**Returns**: + + True if the alias exists, False otherwise + + + +### assign\_tags + +```python +async def assign_tags(client: AuthenticatedClient, target_name: str, + tags: List[str]) -> TemplateTagInfo +``` + +Assign tag(s) to an existing template build. + +**Arguments**: + +- `client` - Authenticated API client +- `target_name` - Template name in 'name:tag' format (the source build to tag from) +- `tags` - Tags to assign + + +**Returns**: + + TemplateTagInfo with build_id and assigned tags + + + +### remove\_tags + +```python +async def remove_tags(client: AuthenticatedClient, name: str, + tags: List[str]) -> None +``` + +Remove tag(s) from a template. + +**Arguments**: + +- `client` - Authenticated API client +- `name` - Template name +- `tags` - List of tags to remove + + + +### get\_template\_tags + +```python +async def get_template_tags(client: AuthenticatedClient, + template_id: str) -> List[TemplateTag] +``` + +Get all tags for a template. + +**Arguments**: + +- `client` - Authenticated API client +- `template_id` - Template ID or name diff --git a/docs/sdk-reference/python-sdk/v2.19.0/template_sync.mdx b/docs/sdk-reference/python-sdk/v2.19.0/template_sync.mdx new file mode 100644 index 00000000..ff5cee37 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.19.0/template_sync.mdx @@ -0,0 +1,356 @@ +--- +sidebarTitle: "Template Sync" +--- + + + + + + +## Template + +```python +class Template(TemplateBase) +``` + +Synchronous template builder for E2B sandboxes. + + + +### build + +```python +@staticmethod +def build(template: TemplateClass, + name: Optional[str] = None, + *, + alias: Optional[str] = None, + tags: Optional[List[str]] = None, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], None]] = None, + **opts: Unpack[ApiParams]) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure. + +**Arguments**: + +- `template`: The template to build +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. +- `tags`: Optional additional tags to assign to the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `on_build_logs`: Callback function to receive build logs during the build process +Example +```python +from e2b import Template + +template = ( + Template() + .from_python_image('3') + .copy('requirements.txt', '/home/user/') + .run_cmd('pip install -r /home/user/requirements.txt') +) + +Template.build(template, 'my-python-env:v1.0') + +Template.build(template, 'my-python-env', tags=['v1.1.0', 'stable']) +``` + + + +### build\_in\_background + +```python +@staticmethod +def build_in_background(template: TemplateClass, + name: Optional[str] = None, + *, + alias: Optional[str] = None, + tags: Optional[List[str]] = None, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], + None]] = None, + **opts: Unpack[ApiParams]) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +**Arguments**: + +- `template`: The template to build +- `name`: Template name in 'name' or 'name:tag' format +- `alias`: (Deprecated) Alias name for the template. Use name instead. +- `tags`: Optional additional tags to assign to the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache + +**Returns**: + +BuildInfo containing the template ID and build ID +Example +```python +from e2b import Template + +template = ( + Template() + .from_python_image('3') + .run_cmd('echo "test"') + .set_start_cmd('echo "Hello"', 'sleep 1') +) + +build_info = Template.build_in_background(template, 'my-python-env:v1.0') + +build_info = Template.build_in_background(template, 'my-python-env', tags=['v1.1.0', 'stable']) +``` + + + +### get\_build\_status + +```python +@staticmethod +def get_build_status(build_info: BuildInfo, + logs_offset: int = 0, + **opts: Unpack[ApiParams]) +``` + +Get the status of a build. + +**Arguments**: + +- `build_info`: Build identifiers returned from build_in_background +- `logs_offset`: Offset for fetching logs + +**Returns**: + +TemplateBuild containing the build status and logs +Example +```python +from e2b import Template + +build_info = Template.build_in_background(template, alias='my-template') +status = Template.get_build_status(build_info, logs_offset=0) +``` + + + +### exists + +```python +@staticmethod +def exists(name: str, **opts: Unpack[ApiParams]) -> bool +``` + +Check if a template with the given name exists. + +**Arguments**: + +- `name`: Template name to check + +**Returns**: + +True if the name exists, False otherwise +Example +```python +from e2b import Template + +exists = Template.exists('my-python-env') +if exists: + print('Template exists!') +``` + + + +### alias\_exists + +```python +@staticmethod +def alias_exists(alias: str, **opts: Unpack[ApiParams]) -> bool +``` + +Check if a template with the given alias exists. + +Deprecated Use `exists` instead. + +**Arguments**: + +- `alias`: Template alias to check + +**Returns**: + +True if the alias exists, False otherwise +Example +```python +from e2b import Template + +exists = Template.alias_exists('my-python-env') +if exists: + print('Template exists!') +``` + + + +### assign\_tags + +```python +@staticmethod +def assign_tags(target_name: str, tags: Union[str, List[str]], + **opts: Unpack[ApiParams]) -> TemplateTagInfo +``` + +Assign tag(s) to an existing template build. + +**Arguments**: + +- `target_name`: Template name in 'name:tag' format (the source build to tag from) +- `tags`: Tag or tags to assign + +**Returns**: + +TemplateTagInfo with build_id and assigned tags +Example +```python +from e2b import Template + +result = Template.assign_tags('my-template:v1.0', 'production') + +result = Template.assign_tags('my-template:v1.0', ['production', 'stable']) +``` + + + +### remove\_tags + +```python +@staticmethod +def remove_tags(name: str, tags: Union[str, List[str]], + **opts: Unpack[ApiParams]) -> None +``` + +Remove tag(s) from a template. + +**Arguments**: + +- `name`: Template name +- `tags`: Tag or tags to remove +Example +```python +from e2b import Template + +Template.remove_tags('my-template', 'production') + +Template.remove_tags('my-template', ['production', 'stable']) +``` + + + +### get\_tags + +```python +@staticmethod +def get_tags(template_id: str, **opts: Unpack[ApiParams]) -> List[TemplateTag] +``` + +Get all tags for a template. + +**Arguments**: + +- `template_id`: Template ID or name + +**Returns**: + +List of TemplateTag with tag name, build_id, and created_at +Example +```python +from e2b import Template + +tags = Template.get_tags('my-template') +for tag in tags: + print(f"Tag: {tag.tag}, Build: {tag.build_id}, Created: {tag.created_at}") +``` + + + + + + +### check\_alias\_exists + +```python +def check_alias_exists(client: AuthenticatedClient, alias: str) -> bool +``` + +Check if a template with the given alias exists. + +**Arguments**: + +- `client` - Authenticated API client +- `alias` - Template alias to check + + +**Returns**: + + True if the alias exists, False otherwise + + + +### assign\_tags + +```python +def assign_tags(client: AuthenticatedClient, target_name: str, + tags: List[str]) -> TemplateTagInfo +``` + +Assign tag(s) to an existing template build. + +**Arguments**: + +- `client` - Authenticated API client +- `target_name` - Template name in 'name:tag' format (the source build to tag from) +- `tags` - Tags to assign + + +**Returns**: + + TemplateTagInfo with build_id and assigned tags + + + +### remove\_tags + +```python +def remove_tags(client: AuthenticatedClient, name: str, + tags: List[str]) -> None +``` + +Remove tag(s) from a template. + +**Arguments**: + +- `client` - Authenticated API client +- `name` - Template name +- `tags` - List of tags to remove + + + +### get\_template\_tags + +```python +def get_template_tags(client: AuthenticatedClient, + template_id: str) -> List[TemplateTag] +``` + +Get all tags for a template. + +**Arguments**: + +- `client` - Authenticated API client +- `template_id` - Template ID or name diff --git a/docs/sdk-reference/python-sdk/v2.19.0/volume_async.mdx b/docs/sdk-reference/python-sdk/v2.19.0/volume_async.mdx new file mode 100644 index 00000000..8dcea0fd --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.19.0/volume_async.mdx @@ -0,0 +1,220 @@ +--- +sidebarTitle: "Volume Async" +--- + + + + + + +## AsyncVolume + +```python +class AsyncVolume() +``` + +E2B Volume for persistent storage that can be mounted to sandboxes (async). + + + +### create + +```python +@classmethod +async def create(cls, name: str, **opts: Unpack[ApiParams]) -> "AsyncVolume" +``` + +Create a new volume. + +**Arguments**: + +- `name`: Name of the volume + +**Returns**: + +An AsyncVolume instance for the new volume + + + +### connect + +```python +@classmethod +async def connect(cls, volume_id: str, + **opts: Unpack[ApiParams]) -> "AsyncVolume" +``` + +Connect to an existing volume by ID. + +**Arguments**: + +- `volume_id`: Volume ID + +**Returns**: + +An AsyncVolume instance for the existing volume + + + +### destroy + +```python +@staticmethod +async def destroy(volume_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Destroy a volume. + +**Arguments**: + +- `volume_id`: Volume ID + + + +### make\_dir + +```python +async def make_dir(path: str, + uid: Optional[int] = None, + gid: Optional[int] = None, + mode: Optional[int] = None, + force: Optional[bool] = None, + **opts: Unpack[VolumeApiParams]) -> VolumeEntryStat +``` + +Create a directory. + +**Arguments**: + +- `path`: Path to the directory to create +- `uid`: User ID of the created directory +- `gid`: Group ID of the created directory +- `mode`: Mode of the created directory +- `force`: Create parent directories if they don't exist +- `opts`: Connection options + +**Returns**: + +Information about the created directory + + + +### exists + +```python +async def exists(path: str, **opts: Unpack[VolumeApiParams]) -> bool +``` + +Check whether a file or directory exists. + +Uses get_info under the hood. Returns True if the path exists, +False if it does not (404). Other errors are re-raised. + +**Arguments**: + +- `path`: Path to the file or directory +- `opts`: Connection options + +**Returns**: + +True if the path exists, False otherwise + + + +### update\_metadata + +```python +async def update_metadata(path: str, + uid: Optional[int] = None, + gid: Optional[int] = None, + mode: Optional[int] = None, + **opts: Unpack[VolumeApiParams]) -> VolumeEntryStat +``` + +Update file or directory metadata. + +**Arguments**: + +- `path`: Path to the file or directory +- `uid`: User ID of the file or directory +- `gid`: Group ID of the file or directory +- `mode`: Mode of the file or directory +- `opts`: Connection options + +**Returns**: + +Updated entry information + + + +### read\_file + +```python +async def read_file( + path: str, + format: Literal["text", "bytes", "stream"] = "text", + **opts: Unpack[VolumeApiParams] +) -> Union[str, bytes, AsyncIterator[bytes]] +``` + +Read file content. + +You can pass `text`, `bytes`, or `stream` to `format` to change the return type. + +**Arguments**: + +- `path`: Path to the file +- `format`: Format of the file content—`text` by default +- `opts`: Connection options + +**Returns**: + +File content as string, bytes, or async iterator of bytes + + + +### write\_file + +```python +async def write_file(path: str, + data: Union[str, bytes, IO[bytes]], + uid: Optional[int] = None, + gid: Optional[int] = None, + mode: Optional[int] = None, + force: Optional[bool] = None, + **opts: Unpack[VolumeApiParams]) -> VolumeEntryStat +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file. Data can be a string, bytes, or IO. +- `uid`: User ID of the created file +- `gid`: Group ID of the created file +- `mode`: Mode of the created file +- `force`: Force overwrite of an existing file +- `opts`: Connection options + +**Returns**: + +Information about the written file + + + +### remove + +```python +async def remove(path: str, **opts: Unpack[VolumeApiParams]) -> None +``` + +Remove a file or directory. + +**Arguments**: + +- `path`: Path to the file or directory to remove +- `opts`: Connection options diff --git a/docs/sdk-reference/python-sdk/v2.19.0/volume_sync.mdx b/docs/sdk-reference/python-sdk/v2.19.0/volume_sync.mdx new file mode 100644 index 00000000..408eab69 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.19.0/volume_sync.mdx @@ -0,0 +1,218 @@ +--- +sidebarTitle: "Volume Sync" +--- + + + + + + +## Volume + +```python +class Volume() +``` + +E2B Volume for persistent storage that can be mounted to sandboxes. + + + +### create + +```python +@classmethod +def create(cls, name: str, **opts: Unpack[ApiParams]) -> "Volume" +``` + +Create a new volume. + +**Arguments**: + +- `name`: Name of the volume + +**Returns**: + +A Volume instance for the new volume + + + +### connect + +```python +@classmethod +def connect(cls, volume_id: str, **opts: Unpack[ApiParams]) -> "Volume" +``` + +Connect to an existing volume by ID. + +**Arguments**: + +- `volume_id`: Volume ID + +**Returns**: + +A Volume instance for the existing volume + + + +### destroy + +```python +@staticmethod +def destroy(volume_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Destroy a volume. + +**Arguments**: + +- `volume_id`: Volume ID + + + +### make\_dir + +```python +def make_dir(path: str, + uid: Optional[int] = None, + gid: Optional[int] = None, + mode: Optional[int] = None, + force: Optional[bool] = None, + **opts: Unpack[VolumeApiParams]) -> VolumeEntryStat +``` + +Create a directory. + +**Arguments**: + +- `path`: Path to the directory to create +- `uid`: User ID of the created directory +- `gid`: Group ID of the created directory +- `mode`: Mode of the created directory +- `force`: Create parent directories if they don't exist +- `opts`: Connection options + +**Returns**: + +Information about the created directory + + + +### exists + +```python +def exists(path: str, **opts: Unpack[VolumeApiParams]) -> bool +``` + +Check whether a file or directory exists. + +Uses get_info under the hood. Returns True if the path exists, +False if it does not (404). Other errors are re-raised. + +**Arguments**: + +- `path`: Path to the file or directory +- `opts`: Connection options + +**Returns**: + +True if the path exists, False otherwise + + + +### update\_metadata + +```python +def update_metadata(path: str, + uid: Optional[int] = None, + gid: Optional[int] = None, + mode: Optional[int] = None, + **opts: Unpack[VolumeApiParams]) -> VolumeEntryStat +``` + +Update file or directory metadata. + +**Arguments**: + +- `path`: Path to the file or directory +- `uid`: User ID of the file or directory +- `gid`: Group ID of the file or directory +- `mode`: Mode of the file or directory +- `opts`: Connection options + +**Returns**: + +Updated entry information + + + +### read\_file + +```python +def read_file( + path: str, + format: Literal["text", "bytes", "stream"] = "text", + **opts: Unpack[VolumeApiParams]) -> Union[str, bytes, Iterator[bytes]] +``` + +Read file content. + +You can pass `text`, `bytes`, or `stream` to `format` to change the return type. + +**Arguments**: + +- `path`: Path to the file +- `format`: Format of the file content—`text` by default +- `opts`: Connection options + +**Returns**: + +File content as string, bytes, or iterator of bytes + + + +### write\_file + +```python +def write_file(path: str, + data: Union[str, bytes, IO[bytes]], + uid: Optional[int] = None, + gid: Optional[int] = None, + mode: Optional[int] = None, + force: Optional[bool] = None, + **opts: Unpack[VolumeApiParams]) -> VolumeEntryStat +``` + +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. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file. Data can be a string, bytes, or IO. +- `uid`: User ID of the created file +- `gid`: Group ID of the created file +- `mode`: Mode of the created file +- `force`: Force overwrite of an existing file +- `opts`: Connection options + +**Returns**: + +Information about the written file + + + +### remove + +```python +def remove(path: str, **opts: Unpack[VolumeApiParams]) -> None +``` + +Remove a file or directory. + +**Arguments**: + +- `path`: Path to the file or directory to remove +- `opts`: Connection options