Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Document process for customizing sandbox compute (#322)
Vasek Mlejnsky710f227b853d
diff --git a/.changeset/slow-starfishes-laugh.md b/.changeset/slow-starfishes-laugh.mdnew file mode 100644index 000000000..9de3e02e1--- /dev/null+++ b/.changeset/slow-starfishes-laugh.md@@ -0,0 +1,5 @@+---+"@e2b/cli": minor+---++Regroup commandsdiff --git a/.changeset/tall-starfishes-unite.md b/.changeset/tall-starfishes-unite.mdnew file mode 100644index 000000000..71ad19342--- /dev/null+++ b/.changeset/tall-starfishes-unite.md@@ -0,0 +1,7 @@+---+"@e2b/cli": patch+"e2b/python-sdk": patch+"e2b": patch+---++Add kill commanddiff --git a/.changeset/ten-insects-learn.md b/.changeset/ten-insects-learn.mdnew file mode 100644index 000000000..26261701d--- /dev/null+++ b/.changeset/ten-insects-learn.md@@ -0,0 +1,5 @@+---+"@e2b/cli": patch+---++Add possibility to build template with custom specsdiff --git a/apps/docs/src/app/cli/commands/page.mdx b/apps/docs/src/app/cli/commands/page.mdxindex cb5e58b33..c966c6e36 100644--- a/apps/docs/src/app/cli/commands/page.mdx+++ b/apps/docs/src/app/cli/commands/page.mdx@@ -6,18 +6,72 @@ Build your sandbox with our CLI. {{ className: 'lead' }}You can use `--help` flag for more information about commands.</Note>-## `build`+---++# Auth++<br/>++## `auth login`++Log in to the CLI. It will save your access token in `~/.e2b` file.++```bash+e2b auth login+```++## `auth logout`++Log out of the CLI. It will remove your access token from `~/.e2b` file.++```+e2b auth logout+```++## `auth info`++Get info about your current user.++```+e2b auth info+```++---++# Templates++<br/>++## `template init`++Creates a basic Dockerfile (`./e2b.Dockerfile`) in current directory.+You can then run `e2b template build` to build sandbox template from this Dockerfile.++```bash+e2b template init+```++#### **Options**++<Options>+ <Option name="path" type="-p, --path">+ Change the root directory where the command is executed to `path` directory.+ </Option>+</Options>+++## `template build`Builds a sandbox template defined by `./e2b.Dockerfile` or `./Dockerfile` from the root directory.By default, the root directory is the current working directory.This command also creates the `e2b.toml` config.```bash-e2b build+e2b template build```<Note>-Running `e2b build` without specifying a template with the `[template]` argument will rebuild template defined by the `e2b.toml` config.+Running `e2b template build` without specifying a template with the `[template]` argument will rebuild template defined by the `e2b.toml` config.If there is no `e2b.toml` config a new template will be created.</Note>@@ -46,30 +100,15 @@ If there is no `e2b.toml` config a new template will be created.<Option type="-d, --dockerfile" name="dockerfile">Specify the path to Dockerfile. By default E2B tries to find `e2b.Dockerfile` or `Dockerfile` in the root directory.</Option>-</Options>-------## `init`--Creates a basic Dockerfile (`./e2b.Dockerfile`) in current directory.-You can then run `e2b build` to build sandbox template from this Dockerfile.--```bash-e2b init-```--#### **Options**--<Options>- <Option name="path" type="-p, --path">- Change the root directory where the command is executed to `path` directory.+ <Option type="--cpu-count" name="cpu-count">+ Specify the number of CPUs that will be used to run the sandbox. The default value is 2.+ </Option>+ <Option type="--memory-mb" name="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.</Option></Options>------## `delete`+## `template delete`Delete the sandbox template specified by the `[template]` argument, `e2b.toml` config in the working directory, or by an interactive selection.By default, the root directory is the current working directory.@@ -77,11 +116,11 @@ By default, the root directory is the current working directory.This command also deletes the `e2b.toml` config.```bash-e2b delete+e2b template delete```<Note>-Running `e2b delete` without specifying a template with the `[template]` argument will delete the template defined by the `e2b.toml` config.+Running `e2b template delete` without specifying a template with the `[template]` argument will delete the template defined by the `e2b.toml` config.</Note>#### **Arguments**@@ -107,39 +146,53 @@ Running `e2b delete` without specifying a template with the `[template]` argumen</Option></Options>-----## `list`+## `template list`List your sandbox templates.```bash-e2b list+e2b template list```----## `login`+# Sandboxes-Log in to the CLI. It will save your access token in `~/.e2b` file.+<br/>++## `sandbox list`++List your spawned sandboxes that are running right now.```bash-e2b login+e2b sandbox list```----+## `sandbox connect`-## `logout`+Connects your terminal to a running sandbox that you spawned via the E2B SDK.+This command is useful if you need to debug a running sandbox.-Log out of the CLI. It will remove your access token from `~/.e2b` file.+This command works similar to the `docker exec -it <container> bash` command in Docker.-```-e2b logout+```bash+e2b sandbox connect <sandboxID>```----+<Note>+You can use `e2b sandbox list` to get a list of running sandboxes and their IDs that can be used with `e2b sandbox connect <sandboxID>` command.+</Note>++#### **Arguments**++<Options>+ <Option type="<sandboxID>">+ Specify the ID of a running sandbox you want to connect to.+ </Option>+</Options>-## `shell`+## `sandbox spawn`Spawns a sandbox and connects your terminal to the sandbox.This command can be used to debug your sandbox template.@@ -147,11 +200,11 @@ This command can be used to debug your sandbox template.This command works similar to the `docker run -it <image> bash` command in Docker.```bash-e2b shell+e2b sandbox spawn```<Note>-Running `e2b shell` without specifying a template with the `[template]` argument will spawn sandbox defined by the `e2b.toml` config.+Running `e2b sandbox spawn` without specifying a template with the `[template]` argument will spawn sandbox defined by the `e2b.toml` config.</Note>#### **Arguments**@@ -171,43 +224,11 @@ Running `e2b shell` without specifying a template with the `[template]` argument</Option></Options>------## `sandboxes`--List your spawned sandboxes that are running right now.--```bash-e2b sandboxes-```-------## `connect`--Connects your terminal to a running sandbox that you spawned via the E2B SDK.-This command is useful if you need to debug a running sandbox.+## `sandbox kill`-This command works similar to the `docker exec -it <container> bash` command in Docker.+Immediately kill a running sandbox.```bash-e2b connect <sandboxID>+e2b sandbox kill <sandboxID>```-<Note>-You can use `e2b sandboxes` to get a list of running sandboxes and their IDs that can be used with `e2b connect <sandboxID>` command.-</Note>--#### **Arguments**--<Options>- <Option type="<sandboxID>">- Specify the ID of a running sandbox you want to connect to.- </Option>-</Options>--### Next steps--1. [Create your first sandbox template](/sandbox/templates/overview)-1. [Check out the official guides](/guides/custom-sandbox)-{/* 1. [Follow the "Hello World" example](/guides/) */}diff --git a/apps/docs/src/app/pricing/page.mdx b/apps/docs/src/app/pricing/page.mdxindex 42f43aea9..a8fa9e19a 100644--- a/apps/docs/src/app/pricing/page.mdx+++ b/apps/docs/src/app/pricing/page.mdx@@ -1,4 +1,5 @@import ManageBilling from '@/components/ManageBilling'+import SandboxSpec from '@/components/SandboxSpec'import Promo from './Promo'import SwitchToHobbyButton from './SwitchToHobbyButton'@@ -8,53 +9,57 @@ import SwitchToProButton from './SwitchToProButton'<ManageBilling />-We charge you based on your real sandbox usage. All new users get one-time free $100 worth of usage in credits. {{ className: 'lead' }}-## Resource pricing-- vCPU: $0.000014 per second (~$0.05 per hour)-- GB RAM: $0.0000045 per second (~$0.018 per hour)+----## Plans-Additionally to the usage costs, you can also select a tier that includes dedicated support, prioritized features, and customizable sandbox machine specs.+# Plans pricing+Additionally to the usage costs, you can also select a tier that includes dedicated support, prioritized features, and higher sandbox limits.++## Hobby tier+**$0/month + usage costs**-### Hobby tier ($0/month + usage costs)<SwitchToHobbyButton/>- One-time $100 of usage in credits- Community support- Up to 1 hour sandbox session length- Up to 20 concurrently running sandboxes-- Hobby sandbox machine specs:- - 2 vCPU- - 512 MB RAM- - 1 GB free disk storage--**Expected costs on the Hobby plan**-- Example of running 1 Hobby sandbox for 1 second = 2 * $0.000014 + 0.5 * $0.0000045 = $0.00003-- Example of running 1 Hobby sandbox for 1 minute = $0.00003 * 60 s = $0.0018-- Example of running 1 Hobby sandbox for 1 hour = $0.00003 * 3,600 s = $0.11-- Example of running 1 Hobby sandbox for 24 hours = $0.00003 * 86,400 s = $2.59--### Pro tier ($150/month + usage costs)++## Pro tier+**$150/month + usage costs**+<SwitchToProButton/>- One-time $100 of usage in credits- Dedicated Slack channel with live Pro support from our team- Prioritized features-- Customize your sandbox machine specs based on your needs ([let us know](/getting-help))+- Customize your [sandbox compute](/sandbox/compute)- Up to 24 hours sandbox session length- Up to 100 concurrently running sandboxes-- Pro sandbox machine specs:- - 4 vCPU- - 4 GB RAM- - 5 GB free disk storage-**Expected costs on the Pro plan**-- Example of running 1 Pro sandbox for 1 second = 4 * $0.000014 + 4 * $0.0000045 = $0.000074-- Example of running 1 Pro sandbox for 1 minute = $0.000074 * 60 s = $0.00444-- Example of running 1 Pro sandbox for 1 hour = $0.000074 * 3,600 s = $0.27-- Example of running 1 Pro sandbox for 24 hours = $0.000074 * 86,400 s = $6.39-- Additional $150 monthly flat fee+If you need any additional features or resources, please [reach out to us](/getting-help) with your use case.+----If you need any additional features or resources, please [reach out to us](/getting-help) with your use case.+# Compute pricing+We charge per second of a running sandbox.+- vCPU: $0.000014 per second (~$0.05 per hour)+- GiB RAM: $0.0000045 per second (~$0.018 per hour)+- GiB storage: Free++<Note>+1 GiB is equal to 1,024 MiB+</Note>++## Sandbox compute+Pro customers can customize the sandbox with **any combination** of the CPU and RAM based on the following tables.++<Note>+To customize your sandbox compute, you need to build your custom sandbox template using the [E2B CLI](/cli/installation).+Run [`e2b template build`](/cli/commands#template-build) and specify the `--cpu-count` and `--memory-mb` options.+</Note>++<SandboxSpec/>++<br/>+[Let us know](/getting-help) if you need more powerful compute.diff --git a/apps/docs/src/app/sandbox/compute/page.mdx b/apps/docs/src/app/sandbox/compute/page.mdxnew file mode 100644index 000000000..872b285b3--- /dev/null+++ b/apps/docs/src/app/sandbox/compute/page.mdx@@ -0,0 +1,17 @@+import SandboxSpec from '@/components/SandboxSpec'++# Sandbox compute+Pro customers can customize the sandbox with **any combination** of the CPU and RAM based on the following tables.++Read a dedicated page to [learn more about pricing](/pricing).++<Note>+To customize your sandbox compute, you need to build your custom sandbox template using the [E2B CLI](/cli/installation).+Run [`e2b template build`](/cli/commands#template-build) and specify the `--cpu-count` and `--memory-mb` options.+</Note>++<SandboxSpec/>++<br/>++[Let us know](/getting-help) if you need more powerful compute.\ No newline at end of filediff --git a/apps/docs/src/app/sandbox/resources/page.mdx b/apps/docs/src/app/sandbox/resources/page.mdxdeleted file mode 100644index 1a446e0d0..000000000--- a/apps/docs/src/app/sandbox/resources/page.mdx+++ /dev/null@@ -1,35 +0,0 @@-# Sandbox resources--Learn more about pricing on the [dedicated page](/pricing).--## Resource pricing-- vCPU: $0.000014 per second (~$0.05 per hour)-- GB RAM: $0.0000045 per second (~$0.018 per hour)--### Hobby tier ($0/month + usage costs)-- One-time $100 of usage in credits-- Community support-- Up to 1 hour sandbox session length-- Up to 20 concurrently running sandboxes-- Hobby sandbox machine specs:- - 2 vCPU- - 512 MB RAM- - 1 GB free disk storage--### Pro tier ($150/month + usage costs)-- One-time $100 of usage in credits-- Dedicated Slack channel with live Pro support from our team-- Prioritized features-- Customize your sandbox machine specs based on your needs ([let us know](/getting-help))-- Up to 24 hours sandbox session length-- Up to 100 concurrently running sandboxes-- Pro sandbox machine specs:- - 4 vCPU- - 4 GB RAM- - 5 GB free disk storage--<Note>-Please [reach out](/getting-help) if you're interested in the Pro tier.-</Note>--If you need more resources, please [reach out to us](/getting-help) with your use case.diff --git a/apps/docs/src/components/Navigation/routes.tsx b/apps/docs/src/components/Navigation/routes.tsxindex 096b83109..be44f56ee 100644--- a/apps/docs/src/components/Navigation/routes.tsx+++ b/apps/docs/src/components/Navigation/routes.tsx@@ -48,7 +48,7 @@ export const routes = [size={20}/>),- title: 'Your Usage',+ title: 'Track usage',href: '/usage',},{@@ -138,8 +138,8 @@ export const routes = [size={20}/>),- title: 'Resources',- href: '/sandbox/resources',+ title: 'Compute',+ href: '/sandbox/compute',},{icon: (diff --git a/apps/docs/src/components/SandboxSpec/CPUSpec.tsx b/apps/docs/src/components/SandboxSpec/CPUSpec.tsxnew file mode 100644index 000000000..1290a4803--- /dev/null+++ b/apps/docs/src/components/SandboxSpec/CPUSpec.tsx@@ -0,0 +1,44 @@+export interface CPUValue {+ value: number+ plan: 'Hobby / Pro' | 'Pro'+}++export interface Props {+ cpuVals: CPUValue[]+ cpuPrice: number+}++function CPUSpec({+ cpuVals,+ cpuPrice,+}: Props) {+ return (+ <div className="w-full flex flex-col gap-2 items-start justify-start">+ <div className="flex items-center justify-between w-full px-2 bg-brand-500/10 rounded">+ <div className="flex items-center justify-start space-between w-full w-[300px]">+ <span className="text-sm flex-1 text-white font-bold">CPUs</span>+ <span className="text-sm text-white font-bold text-left w-[150px]">Plan</span>+ </div>+ <span className="text-sm text-white font-bold">Costs</span>+ </div>++ <div className="flex flex-col items-start justify-start w-full">+ {cpuVals.map((val) => (+ <div+ key={val.value}+ className="flex items-center justify-between w-full p-2 border-b border-white/10"+ >+ <div className="flex items-center justify-start space-between w-full w-[300px]">+ <span className="text-sm flex-1 font-mono text-left">{val.value}</span>+ <span className="text-sm font-mono text-left w-[150px]">{val.plan}</span>+ </div>++ <span className="text-sm font-mono text-right">${(val.value * cpuPrice).toFixed(6)}/s</span>+ </div>+ ))}+ </div>+ </div>+ )+}++export default CPUSpec\ No newline at end of filediff --git a/apps/docs/src/components/SandboxSpec/RAMSpec.tsx b/apps/docs/src/components/SandboxSpec/RAMSpec.tsxnew file mode 100644index 000000000..48dbc7178--- /dev/null+++ b/apps/docs/src/components/SandboxSpec/RAMSpec.tsx@@ -0,0 +1,49 @@+export interface Props {+ ramPrice: number+}++function RAMSpec({+ ramPrice,+}: Props) {+ return (+ <div className="w-full flex flex-col gap-2 items-start justify-start">+ <div className="flex items-center justify-between w-full px-2 bg-brand-500/10 rounded">+ <div className="flex items-center justify-start space-between w-full">+ <span className="text-sm text-white font-bold w-[400px]">RAM</span>+ <span className="text-sm text-white font-bold text-right w-[45px]">Plan</span>+ </div>+ <span className="text-sm text-white font-bold w-full text-center">Costs</span>+ </div>++ <div className="flex items-center justify-start w-full">+ <div className="flex flex-col items-sart justify-start">+ <div+ className="flex items-center justify-between w-full border-b border-white/10"+ >+ {/* Hobby */}+ <div className="flex items-center justify-end py-2 pl-2">+ <span className="text-sm flex-1 font-mono text-left w-[350px]">512 MiB</span>+ <span className="text-sm font-mono text-left w-[95px]">Hobby / Pro</span>+ </div>+ </div>++ {/* Pro */}+ <div+ className="flex items-center justify-start"+ >+ <div className="flex items-center justify-end py-2 pl-2 w-full">+ <span className="text-sm flex-1 font-mono text-left w-[400px]"><b>even</b> value <b>between 128 MiB</b> and <b>8,192 MiB</b></span>+ <span className="text-sm font-mono text-right w-[45px]">Pro</span>+ </div>+ </div>+ </div>++ <div className="flex flex-1 items-center justify-center p-2">+ <span className="text-sm font-mono">${ramPrice}/GiB/s</span>+ </div>+ </div>+ </div>+ )+}++export default RAMSpec\ No newline at end of filediff --git a/apps/docs/src/components/SandboxSpec/StorageSpec.tsx b/apps/docs/src/components/SandboxSpec/StorageSpec.tsxnew file mode 100644index 000000000..55d8dcee8--- /dev/null+++ b/apps/docs/src/components/SandboxSpec/StorageSpec.tsx@@ -0,0 +1,42 @@+export interface StorageValue {+ value: number+ plan: 'Hobby' | 'Pro'+}++export interface Props {+ storageVals: StorageValue[]+}++function CPUSpec({+ storageVals,+}: Props) {+ return (+ <div className="w-full flex flex-col gap-2 items-start justify-start">+ <div className="flex items-center justify-between w-full px-2 bg-brand-500/10 rounded">+ <div className="flex items-center justify-start space-between w-full w-[300px]">+ <span className="text-sm flex-1 text-white font-bold">Storage</span>+ <span className="text-sm text-white font-bold text-left w-[150px]">Plan</span>+ </div>+ <span className="text-sm text-white font-bold">Costs</span>+ </div>++ <div className="flex flex-col items-start justify-start w-full">+ {storageVals.map((val) => (+ <div+ key={val.value}+ className="flex items-center justify-between w-full p-2 border-b border-white/10"+ >+ <div className="flex items-center justify-start space-between w-full w-[300px]">+ <span className="text-sm flex-1 font-mono text-left">{val.value} GiB</span>+ <span className="text-sm font-mono text-left w-[150px]">{val.plan}</span>+ </div>++ <span className="text-sm font-mono text-right">Free</span>+ </div>+ ))}+ </div>+ </div>+ )+}++export default CPUSpec\ No newline at end of filediff --git a/apps/docs/src/components/SandboxSpec/index.tsx b/apps/docs/src/components/SandboxSpec/index.tsxnew file mode 100644index 000000000..1efe53af1--- /dev/null+++ b/apps/docs/src/components/SandboxSpec/index.tsx@@ -0,0 +1,76 @@+import CPUSpec, { CPUValue } from './CPUSpec'+import RAMSpec from './RAMSpec'+import StorageSpec, { StorageValue } from './StorageSpec'+++const cpuVals: CPUValue[] = [+ {+ value: 1,+ plan: 'Pro',+ },+ {+ value: 2,+ plan: 'Hobby / Pro',+ },+ {+ value: 3,+ plan: 'Pro',+ },+ {+ value: 4,+ plan: 'Pro',+ },+ {+ value: 5,+ plan: 'Pro',+ },+ {+ value: 6,+ plan: 'Pro',+ },+ {+ value: 7,+ plan: 'Pro',+ },+ {+ value: 8,+ plan: 'Pro',+ },+]++const cpuPrice = 0.000014+const ramPrice = 0.0000045++const storageValues: StorageValue[] = [+ {+ value: 1,+ plan: 'Hobby'+ },+ {+ value: 5,+ plan: 'Pro'+ },+]++function SandboxSpec() {+ return (+ <div className="w-full flex flex-col gap-6 items-start">+ <div className="w-full flex flex-col gap-4 items-start">+ <h3 className="text-lg font-bold">CPU</h3>+ <CPUSpec cpuVals={cpuVals} cpuPrice={cpuPrice} />+ </div>++ <div className="w-full flex flex-col gap-4 items-start">+ <h3 className="text-lg font-bold">RAM</h3>+ <RAMSpec ramPrice={ramPrice} />+ </div>++ <div className="w-full flex flex-col gap-4 items-start">+ <h3 className="text-lg font-bold">Storage</h3>+ <StorageSpec storageVals={storageValues} />+ </div>+ </div>+ )+}++export default SandboxSpec\ No newline at end of filediff --git a/packages/cli/src/commands/auth/index.ts b/packages/cli/src/commands/auth/index.tsnew file mode 100644index 000000000..56a6cca6a--- /dev/null+++ b/packages/cli/src/commands/auth/index.ts@@ -0,0 +1,10 @@+import * as commander from 'commander'+import { loginCommand } from './login'+import { logoutCommand } from './logout'+import { infoCommand } from './info'+++export const authCommand = new commander.Command('auth').description('Authentication commands')+ .addCommand(loginCommand)+ .addCommand(logoutCommand)+ .addCommand(infoCommand)diff --git a/packages/cli/src/commands/auth/info.ts b/packages/cli/src/commands/auth/info.tsnew file mode 100644index 000000000..0d0593d1d--- /dev/null+++ b/packages/cli/src/commands/auth/info.ts@@ -0,0 +1,23 @@+import * as commander from 'commander'++import { getUserConfig } from 'src/user'+import { asBold, asFormattedError } from 'src/utils/format'++export const infoCommand = new commander.Command('info')+ .description('Get information about the current user')+ .action(async () => {+ let userConfig+ try {+ userConfig = getUserConfig()+ } catch (err) {+ console.error(asFormattedError('Failed to read user config', err))+ }++ if (!userConfig) {+ console.log('Not logged in')+ return+ }++ console.log(`Logged in as ${asBold(userConfig.email)}`)+ process.exit(0)+ })diff --git a/packages/cli/src/commands/login.ts b/packages/cli/src/commands/auth/login.tssimilarity index 100%rename from packages/cli/src/commands/login.tsrename to packages/cli/src/commands/auth/login.tsdiff --git a/packages/cli/src/commands/logout.ts b/packages/cli/src/commands/auth/logout.tssimilarity index 100%rename from packages/cli/src/commands/logout.tsrename to packages/cli/src/commands/auth/logout.tsdiff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.tsindex 8bff97d62..2098cb480 100644--- a/packages/cli/src/commands/index.ts+++ b/packages/cli/src/commands/index.ts@@ -1,27 +1,15 @@import * as commander from 'commander'import { asPrimary } from 'src/utils/format'-import { loginCommand } from './login'-import { logoutCommand } from './logout'-import { buildCommand } from './build'-import { listCommand } from './list'-import { shellCommand } from './shell'-import { initCommand } from './init'-import { deleteCommand } from './delete'-import { runningSandboxesCommand } from './sandboxes'-import { connectCommand } from './connect'+import { templateCommand } from './template'+import { sandboxCommand } from './sandbox'+import { authCommand } from './auth'export const program = new commander.Command().description(`Create sandbox templates from Dockerfiles by running ${asPrimary('e2b build')} then use our SDKs to create sandboxes from these templates.Visit ${asPrimary('E2B docs (https://e2b.dev/docs)')} to learn how to create sandbox templates and start sandboxes.`)- .addCommand(loginCommand)- .addCommand(logoutCommand)- .addCommand(buildCommand)- .addCommand(listCommand)- .addCommand(shellCommand)- .addCommand(initCommand)- .addCommand(deleteCommand)- .addCommand(runningSandboxesCommand)- .addCommand(connectCommand)\ No newline at end of file+ .addCommand(authCommand)+ .addCommand(templateCommand)+ .addCommand(sandboxCommand)diff --git a/packages/cli/src/commands/connect.ts b/packages/cli/src/commands/sandbox/connect.tssimilarity index 97%rename from packages/cli/src/commands/connect.tsrename to packages/cli/src/commands/sandbox/connect.tsindex 742af9d0f..3fefb51c0 100644--- a/packages/cli/src/commands/connect.ts+++ b/packages/cli/src/commands/sandbox/connect.ts@@ -3,7 +3,7 @@ import * as commander from 'commander'import { spawnConnectedTerminal } from 'src/terminal'import { asBold, asPrimary } from 'src/utils/format'-import { ensureAPIKey } from '../api'+import { ensureAPIKey } from '../../api'export const connectCommand = new commander.Command('connect').description('Connect terminal to already running sandbox')diff --git a/packages/cli/src/commands/sandbox/index.ts b/packages/cli/src/commands/sandbox/index.tsnew file mode 100644index 000000000..c44b66570--- /dev/null+++ b/packages/cli/src/commands/sandbox/index.ts@@ -0,0 +1,13 @@+import * as commander from 'commander'++import { connectCommand } from './connect'+import { listCommand } from './list'+import { killCommand } from './kill'+import { spawnCommand } from './spawn'++export const sandboxCommand = new commander.Command('sandbox').description('Work with sandboxes')+ .alias('sbx')+ .addCommand(connectCommand)+ .addCommand(listCommand)+ .addCommand(killCommand)+ .addCommand(spawnCommand)diff --git a/packages/cli/src/commands/sandbox/kill.ts b/packages/cli/src/commands/sandbox/kill.tsnew file mode 100644index 000000000..473e04556--- /dev/null+++ b/packages/cli/src/commands/sandbox/kill.ts@@ -0,0 +1,35 @@+import * as commander from 'commander'++import { ensureAPIKey } from 'src/api'+import { asBold } from 'src/utils/format'+import * as e2b from 'e2b'+++const killSandbox = e2b.withAPIKey(+ e2b.api.path('/sandboxes/{sandboxID}').method('delete').create(),+)+export const killCommand = new commander.Command('kill')+ .description('Kill sandbox')+ .argument('<sandboxID>', `Kill the sandbox specified by ${asBold('<sandboxID>')}`)+ .alias('kl')+ .action(async (sandboxID: string) => {+ try {+ const apiKey = ensureAPIKey()++ if (!sandboxID) {+ console.error('You need to specify sandbox ID')+ process.exit(1)+ }++ await killSandbox( apiKey, { sandboxID } )++ console.log(`Sandbox ${asBold(sandboxID)} has been killed`)+ } catch (err: any) {+ if (err?.status === 404) {+ console.error(`Sandbox ${asBold(sandboxID)} wasn't found`)+ } else {+ console.error(err)+ }+ process.exit(1)+ }+ })diff --git a/packages/cli/src/commands/sandboxes.ts b/packages/cli/src/commands/sandbox/list.tssimilarity index 86%rename from packages/cli/src/commands/sandboxes.tsrename to packages/cli/src/commands/sandbox/list.tsindex d6f8ccf83..76ea848eb 100644--- a/packages/cli/src/commands/sandboxes.ts+++ b/packages/cli/src/commands/sandbox/list.ts@@ -8,9 +8,9 @@ const listRunningSandboxes = e2b.withAPIKey(e2b.api.path('/sandboxes').method('get').create(),)-export const runningSandboxesCommand = new commander.Command('sandboxes')+export const listCommand = new commander.Command('list').description('List all running sandboxes')- .alias('sb')+ .alias('ls').action(async () => {try {const apiKey = ensureAPIKey()@@ -26,10 +26,10 @@ export const runningSandboxesCommand = new commander.Command('sandboxes'){ name: 'templateID', alignment: 'left', title: 'Template ID' },{ name: 'alias', alignment: 'left', title: 'Alias' },{ name: 'startedAt', alignment: 'left', title: 'Started at' },- { name: 'metadata', alignment: 'left', title: 'Metadata'},+ { name: 'metadata', alignment: 'left', title: 'Metadata' },],disabledColumns: ['clientID'],- rows: sandboxes.map((sandbox) => ({ ...sandbox, sandboxID: `${sandbox.sandboxID}-${sandbox.clientID}`,startedAt: new Date(sandbox.startedAt).toLocaleString(), metadata: JSON.stringify(sandbox.metadata) })),+ rows: sandboxes.map((sandbox) => ({ ...sandbox, sandboxID: `${sandbox.sandboxID}-${sandbox.clientID}`, startedAt: new Date(sandbox.startedAt).toLocaleString(), metadata: JSON.stringify(sandbox.metadata) })),colorMap: {orange: '\x1b[38;5;216m',},diff --git a/packages/cli/src/commands/shell.ts b/packages/cli/src/commands/sandbox/spawn.tssimilarity index 87%rename from packages/cli/src/commands/shell.tsrename to packages/cli/src/commands/sandbox/spawn.tsindex ee2d7ac38..13563e76b 100644--- a/packages/cli/src/commands/shell.ts+++ b/packages/cli/src/commands/sandbox/spawn.ts@@ -5,16 +5,16 @@ import * as path from 'path'import { ensureAPIKey } from 'src/api'import { spawnConnectedTerminal } from 'src/terminal'import { asBold, asFormattedSandboxTemplate } from 'src/utils/format'-import { getRoot } from '../utils/filesystem'-import { getConfigPath, loadConfig } from '../config'+import { getRoot } from '../../utils/filesystem'+import { getConfigPath, loadConfig } from '../../config'import fs from 'fs'-import { pathOption } from '../options'+import { pathOption } from '../../options'-export const shellCommand = new commander.Command('shell')- .description('Connect terminal to sandbox')- .argument('[template]', `Connect to sandbox specified by ${asBold('[template]')}`)+export const spawnCommand = new commander.Command('spawn')+ .description('Spawn sandbox and connect terminal to it')+ .argument('[template]', `Spawn and connect to sandbox specified by ${asBold('[template]')}`).addOption(pathOption)- .alias('sh')+ .alias('sp').action(async (template: string | undefined, opts: {name?: string;path?: string;diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/template/build.tssimilarity index 94%rename from packages/cli/src/commands/build.tsrename to packages/cli/src/commands/template/build.tsindex bcadafe36..0e6bf232a 100644--- a/packages/cli/src/commands/build.ts+++ b/packages/cli/src/commands/template/build.ts@@ -23,7 +23,7 @@ import { pathOption } from 'src/options'import { createBlobFromFiles } from 'src/docker/archive'import { defaultDockerfileName, fallbackDockerfileName } from 'src/docker/constants'import { configName, getConfigPath, loadConfig, maxContentSize, saveConfig } from 'src/config'-import { estimateContentLength } from '../utils/form'+import { estimateContentLength } from '../../utils/form'const templateCheckInterval = 1_000 // 1 sec@@ -64,6 +64,14 @@ export const buildCommand = new commander.Command('build')'-c, --cmd <start-command>','Specify command that will be executed when the sandbox is started',)+ .option(+ '--cpu-count <cpu-count>',+ 'Specify the number of CPUs that will be used to run the sandbox. The default value is 2.',+ )+ .option(+ '--memory-mb <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.',+ ).alias('bd').action(async (@@ -73,6 +81,8 @@ export const buildCommand = new commander.Command('build')dockerfile?: string;name?: string;cmd?: string;+ cpuCount?: string;+ memoryMb?: string;},) => {try {@@ -90,6 +100,7 @@ export const buildCommand = new commander.Command('build')let dockerfile = opts.dockerfilelet startCmd = opts.cmd+const root = getRoot(opts.path)const configPath = getConfigPath(root)@@ -177,6 +188,21 @@ export const buildCommand = new commander.Command('build')body.append('startCmd', startCmd)}+ if (opts.cpuCount) {+ body.append('cpuCount', opts.cpuCount)+ }++ if (opts.memoryMb) {+ if (parseInt(opts.memoryMb) % 2 !== 0) {+ console.error(+ `The memory in megabytes must be an even number. You provided ${asLocal(opts.memoryMb)}.`,+ )+ process.exit(1)+ }++ body.append('memoryMB', opts.memoryMb)+ }+const estimatedSize = estimateContentLength(body)if (estimatedSize > maxContentSize) {console.error(diff --git a/packages/cli/src/commands/delete.ts b/packages/cli/src/commands/template/delete.tssimilarity index 100%rename from packages/cli/src/commands/delete.tsrename to packages/cli/src/commands/template/delete.tsdiff --git a/packages/cli/src/commands/template/index.ts b/packages/cli/src/commands/template/index.tsnew file mode 100644index 000000000..1d6db0caf--- /dev/null+++ b/packages/cli/src/commands/template/index.ts@@ -0,0 +1,13 @@+import * as commander from 'commander'++import { buildCommand } from './build'+import { listCommand } from './list'+import { initCommand } from './init'+import { deleteCommand } from './delete'++export const templateCommand = new commander.Command('template').description('Manage sandbox templates')+ .alias('tpl')+ .addCommand(buildCommand)+ .addCommand(listCommand)+ .addCommand(initCommand)+ .addCommand(deleteCommand)diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/template/init.tssimilarity index 100%rename from packages/cli/src/commands/init.tsrename to packages/cli/src/commands/template/init.tsdiff --git a/packages/cli/src/commands/list.ts b/packages/cli/src/commands/template/list.tssimilarity index 97%rename from packages/cli/src/commands/list.tsrename to packages/cli/src/commands/template/list.tsindex 2b3c20e9a..b8d83f64f 100644--- a/packages/cli/src/commands/list.ts+++ b/packages/cli/src/commands/template/list.ts@@ -3,7 +3,7 @@ import * as commander from 'commander'import * as e2b from 'e2b'import { ensureAccessToken } from 'src/api'-import { listAliases } from '../utils/format'+import { listAliases } from '../../utils/format'import { sortTemplatesAliases } from 'src/utils/templateSort'const listTemplates = e2b.withAccessToken(diff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.tsindex 8bb34c1f5..9d1597098 100644--- a/packages/js-sdk/src/api/schema.gen.ts+++ b/packages/js-sdk/src/api/schema.gen.ts@@ -49,6 +49,23 @@ export interface paths {};};};+ "/sandboxes/{sandboxID}": {+ /** Kill a sandbox */+ delete: {+ parameters: {+ path: {+ sandboxID: components["parameters"]["sandboxID"];+ };+ };+ responses: {+ /** The sandbox was killed successfully */+ 204: never;+ 401: components["responses"]["401"];+ 404: components["responses"]["404"];+ 500: components["responses"]["500"];+ };+ };+ };"/sandboxes/{sandboxID}/refreshes": {/** Refresh the sandbox extending its time to live */post: {@@ -113,6 +130,10 @@ export interface paths {dockerfile: string;/** @description Start command to execute in the template after the build */startCmd?: string;+ /** @description CPU cores for the template */+ cpuCount?: string;+ /** @description Memory limit for the template in MB */+ memoryMB?: string;};};};@@ -150,6 +171,10 @@ export interface paths {dockerfile: string;/** @description Start command to execute in the template after the build */startCmd?: string;+ /** @description CPU cores for the template */+ cpuCount?: string;+ /** @description Memory limit for the template in MB */+ memoryMB?: string;};};};diff --git a/packages/js-sdk/src/sandbox/sandboxConnection.ts b/packages/js-sdk/src/sandbox/sandboxConnection.tsindex 4ae842ea8..7b6d91c95 100644--- a/packages/js-sdk/src/sandbox/sandboxConnection.ts+++ b/packages/js-sdk/src/sandbox/sandboxConnection.ts@@ -84,6 +84,9 @@ const listSandboxes = withAPIKey(const createSandbox = withAPIKey(api.path('/sandboxes').method('post').create(),)+const killSandbox = withAPIKey(+ api.path('/sandboxes/{sandboxID}').method('delete').create(),+)const refreshSandbox = withAPIKey(api.path('/sandboxes/{sandboxID}/refreshes').method('post').create(),)@@ -185,6 +188,33 @@ export class SandboxConnection {}}+ /**+ * List all running sandboxes+ * @param sandboxID ID of the sandbox to kill+ * @param apiKey API key to use for authentication. If not provided, the `E2B_API_KEY` environment variable will be used.+ */+ static async kill(sandboxID: string, apiKey?: string): Promise<void> {+ apiKey = getApiKey(apiKey)+ try {+ await killSandbox(apiKey, {sandboxID})+ } catch (e) {+ if (e instanceof killSandbox.Error) {+ const error = e.getActualType()+ if (error.status === 401) {+ throw new Error(+ `Error killing sandbox (${sandboxID}) - (${error.status}) unauthenticated: ${error.data.message}`,+ )+ }+ if (error.status === 500) {+ throw new Error(+ `Error killing sandbox (${sandboxID}) - (${error.status}) server error: ${error.data.message}`,+ )+ }+ }+ throw e+ }+ }+/*** Keep the sandbox alive for the specified duration.*@@ -537,11 +567,10 @@ export class SandboxConnection {await wait(SANDBOX_REFRESH_PERIOD)try {- this.logger.debug?.(`Refreshed sandbox "${sandboxID}"`)-await refreshSandbox(this.apiKey, {sandboxID, duration: 0,})+ this.logger.debug?.(`Refreshed sandbox "${sandboxID}"`)} catch (e) {if (e instanceof refreshSandbox.Error) {const error = e.getActualType()diff --git a/packages/js-sdk/test/killSandbox.test.mjs b/packages/js-sdk/test/killSandbox.test.mjsnew file mode 100644index 000000000..6e58d5b65--- /dev/null+++ b/packages/js-sdk/test/killSandbox.test.mjs@@ -0,0 +1,10 @@+import { expect, test } from 'vitest'+import { Sandbox } from '../src'+import wait from '../src/utils/wait'++test('kill running sandbox', async () => {+ await expect(async () => {+ const sandbox = await Sandbox.create()+ await Sandbox.kill(sandbox.id)+ }).rejects.toThrowError("Not Found")+})diff --git a/packages/python-sdk/e2b/api/v1/client/api/sandboxes_api.py b/packages/python-sdk/e2b/api/v1/client/api/sandboxes_api.pyindex 68482c030..93c74a0ca 100644--- a/packages/python-sdk/e2b/api/v1/client/api/sandboxes_api.py+++ b/packages/python-sdk/e2b/api/v1/client/api/sandboxes_api.py@@ -339,6 +339,150 @@ class SandboxesApi:_request_auth=_params.get("_request_auth"),)+ @validate_arguments+ def sandboxes_sandbox_id_delete(+ self, sandbox_id: StrictStr, **kwargs+ ) -> None: # noqa: E501+ """sandboxes_sandbox_id_delete # noqa: E501++ Kill a sandbox # noqa: E501+ This method makes a synchronous HTTP request by default. To make an+ asynchronous HTTP request, please pass async_req=True++ >>> thread = api.sandboxes_sandbox_id_delete(sandbox_id, async_req=True)+ >>> result = thread.get()++ :param sandbox_id: (required)+ :type sandbox_id: str+ :param async_req: Whether to execute the request asynchronously.+ :type async_req: bool, optional+ :param _request_timeout: timeout setting for this request.+ If one number provided, it will be total request+ timeout. It can also be a pair (tuple) of+ (connection, read) timeouts.+ :return: Returns the result object.+ If the method is called asynchronously,+ returns the request thread.+ :rtype: None+ """+ kwargs["_return_http_data_only"] = True+ if "_preload_content" in kwargs:+ message = "Error! Please call the sandboxes_sandbox_id_delete_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501+ raise ValueError(message)+ return self.sandboxes_sandbox_id_delete_with_http_info(+ sandbox_id, **kwargs+ ) # noqa: E501++ @validate_arguments+ def sandboxes_sandbox_id_delete_with_http_info(+ self, sandbox_id: StrictStr, **kwargs+ ) -> ApiResponse: # noqa: E501+ """sandboxes_sandbox_id_delete # noqa: E501++ Kill a sandbox # noqa: E501+ This method makes a synchronous HTTP request by default. To make an+ asynchronous HTTP request, please pass async_req=True++ >>> thread = api.sandboxes_sandbox_id_delete_with_http_info(sandbox_id, async_req=True)+ >>> result = thread.get()++ :param sandbox_id: (required)+ :type sandbox_id: str+ :param async_req: Whether to execute the request asynchronously.+ :type async_req: bool, optional+ :param _preload_content: if False, the ApiResponse.data will+ be set to none and raw_data will store the+ HTTP response body without reading/decoding.+ Default is True.+ :type _preload_content: bool, optional+ :param _return_http_data_only: response data instead of ApiResponse+ object with status code, headers, etc+ :type _return_http_data_only: bool, optional+ :param _request_timeout: timeout setting for this request. If one+ number provided, it will be total request+ timeout. It can also be a pair (tuple) of+ (connection, read) timeouts.+ :param _request_auth: set to override the auth_settings for an a single+ request; this effectively ignores the authentication+ in the spec for a single request.+ :type _request_auth: dict, optional+ :type _content_type: string, optional: force content-type for the request+ :return: Returns the result object.+ If the method is called asynchronously,+ returns the request thread.+ :rtype: None+ """++ _params = locals()++ _all_params = ["sandbox_id"]+ _all_params.extend(+ [+ "async_req",+ "_return_http_data_only",+ "_preload_content",+ "_request_timeout",+ "_request_auth",+ "_content_type",+ "_headers",+ ]+ )++ # validate the arguments+ for _key, _val in _params["kwargs"].items():+ if _key not in _all_params:+ raise ApiTypeError(+ "Got an unexpected keyword argument '%s'"+ " to method sandboxes_sandbox_id_delete" % _key+ )+ _params[_key] = _val+ del _params["kwargs"]++ _collection_formats = {}++ # process the path parameters+ _path_params = {}+ if _params["sandbox_id"] is not None:+ _path_params["sandboxID"] = _params["sandbox_id"]++ # process the query parameters+ _query_params = []+ # process the header parameters+ _header_params = dict(_params.get("_headers", {}))+ # process the form parameters+ _form_params = []+ _files = {}+ # process the body parameter+ _body_params = None+ # set the HTTP header `Accept`+ _header_params["Accept"] = self.api_client.select_header_accept(+ ["application/json"]+ ) # noqa: E501++ # authentication setting+ _auth_settings = ["ApiKeyAuth"] # noqa: E501++ _response_types_map = {}++ return self.api_client.call_api(+ "/sandboxes/{sandboxID}",+ "DELETE",+ _path_params,+ _query_params,+ _header_params,+ body=_body_params,+ post_params=_form_params,+ files=_files,+ response_types_map=_response_types_map,+ auth_settings=_auth_settings,+ async_req=_params.get("async_req"),+ _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501+ _preload_content=_params.get("_preload_content", True),+ _request_timeout=_params.get("_request_timeout"),+ collection_formats=_collection_formats,+ _request_auth=_params.get("_request_auth"),+ )+@validate_argumentsdef sandboxes_sandbox_id_refreshes_post(self,diff --git a/packages/python-sdk/e2b/api/v1/client_README.md b/packages/python-sdk/e2b/api/v1/client_README.mdindex 0aca874e5..137e0294c 100644--- a/packages/python-sdk/e2b/api/v1/client_README.md+++ b/packages/python-sdk/e2b/api/v1/client_README.md@@ -74,6 +74,7 @@ Class | Method | HTTP request | Description------------ | ------------- | ------------- | -------------*SandboxesApi* | [**sandboxes_get**](e2b/api/v1/client/docs/SandboxesApi.md#sandboxes_get) | **GET** /sandboxes |*SandboxesApi* | [**sandboxes_post**](e2b/api/v1/client/docs/SandboxesApi.md#sandboxes_post) | **POST** /sandboxes |+*SandboxesApi* | [**sandboxes_sandbox_id_delete**](e2b/api/v1/client/docs/SandboxesApi.md#sandboxes_sandbox_id_delete) | **DELETE** /sandboxes/{sandboxID} |*SandboxesApi* | [**sandboxes_sandbox_id_refreshes_post**](e2b/api/v1/client/docs/SandboxesApi.md#sandboxes_sandbox_id_refreshes_post) | **POST** /sandboxes/{sandboxID}/refreshes |diff --git a/packages/python-sdk/e2b/api/v2/client/api/sandboxes_api.py b/packages/python-sdk/e2b/api/v2/client/api/sandboxes_api.pyindex 5bb1f690e..2b2599faa 100644--- a/packages/python-sdk/e2b/api/v2/client/api/sandboxes_api.py+++ b/packages/python-sdk/e2b/api/v2/client/api/sandboxes_api.py@@ -540,6 +540,238 @@ class SandboxesApi:_request_auth=_request_auth,)+ @validate_call+ def sandboxes_sandbox_id_delete(+ self,+ sandbox_id: StrictStr,+ _request_timeout: Union[+ None,+ Annotated[StrictFloat, Field(gt=0)],+ Tuple[+ Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]+ ],+ ] = None,+ _request_auth: Optional[Dict[StrictStr, Any]] = None,+ _content_type: Optional[StrictStr] = None,+ _headers: Optional[Dict[StrictStr, Any]] = None,+ _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,+ ) -> None:+ """sandboxes_sandbox_id_delete++ Kill a sandbox++ :param sandbox_id: (required)+ :type sandbox_id: str+ :param _request_timeout: timeout setting for this request. If one+ number provided, it will be total request+ timeout. It can also be a pair (tuple) of+ (connection, read) timeouts.+ :type _request_timeout: int, tuple(int, int), optional+ :param _request_auth: set to override the auth_settings for an a single+ request; this effectively ignores the+ authentication in the spec for a single request.+ :type _request_auth: dict, optional+ :param _content_type: force content-type for the request.+ :type _content_type: str, Optional+ :param _headers: set to override the headers for a single+ request; this effectively ignores the headers+ in the spec for a single request.+ :type _headers: dict, optional+ :param _host_index: set to override the host_index for a single+ request; this effectively ignores the host_index+ in the spec for a single request.+ :type _host_index: int, optional+ :return: Returns the result object.+ """ # noqa: E501++ _param = self._sandboxes_sandbox_id_delete_serialize(+ sandbox_id=sandbox_id,+ _request_auth=_request_auth,+ _content_type=_content_type,+ _headers=_headers,+ _host_index=_host_index,+ )++ _response_types_map: Dict[str, Optional[str]] = {}+ response_data = self.api_client.call_api(+ *_param, _request_timeout=_request_timeout+ )+ response_data.read()+ return self.api_client.response_deserialize(+ response_data=response_data,+ response_types_map=_response_types_map,+ ).data++ @validate_call+ def sandboxes_sandbox_id_delete_with_http_info(+ self,+ sandbox_id: StrictStr,+ _request_timeout: Union[+ None,+ Annotated[StrictFloat, Field(gt=0)],+ Tuple[+ Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]+ ],+ ] = None,+ _request_auth: Optional[Dict[StrictStr, Any]] = None,+ _content_type: Optional[StrictStr] = None,+ _headers: Optional[Dict[StrictStr, Any]] = None,+ _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,+ ) -> ApiResponse[None]:+ """sandboxes_sandbox_id_delete++ Kill a sandbox++ :param sandbox_id: (required)+ :type sandbox_id: str+ :param _request_timeout: timeout setting for this request. If one+ number provided, it will be total request+ timeout. It can also be a pair (tuple) of+ (connection, read) timeouts.+ :type _request_timeout: int, tuple(int, int), optional+ :param _request_auth: set to override the auth_settings for an a single+ request; this effectively ignores the+ authentication in the spec for a single request.+ :type _request_auth: dict, optional+ :param _content_type: force content-type for the request.+ :type _content_type: str, Optional+ :param _headers: set to override the headers for a single+ request; this effectively ignores the headers+ in the spec for a single request.+ :type _headers: dict, optional+ :param _host_index: set to override the host_index for a single+ request; this effectively ignores the host_index+ in the spec for a single request.+ :type _host_index: int, optional+ :return: Returns the result object.+ """ # noqa: E501++ _param = self._sandboxes_sandbox_id_delete_serialize(+ sandbox_id=sandbox_id,+ _request_auth=_request_auth,+ _content_type=_content_type,+ _headers=_headers,+ _host_index=_host_index,+ )++ _response_types_map: Dict[str, Optional[str]] = {}+ response_data = self.api_client.call_api(+ *_param, _request_timeout=_request_timeout+ )+ response_data.read()+ return self.api_client.response_deserialize(+ response_data=response_data,+ response_types_map=_response_types_map,+ )++ @validate_call+ def sandboxes_sandbox_id_delete_without_preload_content(+ self,+ sandbox_id: StrictStr,+ _request_timeout: Union[+ None,+ Annotated[StrictFloat, Field(gt=0)],+ Tuple[+ Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]+ ],+ ] = None,+ _request_auth: Optional[Dict[StrictStr, Any]] = None,+ _content_type: Optional[StrictStr] = None,+ _headers: Optional[Dict[StrictStr, Any]] = None,+ _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,+ ) -> RESTResponseType:+ """sandboxes_sandbox_id_delete++ Kill a sandbox++ :param sandbox_id: (required)+ :type sandbox_id: str+ :param _request_timeout: timeout setting for this request. If one+ number provided, it will be total request+ timeout. It can also be a pair (tuple) of+ (connection, read) timeouts.+ :type _request_timeout: int, tuple(int, int), optional+ :param _request_auth: set to override the auth_settings for an a single+ request; this effectively ignores the+ authentication in the spec for a single request.+ :type _request_auth: dict, optional+ :param _content_type: force content-type for the request.+ :type _content_type: str, Optional+ :param _headers: set to override the headers for a single+ request; this effectively ignores the headers+ in the spec for a single request.+ :type _headers: dict, optional+ :param _host_index: set to override the host_index for a single+ request; this effectively ignores the host_index+ in the spec for a single request.+ :type _host_index: int, optional+ :return: Returns the result object.+ """ # noqa: E501++ _param = self._sandboxes_sandbox_id_delete_serialize(+ sandbox_id=sandbox_id,+ _request_auth=_request_auth,+ _content_type=_content_type,+ _headers=_headers,+ _host_index=_host_index,+ )++ _response_types_map: Dict[str, Optional[str]] = {}+ response_data = self.api_client.call_api(+ *_param, _request_timeout=_request_timeout+ )+ return response_data.response++ def _sandboxes_sandbox_id_delete_serialize(+ self,+ sandbox_id,+ _request_auth,+ _content_type,+ _headers,+ _host_index,+ ) -> Tuple:+ _host = None++ _collection_formats: Dict[str, str] = {}++ _path_params: Dict[str, str] = {}+ _query_params: List[Tuple[str, str]] = []+ _header_params: Dict[str, Optional[str]] = _headers or {}+ _form_params: List[Tuple[str, str]] = []+ _files: Dict[str, str] = {}+ _body_params: Optional[bytes] = None++ # process the path parameters+ if sandbox_id is not None:+ _path_params["sandboxID"] = sandbox_id+ # process the query parameters+ # process the header parameters+ # process the form parameters+ # process the body parameter++ # set the HTTP header `Accept`+ _header_params["Accept"] = self.api_client.select_header_accept(+ ["application/json"]+ )++ # authentication setting+ _auth_settings: List[str] = ["ApiKeyAuth"]++ return self.api_client.param_serialize(+ method="DELETE",+ resource_path="/sandboxes/{sandboxID}",+ path_params=_path_params,+ query_params=_query_params,+ header_params=_header_params,+ body=_body_params,+ post_params=_form_params,+ files=_files,+ auth_settings=_auth_settings,+ collection_formats=_collection_formats,+ _host=_host,+ _request_auth=_request_auth,+ )+@validate_calldef sandboxes_sandbox_id_refreshes_post(self,diff --git a/packages/python-sdk/e2b/api/v2/client_README.md b/packages/python-sdk/e2b/api/v2/client_README.mdindex be411f76b..93e0e1659 100644--- a/packages/python-sdk/e2b/api/v2/client_README.md+++ b/packages/python-sdk/e2b/api/v2/client_README.md@@ -73,6 +73,7 @@ Class | Method | HTTP request | Description------------ | ------------- | ------------- | -------------*SandboxesApi* | [**sandboxes_get**](e2b/api/v2/client/docs/SandboxesApi.md#sandboxes_get) | **GET** /sandboxes |*SandboxesApi* | [**sandboxes_post**](e2b/api/v2/client/docs/SandboxesApi.md#sandboxes_post) | **POST** /sandboxes |+*SandboxesApi* | [**sandboxes_sandbox_id_delete**](e2b/api/v2/client/docs/SandboxesApi.md#sandboxes_sandbox_id_delete) | **DELETE** /sandboxes/{sandboxID} |*SandboxesApi* | [**sandboxes_sandbox_id_refreshes_post**](e2b/api/v2/client/docs/SandboxesApi.md#sandboxes_sandbox_id_refreshes_post) | **POST** /sandboxes/{sandboxID}/refreshes |diff --git a/packages/python-sdk/e2b/sandbox/process.py b/packages/python-sdk/e2b/sandbox/process.pyindex ab63bf2f0..45962d494 100644--- a/packages/python-sdk/e2b/sandbox/process.py+++ b/packages/python-sdk/e2b/sandbox/process.py@@ -2,6 +2,7 @@ import loggingimport reimport inspectimport threading+import timefrom concurrent.futures import Futurefrom typing import (Any,@@ -169,7 +170,13 @@ class Process::param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out. If set to None, the method will continue to wait until it completes, regardless of time"""- return self._finished.result(timeout)+ start_time = time.time()+ while timeout is None or time.time() - start_time < timeout:+ if self._finished.done():+ return self._finished.result()+ time.sleep(0.1)+ if not self._sandbox.is_open:+ breakdef send_stdin(self, data: str, timeout: Optional[float] = TIMEOUT) -> None:"""diff --git a/packages/python-sdk/e2b/sandbox/sandbox_connection.py b/packages/python-sdk/e2b/sandbox/sandbox_connection.pyindex cf64086a4..7482b7598 100644--- a/packages/python-sdk/e2b/sandbox/sandbox_connection.py+++ b/packages/python-sdk/e2b/sandbox/sandbox_connection.py@@ -291,7 +291,6 @@ class SandboxConnection:def _start_refreshing(self):threading.Thread(target=self._refresh,- args=(self._sandbox.sandbox_id,),daemon=True,name="e2b-sandbox-refresh",).start()@@ -409,7 +408,7 @@ class SandboxConnection:if id == data.params["subscription"]:sub.handler(data.params["result"])- def _refresh(self, sandbox_id: str):+ def _refresh(self):if not self._sandbox:logger.info("No sandbox to refresh. Sandbox was not created")return@@ -432,7 +431,7 @@ class SandboxConnection:sleep(SANDBOX_REFRESH_PERIOD)try:api.sandboxes_sandbox_id_refreshes_post(- sandbox_id,+ self._sandbox.sandbox_id,client.SandboxesSandboxIDRefreshesPostRequest(duration=0),)logger.debug(f"Refreshed sandbox {self.id}")@@ -481,3 +480,18 @@ class SandboxConnection:)for sandbox in client.SandboxesApi(api_client).sandboxes_get()]++ @staticmethod+ def kill(sandbox_id: str, api_key: Optional[str] = None) -> None:+ """+ Kill the running sandbox specified by the sandbox ID.++ :param sandbox_id: ID of the sandbox to kill.+ :param api_key: API key to use for authentication.+ If not provided, the `E2B_API_KEY` environment variable will be used.+ """+ api_key = get_api_key(api_key)+ with E2BApiClient(api_key=api_key) as api_client:+ return client.SandboxesApi(api_client).sandboxes_sandbox_id_delete(+ sandbox_id=sandbox_id+ )diff --git a/packages/python-sdk/e2b/sandbox/sandbox_rpc.py b/packages/python-sdk/e2b/sandbox/sandbox_rpc.pyindex 650d5c495..207df64d8 100644--- a/packages/python-sdk/e2b/sandbox/sandbox_rpc.py+++ b/packages/python-sdk/e2b/sandbox/sandbox_rpc.py@@ -4,6 +4,7 @@ import asyncioimport jsonimport loggingimport threading+import timefrom concurrent.futures import ThreadPoolExecutor, TimeoutErrorfrom queue import Queue@@ -64,6 +65,7 @@ class SandboxRpc(BaseModel):_queue_out: Queue = PrivateAttr(default_factory=Queue)_process_cleanup: List[Callable[[], Any]] = PrivateAttr(default_factory=list)_websocket_task: Optional[threading.Thread] = PrivateAttr(default=None)+ _closed: bool = PrivateAttr(default=False)def process_messages(self):while True:@@ -81,38 +83,34 @@ class SandboxRpc(BaseModel):target=self.process_messages, daemon=True, name="e2b-process-messages").start()- executor = ThreadPoolExecutor(thread_name_prefix="e2b-websocket")- loop = asyncio.new_event_loop()-- # Keep the websocket running as non daemon thread, so it can close websocket properly- websocket_task = executor.submit(- run_async_func_in_loop,- loop,- WebSocket(+ threading.Thread(+ target=WebSocket(url=self.url,queue_in=self._queue_in,queue_out=self._queue_out,started=started,stopped=stopped,- ).run(),- )-- self._process_cleanup.append(websocket_task.cancel)- self._process_cleanup.append(lambda: shutdown_executor(executor))+ ).run,+ daemon=True,+ name="e2b-websocket",+ ).start()logger.info("WebSocket waiting to start")try:- signaled = started.wait(timeout=timeout)- if not signaled:+ start_time = time.time()+ while (+ not started.is_set()+ and time.time() - start_time < timeout+ and not self._closed+ ):+ time.sleep(0.1)++ if not started.is_set():logger.error("WebSocket failed to start")raise TimeoutException("WebSocket failed to start")except BaseException as e:self.close()-- if loop.is_running():- loop.stop()-raise SandboxException(f"WebSocket failed to start: {e}") from elogger.info("WebSocket started")@@ -183,6 +181,8 @@ class SandboxRpc(BaseModel):self.on_message(message)def _close(self):+ self._closed = True+for cancel in self._process_cleanup:cancel()diff --git a/packages/python-sdk/e2b/sandbox/websocket_client.py b/packages/python-sdk/e2b/sandbox/websocket_client.pyindex 37d2fea6a..65ead1136 100644--- a/packages/python-sdk/e2b/sandbox/websocket_client.py+++ b/packages/python-sdk/e2b/sandbox/websocket_client.py@@ -31,7 +31,13 @@ class WebSocket:self._queue_in = queue_inself._queue_out = queue_out- async def run(self):+ def run(self):+ loop = asyncio.new_event_loop()+ asyncio.set_event_loop(loop)++ loop.run_until_complete(self.async_run())++ async def async_run(self):await self._connect()await self.close()diff --git a/packages/python-sdk/tests/test_kill_sandbox.py b/packages/python-sdk/tests/test_kill_sandbox.pynew file mode 100644index 000000000..88f5efe89--- /dev/null+++ b/packages/python-sdk/tests/test_kill_sandbox.py@@ -0,0 +1,11 @@+import pytest++from e2b import Sandbox+from e2b.api import exceptions+++def test_kill_sandbox():+ s = Sandbox()+ with pytest.raises(exceptions.ApiException):+ Sandbox.kill(s.id)+ s._refresh()diff --git a/spec/openapi.yml b/spec/openapi.ymlindex b72a9cf26..2bd1b019f 100644--- a/spec/openapi.yml+++ b/spec/openapi.yml@@ -36,7 +36,7 @@ components:required: trueschema:type: string-# ------ Deprecated --------+ # ------ Deprecated --------envID:name: envIDin: path@@ -49,7 +49,7 @@ components:required: trueschema:type: string-# ----------------------+ # ----------------------responses:400:@@ -199,7 +199,7 @@ components:message:type: stringdescription: Error-# ------ Deprecated --------+ # ------ Deprecated --------Environment:required:- envID@@ -306,7 +306,7 @@ components:tags:- name: templates- name: sandboxes-# ------ Deprecated --------+ # ------ Deprecated --------- name: instances- name: envs# ---------------------------@@ -326,7 +326,7 @@ paths:description: List all running sandboxestags: [sandboxes]security:- - ApiKeyAuth: [ ]+ - ApiKeyAuth: []responses:200:description: Successfully returned all running sandboxes@@ -368,6 +368,24 @@ paths:500:$ref: "#/components/responses/500"+ /sandboxes/{sandboxID}:+ delete:+ description: Kill a sandbox+ tags: [sandboxes]+ security:+ - ApiKeyAuth: []+ parameters:+ - $ref: "#/components/parameters/sandboxID"+ responses:+ 204:+ description: The sandbox was killed successfully+ 404:+ $ref: "#/components/responses/404"+ 401:+ $ref: "#/components/responses/401"+ 500:+ $ref: "#/components/responses/500"+/sandboxes/{sandboxID}/refreshes:post:description: Refresh the sandbox extending its time to live@@ -444,6 +462,12 @@ paths:startCmd:description: Start command to execute in the template after the buildtype: string+ cpuCount:+ description: CPU cores for the template+ type: string # form data does not support integer+ memoryMB:+ description: Memory limit for the template in MB+ type: string # form data does not support integerencoding:buildContext:contentType: application/octet-stream@@ -491,6 +515,12 @@ paths:startCmd:description: Start command to execute in the template after the buildtype: string+ cpuCount:+ description: CPU cores for the template+ type: string # form data does not support integer+ memoryMB:+ description: Memory limit for the template in MB+ type: string # form data does not support integerencoding:buildContext:contentType: application/octet-stream@@ -774,7 +804,7 @@ paths:description: List all running instancestags: [instances]security:- - ApiKeyAuth: [ ]+ - ApiKeyAuth: []responses:200:description: Successfully returned all running instances