Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
feat(cli): add config override flags to template migrate (#1494)
Mish Ushakov2869febdeea1
diff --git a/.changeset/migrate-name-override.md b/.changeset/migrate-name-override.mdnew file mode 100644index 000000000..59c2711e2--- /dev/null+++ b/.changeset/migrate-name-override.md@@ -0,0 +1,5 @@+---+"@e2b/cli": patch+---++Add override options to `e2b template migrate`: `--name`/`-n` to override the generated template name, `--cmd`/`-c` for the start command, `--ready-cmd` for the ready command, and `--cpu-count` / `--memory-mb` for sandbox resources. Each falls back to the value from the config file (`e2b.toml`) when not provided. `--cpu-count` and `--memory-mb` (on both `migrate` and `create`) now reject non-numeric values at parse time instead of silently becoming `NaN`. Template name validation is now shared across `init`, `migrate` and `create` and matches the server-side rule: names are trimmed and lowercased, must contain only letters, numbers, dashes and underscores, and are capped at 128 characters. `init`/`migrate` no longer wrongly reject names with leading/trailing dashes or underscores.diff --git a/packages/cli/src/commands/template/create.ts b/packages/cli/src/commands/template/create.tsindex e848c89f1..a512f858e 100644--- a/packages/cli/src/commands/template/create.ts+++ b/packages/cli/src/commands/template/create.ts@@ -6,7 +6,8 @@ import {defaultDockerfileName,fallbackDockerfileName,} from 'src/docker/constants'-import { pathOption } from 'src/options'+import { parsePositiveInt, pathOption } from 'src/options'+import { validateTemplateName } from 'src/utils/templateName'import { getRoot } from 'src/utils/filesystem'import {asFormattedSandboxTemplate,@@ -45,12 +46,12 @@ export const createCommand = new commander.Command('create').option('--cpu-count <cpu-count>','specify the number of CPUs that will be used to run the sandbox. The default value is 2.',- parseInt+ parsePositiveInt('CPU count')).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.',- parseInt+ parsePositiveInt('Memory in megabytes')).option('--no-cache', 'skip cache when building the template.').alias('ct')@@ -70,12 +71,14 @@ export const createCommand = new commander.Command('create')try {process.stdout.write('\n')- // Validate template name- if (!/^[a-z0-9-_]+$/.test(templateName)) {+ // Validate and normalize template name+ try {+ templateName = validateTemplateName(templateName)+ } catch (err) {console.error(- `Template name ${asLocal(- templateName- )} is not valid. Template name can only contain lowercase letters, numbers, dashes and underscores.`+ `Template name ${asLocal(templateName)} is not valid. ${+ err instanceof Error ? err.message : String(err)+ }`)process.exit(1)}diff --git a/packages/cli/src/commands/template/init.ts b/packages/cli/src/commands/template/init.tsindex 3f2503131..e1b83e7e6 100644--- a/packages/cli/src/commands/template/init.ts+++ b/packages/cli/src/commands/template/init.ts@@ -7,6 +7,7 @@ import * as path from 'path'import { pathOption } from 'src/options'import { getRoot } from 'src/utils/filesystem'import { asPrimary } from 'src/utils/format'+import { validateTemplateName } from 'src/utils/templateName'import {generateAndWriteTemplateFiles,GeneratedFiles,@@ -137,37 +138,17 @@ async function addPackageJsonScripts(}}-/**- * Check template name format- */-function templateNameRegex(name: string): boolean {- return /^[a-z0-9][a-z0-9_-]*[a-z0-9]$|^[a-z0-9]$/.test(name)-}--function validateTemplateName(name: string) {- if (!name || name.trim().length === 0) {- throw new Error('Template name cannot be empty')- }- if (!templateNameRegex(name.trim())) {- throw new Error(- 'Template name must contain only lowercase letters, numbers, hyphens, and underscores, and cannot start or end with a hyphen or underscore'- )- }-}-export const initCommand = new commander.Command('init').description('initialize a new sandbox template using the SDK').addOption(pathOption).option('-n, --name <name>', 'template name', (value) => {try {- validateTemplateName(value)+ return validateTemplateName(value)} catch (err) {throw new commander.InvalidArgumentError(err instanceof Error ? err.message : String(err))}-- return value}).option('-l, --language <language>',@@ -210,7 +191,7 @@ export const initCommand = new commander.Command('init')},})}- templateName = templateName.trim()+ templateName = validateTemplateName(templateName)console.log(`Using template name: ${templateName}`)// Step 2: Get language (from CLI or prompt)diff --git a/packages/cli/src/commands/template/migrate.ts b/packages/cli/src/commands/template/migrate.tsindex 6f4474ffe..6bfbb6d06 100644--- a/packages/cli/src/commands/template/migrate.ts+++ b/packages/cli/src/commands/template/migrate.ts@@ -5,10 +5,11 @@ import * as fs from 'fs'import * as path from 'path'import { E2BConfig, getConfigPath, loadConfig } from '../../config'import { defaultDockerfileName } from '../../docker/constants'-import { configOption, pathOption } from '../../options'+import { configOption, parsePositiveInt, pathOption } from '../../options'import { getRoot } from '../../utils/filesystem'import { asLocal, asLocalRelative, asPrimary } from '../../utils/format'import { getDockerfile } from './dockerfile'+import { validateTemplateName } from '../../utils/templateName'import {generateAndWriteTemplateFiles,Language,@@ -22,7 +23,8 @@ async function migrateToLanguage(root: string,config: E2BConfig,dockerfileContent: string,- language: Language+ language: Language,+ nameOverride?: string): Promise<void> {// Initialize template with file contextconst template = Template({@@ -66,7 +68,7 @@ async function migrateToLanguage(parsedTemplate = baseTemplate.setReadyCmd(config.ready_cmd)}- const name = config.template_name || config.template_id+ const name = nameOverride || config.template_name || config.template_idif (!name) {throw new Error('Template name or ID is required')}@@ -93,6 +95,37 @@ export const migrateCommand = new commander.Command('migrate')`specify path to Dockerfile. Defaults to ${asLocal('e2b.Dockerfile')}`).addOption(configOption)+ .option(+ '-n, --name <name>',+ 'override the template name used in the generated files. Defaults to the template name or ID from the config file.',+ (value) => {+ try {+ return validateTemplateName(value)+ } catch (err) {+ throw new commander.InvalidArgumentError(+ err instanceof Error ? err.message : String(err)+ )+ }+ }+ )+ .option(+ '-c, --cmd <start-command>',+ 'override the command that will be executed when the sandbox is started.'+ )+ .option(+ '--ready-cmd <ready-command>',+ 'override the command that will need to exit 0 for the template to be ready.'+ )+ .option(+ '--cpu-count <cpu-count>',+ 'override the number of CPUs that will be used to run the sandbox.',+ parsePositiveInt('CPU count')+ )+ .option(+ '--memory-mb <memory-mb>',+ 'override the amount of memory in megabytes that will be used to run the sandbox. Must be an even number.',+ parsePositiveInt('Memory in megabytes')+ ).option('-l, --language <language>',`specify target language: ${Object.values(Language).join(', ')}`,@@ -114,11 +147,25 @@ export const migrateCommand = new commander.Command('migrate')config?: stringpath?: stringlanguage?: Language+ name?: string+ cmd?: string+ readyCmd?: string+ cpuCount?: number+ memoryMb?: number}) => {let success = falsetry {console.log('\n🔄 Migrating template configuration to SDK format...\n')+ // Validate memory override+ if (opts.memoryMb && opts.memoryMb % 2 !== 0) {+ throw new Error(+ `The memory in megabytes must be an even number. You provided ${asLocal(+ opts.memoryMb.toFixed(0)+ )}.`+ )+ }+const root = getRoot(opts.path)const configPath = getConfigPath(root, opts.config)@@ -141,6 +188,20 @@ export const migrateCommand = new commander.Command('migrate'))}+ // Apply command-line overrides on top of the loaded config+ if (opts.cmd !== undefined) {+ config.start_cmd = opts.cmd+ }+ if (opts.readyCmd !== undefined) {+ config.ready_cmd = opts.readyCmd+ }+ if (opts.cpuCount !== undefined) {+ config.cpu_count = opts.cpuCount+ }+ if (opts.memoryMb !== undefined) {+ config.memory_mb = opts.memoryMb+ }+// Determine target languagelet language: Languageif (opts.language) {@@ -173,7 +234,13 @@ export const migrateCommand = new commander.Command('migrate')}// Perform migration- await migrateToLanguage(root, config, dockerfileContent, language)+ await migrateToLanguage(+ root,+ config,+ dockerfileContent,+ language,+ opts.name+ )// Rename old files to .old extensionsconst oldFilesRenamed: { oldPath: string; newPath: string }[] = []diff --git a/packages/cli/src/options.ts b/packages/cli/src/options.tsindex 82bff22f4..0aa11a47d 100644--- a/packages/cli/src/options.ts+++ b/packages/cli/src/options.ts@@ -1,6 +1,22 @@import * as commander from 'commander'-import { asBold } from './utils/format'+import { asBold, asLocal } from './utils/format'++/**+ * Parse a CLI option as a positive integer, rejecting non-numeric values so+ * they don't silently become NaN.+ */+export function parsePositiveInt(label: string): (value: string) => number {+ return (value) => {+ const parsed = Number(value)+ if (!Number.isInteger(parsed) || parsed < 1) {+ throw new commander.InvalidArgumentError(+ `${label} must be a positive integer. You provided ${asLocal(value)}.`+ )+ }+ return parsed+ }+}export const pathOption = new commander.Option('-p, --path <path>',diff --git a/packages/cli/src/utils/templateName.ts b/packages/cli/src/utils/templateName.tsnew file mode 100644index 000000000..a418ea96b--- /dev/null+++ b/packages/cli/src/utils/templateName.ts@@ -0,0 +1,30 @@+/**+ * Allowed template name (alias) format, matching the server-side validation in+ * e2b-dev/infra (`id.identifierRegex`): the name is trimmed and lowercased,+ * then must contain only lowercase letters, numbers, dashes and underscores.+ */+const templateNameRegex = /^[a-z0-9-_]+$/++const MAX_TEMPLATE_NAME_LENGTH = 128++/**+ * Validates a template name and returns its normalized form (trimmed and+ * lowercased), matching how the server normalizes it.+ */+export function validateTemplateName(name: string): string {+ const cleaned = name?.trim().toLowerCase()+ if (!cleaned) {+ throw new Error('Template name cannot be empty')+ }+ if (!templateNameRegex.test(cleaned)) {+ throw new Error(+ 'Template name must contain only letters, numbers, dashes and underscores'+ )+ }+ if (cleaned.length > MAX_TEMPLATE_NAME_LENGTH) {+ throw new Error(+ `Template name must be at most ${MAX_TEMPLATE_NAME_LENGTH} characters long`+ )+ }+ return cleaned+}diff --git a/packages/cli/tests/commands/template/init.test.ts b/packages/cli/tests/commands/template/init.test.tsindex 7f3222f5d..a46d9ce46 100644--- a/packages/cli/tests/commands/template/init.test.ts+++ b/packages/cli/tests/commands/template/init.test.ts@@ -58,14 +58,13 @@ describe('Template Init', () => {})test('should validate template name format', async () => {+ // Matches the server-side rule in e2b-dev/infra (id.identifierRegex):+ // only lowercase letters, numbers, dashes and underscores are allowed.const invalidNames = [- 'My-Template', // uppercase- '-invalid-start', // starts with hyphen- 'invalid-end-', // ends with hyphen- '_invalid-start', // starts with underscore- 'invalid-end_', // ends with underscore'invalid space', // contains space+ 'invalid.dot', // contains a dot'', // empty+ 'a'.repeat(129), // exceeds the 128 character limit]for (const invalidName of invalidNames) {diff --git a/packages/cli/tests/commands/template/migrate.test.ts b/packages/cli/tests/commands/template/migrate.test.tsindex 227cffb96..9dd87840e 100644--- a/packages/cli/tests/commands/template/migrate.test.ts+++ b/packages/cli/tests/commands/template/migrate.test.ts@@ -174,6 +174,106 @@ describe('Template Migration', () => {}})+ describe('Override Options', () => {+ test('should apply name, command and resource overrides', async () => {+ const dockerfile = 'FROM node:18'+ await fs.writeFile(path.join(testDir, 'e2b.Dockerfile'), dockerfile)++ const config = `template_id = "config-name"+dockerfile = "e2b.Dockerfile"+cpu_count = 2+memory_mb = 512`+ await fs.writeFile(path.join(testDir, 'e2b.toml'), config)++ execSync(+ `node ${cliPath} template migrate --language typescript --name " Overridden-Name " --cmd "node server.js" --ready-cmd "curl localhost:3000" --cpu-count 4 --memory-mb 2048`,+ {+ cwd: testDir,+ }+ )++ const templateFile = await fs.readFile(+ path.join(testDir, 'template.ts'),+ 'utf-8'+ )+ expect(templateFile).toContain(+ ".setStartCmd('sudo node server.js', 'curl localhost:3000')"+ )++ const buildProdFile = await fs.readFile(+ path.join(testDir, 'build.prod.ts'),+ 'utf-8'+ )+ expect(buildProdFile).toContain("'overridden-name'")+ expect(buildProdFile).not.toContain("'config-name'")+ expect(buildProdFile).toContain('cpuCount: 4')+ expect(buildProdFile).toContain('memoryMB: 2048')+ })++ test('should reject an invalid --name', async () => {+ const dockerfile = 'FROM node:18'+ await fs.writeFile(path.join(testDir, 'e2b.Dockerfile'), dockerfile)++ const config = `template_id = "config-name"+dockerfile = "e2b.Dockerfile"`+ await fs.writeFile(path.join(testDir, 'e2b.toml'), config)++ expect(() => {+ execSync(+ `node ${cliPath} template migrate --language typescript --name "Invalid Name"`,+ {+ cwd: testDir,+ }+ )+ }).toThrow()+ })++ test('should reject non-numeric resource overrides', async () => {+ const dockerfile = 'FROM node:18'+ await fs.writeFile(path.join(testDir, 'e2b.Dockerfile'), dockerfile)++ const config = `template_id = "config-name"+dockerfile = "e2b.Dockerfile"`+ await fs.writeFile(path.join(testDir, 'e2b.toml'), config)++ expect(() => {+ execSync(+ `node ${cliPath} template migrate --language typescript --cpu-count abc`,+ {+ cwd: testDir,+ }+ )+ }).toThrow()++ expect(() => {+ execSync(+ `node ${cliPath} template migrate --language typescript --memory-mb abc`,+ {+ cwd: testDir,+ }+ )+ }).toThrow()+ })++ test('should reject an odd memory override', async () => {+ const dockerfile = 'FROM node:18'+ await fs.writeFile(path.join(testDir, 'e2b.Dockerfile'), dockerfile)++ const config = `template_id = "resources"+dockerfile = "e2b.Dockerfile"`+ await fs.writeFile(path.join(testDir, 'e2b.toml'), config)++ expect(() => {+ execSync(+ `node ${cliPath} template migrate --language typescript --memory-mb 1023`,+ {+ cwd: testDir,+ }+ )+ }).toThrow()+ })+ })+describe('Error Cases', () => {test('should succeed with warning when config file is missing', async () => {// Create only Dockerfile, no config