Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
CLI - add config option (#348)
Jakub Novákbaa04d9e07ea
diff --git a/.changeset/loud-donuts-tan.md b/.changeset/loud-donuts-tan.mdnew file mode 100644index 000000000..812948337--- /dev/null+++ b/.changeset/loud-donuts-tan.md@@ -0,0 +1,5 @@+---+"@e2b/cli": patch+---++Add option to specify config filediff --git a/apps/docs/src/app/cli/commands/page.mdx b/apps/docs/src/app/cli/commands/page.mdxindex c966c6e36..82357463d 100644--- a/apps/docs/src/app/cli/commands/page.mdx+++ b/apps/docs/src/app/cli/commands/page.mdx@@ -91,6 +91,9 @@ If there is no `e2b.toml` config a new template will be created.<Option type="-c, --cmd" name="start-command">Specify the command that should be running when a sandbox starts.</Option>+ <Option type="--config" name="e2b-toml">+ Specify the path to the config file. By default, E2B tries to find `e2b.toml` in the root directory.+ </Option><Option type="-n, --name" name="template-name">Specify the name of the sandbox template. You can use the template name to start the sandbox in the SDK. The name must be lowercase and contain only letters, numbers, dashes, and underscores.</Option>@@ -138,6 +141,9 @@ Running `e2b template delete` without specifying a template with the `[template]<Option type="-p, --path" name="path">Change the root directory where the command is executed to the `path` directory.</Option>+ <Option type="--config" name="e2b-toml">+ Specify the path to the config file. By default, E2B tries to find `e2b.toml` in the root directory.+ </Option><Option type="-s, --select">Interactively select sandbox templates you want to delete.</Option>@@ -222,6 +228,9 @@ Running `e2b sandbox spawn` without specifying a template with the `[template]`<Option name="path" type="-p, --path">Change the root directory where the command is executed to `path` directory.</Option>+ <Option type="--config" name="e2b-toml">+ Specify the path to the config file. By default, E2B tries to find `e2b.toml` in the root directory.+ </Option></Options>## `sandbox kill`diff --git a/packages/cli/src/commands/sandbox/spawn.ts b/packages/cli/src/commands/sandbox/spawn.tsindex 35fa899f0..65049218f 100644--- a/packages/cli/src/commands/sandbox/spawn.ts+++ b/packages/cli/src/commands/sandbox/spawn.ts@@ -8,65 +8,77 @@ import { asBold, asFormattedSandboxTemplate } from 'src/utils/format'import { getRoot } from '../../utils/filesystem'import { getConfigPath, loadConfig } from '../../config'import fs from 'fs'-import { pathOption } from '../../options'+import { configOption, pathOption } from '../../options'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]')}`)+ .argument(+ '[template]',+ `spawn and connect to sandbox specified by ${asBold('[template]')}`,+ ).addOption(pathOption)+ .addOption(configOption).alias('sp')- .action(async (template: string | undefined, opts: {- name?: string;- path?: string;- }) => {- try {- const apiKey = ensureAPIKey()- let templateID = template+ .action(+ async (+ template: string | undefined,+ opts: {+ name?: string+ path?: string+ config?: string+ },+ ) => {+ try {+ const apiKey = ensureAPIKey()+ let templateID = template- const root = getRoot(opts.path)- const configPath = getConfigPath(root)+ const root = getRoot(opts.path)+ const configPath = getConfigPath(root, opts.config)- const config = fs.existsSync(configPath)- ? await loadConfig(configPath)- : undefined- const relativeConfigPath = path.relative(root, configPath)+ const config = fs.existsSync(configPath)+ ? await loadConfig(configPath)+ : undefined+ const relativeConfigPath = path.relative(root, configPath)- if (!templateID && config) {- console.log(- `Found sandbox template ${asFormattedSandboxTemplate(- {- templateID: config.template_id,- aliases: config.template_name ? [config.template_name] : undefined,- },- relativeConfigPath,- )}`,- )- templateID = config.template_id- }+ if (!templateID && config) {+ console.log(+ `Found sandbox template ${asFormattedSandboxTemplate(+ {+ templateID: config.template_id,+ aliases: config.template_name+ ? [config.template_name]+ : undefined,+ },+ relativeConfigPath,+ )}`,+ )+ templateID = config.template_id+ }++ if (!templateID) {+ console.error(+ 'You need to specify sandbox template ID or path to sandbox template config',+ )+ process.exit(1)+ }- if (!templateID) {- console.error(- 'You need to specify sandbox template ID or path to sandbox template config',- )+ await connectSandbox({ apiKey, template: { templateID } })+ // We explicitly call exit because the sandbox is keeping the program alive.+ // We also don't want to call sandbox.close because that would disconnect other users from the edit session.+ process.exit(0)+ } catch (err: any) {+ console.error(err)process.exit(1)}-- await connectSandbox({ apiKey, template: { templateID } })- // We explicitly call exit because the sandbox is keeping the program alive.- // We also don't want to call sandbox.close because that would disconnect other users from the edit session.- process.exit(0)- } catch (err: any) {- console.error(err)- process.exit(1)- }- })+ },+ )export async function connectSandbox({apiKey,template,}: {- apiKey: string;- template: Pick<e2b.components['schemas']['Template'], 'templateID'>;+ apiKey: string+ template: Pick<e2b.components['schemas']['Template'], 'templateID'>}) {const sandbox = await e2b.Sandbox.create({apiKey,@@ -78,7 +90,9 @@ export async function connectSandbox({sandbox.terminal,`Terminal connected to sandbox ${asFormattedSandboxTemplate(template,- )}\nwith sandbox URL ${asBold(`${sandbox.getProtocol()}://${sandbox.getHostname()}`)}`,+ )}\nwith sandbox URL ${asBold(+ `${sandbox.getProtocol()}://${sandbox.getHostname()}`,+ )}`,`Disconnecting terminal from sandbox ${asFormattedSandboxTemplate(template,)}`,diff --git a/packages/cli/src/commands/template/build.ts b/packages/cli/src/commands/template/build.tsindex def47c8ce..36e1adfc1 100644--- a/packages/cli/src/commands/template/build.ts+++ b/packages/cli/src/commands/template/build.ts@@ -19,7 +19,7 @@ import {asTypescript,withDelimiter,} from 'src/utils/format'-import { pathOption } from 'src/options'+import { configOption, pathOption } from 'src/options'import {defaultDockerfileName,fallbackDockerfileName,@@ -86,6 +86,7 @@ export const buildCommand = new commander.Command('build')'-c, --cmd <start-command>','specify command that will be executed when the sandbox is started.',)+ .addOption(configOption).option('--cpu-count <cpu-count>','specify the number of CPUs that will be used to run the sandbox. The default value is 2.',@@ -105,6 +106,7 @@ export const buildCommand = new commander.Command('build')dockerfile?: stringname?: stringcmd?: string+ config?: stringcpuCount?: numbermemoryMb?: number},@@ -124,7 +126,9 @@ export const buildCommand = new commander.Command('build')const newName = opts.name?.trim()if (newName && !/[a-z0-9-_]+/.test(newName)) {console.error(- `Name ${asLocal(newName)} is not valid. Name can only contain lowercase letters, numbers, dashes and underscores.`,+ `Name ${asLocal(+ newName,+ )} is not valid. Name can only contain lowercase letters, numbers, dashes and underscores.`,)process.exit(1)}@@ -135,7 +139,7 @@ export const buildCommand = new commander.Command('build')let memoryMB = opts.memoryMbconst root = getRoot(opts.path)- const configPath = getConfigPath(root)+ const configPath = getConfigPath(root, opts.config)const config = fs.existsSync(configPath)? await loadConfig(configPath)@@ -148,7 +152,9 @@ export const buildCommand = new commander.Command('build')`Found sandbox template ${asFormattedSandboxTemplate({templateID: config.template_id,- aliases: config.template_name ? [config.template_name] : undefined,+ aliases: config.template_name+ ? [config.template_name]+ : undefined,},relativeConfigPath,)}`,@@ -174,7 +180,9 @@ export const buildCommand = new commander.Command('build')newName !== config?.template_name) {console.log(- `The sandbox template name will be changed from ${asLocal(config.template_name)} to ${asLocal(newName)}.`,+ `The sandbox template name will be changed from ${asLocal(+ config.template_name,+ )} to ${asLocal(newName)}.`,)}const name = newName || config?.template_name@@ -201,7 +209,9 @@ export const buildCommand = new commander.Command('build')if (opts.memoryMb) {if (opts.memoryMb % 2 !== 0) {console.error(- `The memory in megabytes must be an even number. You provided ${asLocal(opts.memoryMb.toFixed(0))}.`,+ `The memory in megabytes must be an even number. You provided ${asLocal(+ opts.memoryMb.toFixed(0),+ )}.`,)process.exit(1)}@@ -354,7 +364,9 @@ async function waitForBuildFinish(const pythonExample = asPython(`from e2b import Sandbox# Start sandbox-sandbox = Sandbox(template="${aliases?.length ? aliases[0] : template.data.templateID}")+sandbox = Sandbox(template="${+ aliases?.length ? aliases[0] : template.data.templateID+ }")# Interact with sandbox. Learn more here:# https://e2b.dev/docs/sandbox/overview@@ -365,7 +377,9 @@ sandbox.close()`)const typescriptExample = asTypescript(`import { Sandbox } from 'e2b'// Start sandbox-const sandbox = await Sandbox.create({ template: '${aliases?.length ? aliases[0] : template.data.templateID}' })+const sandbox = await Sandbox.create({ template: '${+ aliases?.length ? aliases[0] : template.data.templateID+ }' })// Interact with sandbox. Learn more here:// https://e2b.dev/docs/sandbox/overview@@ -374,7 +388,9 @@ const sandbox = await Sandbox.create({ template: '${aliases?.length ? aliases[0]await sandbox.close()`)const examplesMessage = `You can use E2B Python or JS SDK to spawn sandboxes now.-Find more here - ${asPrimary('https://e2b.dev/docs/guide/custom-sandbox')} in ${asBold('Spawn and control your sandbox')} section.`+Find more here - ${asPrimary(+ 'https://e2b.dev/docs/guide/custom-sandbox',+ )} in ${asBold('Spawn and control your sandbox')} section.`const exampleHeader = boxen.default(examplesMessage, {padding: {@@ -395,7 +411,10 @@ Find more here - ${asPrimary('https://e2b.dev/docs/guide/custom-sandbox')} in ${float: 'left',})- const exampleUsage = `${withDelimiter(pythonExample, 'Python SDK')}\n${withDelimiter(typescriptExample, 'JS SDK', true)}`+ const exampleUsage = `${withDelimiter(+ pythonExample,+ 'Python SDK',+ )}\n${withDelimiter(typescriptExample, 'JS SDK', true)}`console.log(`\n✅ Building sandbox template ${asFormattedSandboxTemplate({@@ -515,7 +534,9 @@ async function requestBuildTemplate(if (error.code === 401) {throw new Error(- `Authentication error: ${res.statusText}, ${error.message ?? 'no message'}`,+ `Authentication error: ${res.statusText}, ${+ error.message ?? 'no message'+ }`,)}@@ -564,7 +585,9 @@ async function triggerBuild(if (error.code === 401) {throw new Error(- `Authentication error: ${res.statusText}, ${error.message ?? 'no message'}`,+ `Authentication error: ${res.statusText}, ${+ error.message ?? 'no message'+ }`,)}diff --git a/packages/cli/src/commands/template/delete.ts b/packages/cli/src/commands/template/delete.tsindex 46e4259a2..0874c9d3d 100644--- a/packages/cli/src/commands/template/delete.ts+++ b/packages/cli/src/commands/template/delete.ts@@ -12,102 +12,156 @@ import {asLocal,asLocalRelative,} from 'src/utils/format'-import { pathOption, selectMultipleOption } from 'src/options'-import { E2BConfig, configName, deleteConfig, getConfigPath, loadConfig } from 'src/config'+import { configOption, pathOption, selectMultipleOption } from 'src/options'+import {+ E2BConfig,+ configName,+ deleteConfig,+ getConfigPath,+ loadConfig,+} from 'src/config'import { getRoot } from 'src/utils/filesystem'import { listSandboxTemplates } from './list'import { getPromptTemplates } from 'src/utils/templatePrompt'import { confirm } from 'src/utils/confirm'const deleteTemplate = e2b.withAccessToken(- e2b.api.path('/templates/{templateID}').method('delete').create()+ e2b.api.path('/templates/{templateID}').method('delete').create(),)export const deleteCommand = new commander.Command('delete').description(`delete sandbox template and ${asLocal(configName)} config`).argument('[template]',- `specify ${asBold(- '[template]',- )} to delete it. If you dont specify ${asBold(+ `specify ${asBold('[template]')} to delete it. If you dont specify ${asBold('[template]',- )} the command will try to delete sandbox template defined by ${asLocal('e2b.toml')}.`,+ )} the command will try to delete sandbox template defined by ${asLocal(+ 'e2b.toml',+ )}.`,).addOption(pathOption)+ .addOption(configOption).addOption(selectMultipleOption).alias('dl').option('-y, --yes', 'skip manual delete confirmation')- .action(async (template, opts: { path?: string, yes?: boolean, select?: boolean }) => {- try {- const accessToken = ensureAccessToken()+ .action(+ async (+ template,+ opts: {+ path?: string+ config?: string+ yes?: boolean+ select?: boolean+ },+ ) => {+ try {+ const accessToken = ensureAccessToken()- const root = getRoot(opts.path)+ const root = getRoot(opts.path)- const templates: (Pick<E2BConfig, 'template_id'> & { configPath?: string })[] = []+ const templates: (Pick<E2BConfig, 'template_id'> & {+ configPath?: string+ })[] = []- if (template) {- templates.push({- template_id: template,- })- } else if (opts.select) {- const allTemplates = await listSandboxTemplates({ accessToken })- const selectedTemplates = await getPromptTemplates(allTemplates, 'Select sandbox templates to delete')- templates.push(...selectedTemplates.map(e => ({ template_id: e.templateID, ...e })))+ if (template) {+ templates.push({+ template_id: template,+ })+ } else if (opts.select) {+ const allTemplates = await listSandboxTemplates({ accessToken })+ const selectedTemplates = await getPromptTemplates(+ allTemplates,+ 'Select sandbox templates to delete',+ )+ templates.push(+ ...selectedTemplates.map((e) => ({+ template_id: e.templateID,+ ...e,+ })),+ )- if (!templates || templates.length === 0) {- console.log('No sandbox templates selected')- return+ if (!templates || templates.length === 0) {+ console.log('No sandbox templates selected')+ return+ }+ } else {+ const configPath = getConfigPath(root)+ const config = fs.existsSync(configPath)+ ? await loadConfig(configPath)+ : undefined++ if (!config) {+ console.log(+ `No ${asLocal(configName)} found in ${asLocalRelative(+ root,+ )}. Specify sandbox template with ${asBold(+ '[template]',+ )} argument or use interactive mode with ${asBold('-s')} flag.`,+ )+ return+ }++ templates.push({+ ...config,+ configPath,+ })}- } else {- const configPath = getConfigPath(root)- const config = fs.existsSync(configPath)- ? await loadConfig(configPath)- : undefined- if (!config) {- console.log(`No ${asLocal(configName)} found in ${asLocalRelative(root)}. Specify sandbox template with ${asBold('[template]')} argument or use interactive mode with ${asBold('-s')} flag.`)+ if (!templates || templates.length === 0) {+ console.log(+ `No sandbox templates selected. Specify sandbox template with ${asBold(+ '[template]',+ )} argument or use interactive mode with ${asBold('-s')} flag.`,+ )return}- templates.push({- ...config,- configPath,- })- }+ console.log(+ chalk.default.red(+ chalk.default.underline('\nSandbox templates to delete'),+ ),+ )+ templates.forEach((e) =>+ console.log(+ asFormattedSandboxTemplate(+ { ...e, templateID: e.template_id },+ e.configPath,+ ),+ ),+ )+ process.stdout.write('\n')- if (!templates || templates.length === 0) {- console.log(`No sandbox templates selected. Specify sandbox template with ${asBold('[template]')} argument or use interactive mode with ${asBold('-s')} flag.`)- return- }+ if (!opts.yes) {+ const confirmed = await confirm(+ `Do you really want to delete ${+ templates.length === 1 ? 'this template' : 'these templates'+ }?`,+ )- console.log(chalk.default.red(chalk.default.underline('\nSandbox templates to delete')))- templates.forEach(e => console.log(asFormattedSandboxTemplate({ ...e, templateID: e.template_id }, e.configPath)))- process.stdout.write('\n')+ if (!confirmed) {+ console.log('Canceled')+ return+ }+ }- if (!opts.yes) {- const confirmed = await confirm(- `Do you really want to delete ${templates.length === 1 ? 'this template' : 'these templates'- }?`,+ await Promise.all(+ templates.map(async (e) => {+ console.log(+ `- Deleting sandbox template ${asFormattedSandboxTemplate(+ { ...e, templateID: e.template_id },+ e.configPath,+ )}`,+ )+ await deleteTemplate(accessToken, { templateID: e.template_id })+ if (e.configPath) {+ await deleteConfig(e.configPath)+ }+ }),)-- if (!confirmed) {- console.log('Canceled')- return- }+ process.stdout.write('\n')+ } catch (err: any) {+ console.error(asFormattedError(err.message))+ process.exit(1)}-- await Promise.all(- templates.map(async e => {- console.log(`- Deleting sandbox template ${asFormattedSandboxTemplate({ ...e, templateID: e.template_id }, e.configPath)}`)- await deleteTemplate(accessToken, { templateID: e.template_id })- if (e.configPath) {- await deleteConfig(e.configPath)- }- }),- )- process.stdout.write('\n')- } catch (err: any) {- console.error(asFormattedError(err.message))- process.exit(1)- }- })+ },+ )diff --git a/packages/cli/src/config/index.ts b/packages/cli/src/config/index.tsindex 5cea8b5b0..25a1dec04 100644--- a/packages/cli/src/config/index.ts+++ b/packages/cli/src/config/index.ts@@ -10,7 +10,9 @@ export const configName = 'e2b.toml'function getConfigHeader(config: E2BConfig) {return `# This is a config for E2B sandbox template.-# You can use 'template_id' (${config.template_id}) ${config.template_name ? `or 'template_name (${config.template_name}) ` : ''}from this config to spawn a sandbox:+# You can use 'template_id' (${config.template_id}) ${+ config.template_name ? `or 'template_name (${config.template_name}) ` : ''+ }from this config to spawn a sandbox:# Python SDK# from e2b import Sandbox@@ -18,7 +20,9 @@ function getConfigHeader(config: E2BConfig) {# JS SDK# import { Sandbox } from 'e2b'-# const sandbox = await Sandbox.create({ template: '${config.template_name || config.template_id}' })+# const sandbox = await Sandbox.create({ template: '${+ config.template_name || config.template_id+ }' })`}@@ -35,8 +39,8 @@ export const configSchema = yup.object({export type E2BConfig = yup.InferType<typeof configSchema>interface Migration {- from: string;- to: string;+ from: string+ to: string}// List of name migrations from old config format to new one.@@ -111,6 +115,8 @@ export async function deleteConfig(configPath: string) {await fsPromise.unlink(configPath)}-export function getConfigPath(root: string) {- return path.join(root, configName)+export function getConfigPath(root: string, configPath?: string) {+ if (configPath && path.isAbsolute(configPath)) return configPath++ return path.join(root, configPath || configName)}diff --git a/packages/cli/src/options.ts b/packages/cli/src/options.tsindex 78965ff65..ef1de2905 100644--- a/packages/cli/src/options.ts+++ b/packages/cli/src/options.ts@@ -9,6 +9,11 @@ export const pathOption = new commander.Option()} directory`,)+export const configOption = new commander.Option(+ '--config <e2b-toml>',+ `specify path to the E2B config toml. By default E2B tries to find ${asBold('./e2b.toml')} in root directory.`,+)+export const selectOption = new commander.Option('-s, --select','select multiple sandbox templates from interactive list',