Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Apply prettier
Jakub Novak16f0512b7ebc
diff --git a/packages/cli/src/api.ts b/packages/cli/src/api.tsindex 4ab0dba09..920a2597d 100644--- a/packages/cli/src/api.ts+++ b/packages/cli/src/api.ts@@ -3,7 +3,7 @@ import * as e2b from 'e2b'import { getUserConfig } from './user'import { asBold, asPrimary } from './utils/format'-import {ConnectionConfig} from 'e2b'+import { ConnectionConfig } from 'e2b'export let apiKey = process.env.E2B_API_KEYexport let accessToken = process.env.E2B_ACCESS_TOKEN@@ -11,8 +11,12 @@ export let accessToken = process.env.E2B_ACCESS_TOKENconst authErrorBox = boxen.default(`You must be logged in to use this command. Run ${asBold('e2b auth login')}.-If you are seeing this message in CI/CD you may need to set the ${asBold('E2B_ACCESS_TOKEN')} environment variable.-Visit ${asPrimary('https://e2b.dev/docs/getting-started/api-key')} to get the access token.`,+If you are seeing this message in CI/CD you may need to set the ${asBold(+ 'E2B_ACCESS_TOKEN',+ )} environment variable.+Visit ${asPrimary(+ 'https://e2b.dev/docs/getting-started/api-key',+ )} to get the access token.`,{width: 70,float: 'center',@@ -39,12 +43,12 @@ export function ensureAPIKey() {}export function ensureUserConfig() {- const userConfig = getUserConfig()- if (!userConfig) {- console.error('No user config found, run `e2b auth login` to log in first.')- process.exit(1)- }- return userConfig+ const userConfig = getUserConfig()+ if (!userConfig) {+ console.error('No user config found, run `e2b auth login` to log in first.')+ process.exit(1)+ }+ return userConfig}export function ensureAccessToken() {@@ -62,8 +66,10 @@ export function ensureAccessToken() {}}-const userConfig = getUserConfig()-export const connectionConfig = new ConnectionConfig({accessToken: userConfig?.accessToken, apiKey: userConfig?.teamApiKey })+export const connectionConfig = new ConnectionConfig({+ accessToken: userConfig?.accessToken,+ apiKey: userConfig?.teamApiKey,+})export const client = new e2b.ApiClient(connectionConfig)diff --git a/packages/cli/src/commands/auth/configure.ts b/packages/cli/src/commands/auth/configure.tsindex faf74aa48..8e9eabd1e 100644--- a/packages/cli/src/commands/auth/configure.ts+++ b/packages/cli/src/commands/auth/configure.ts@@ -5,10 +5,14 @@ import * as e2b from 'e2b'import * as path from 'path'import { USER_CONFIG_PATH } from 'src/user'-import {client, connectionConfig, ensureAccessToken, ensureUserConfig} from 'src/api'+import {+ client,+ connectionConfig,+ ensureAccessToken,+ ensureUserConfig,+} from 'src/api'import { asFormattedTeam } from '../../utils/format'-import {handleE2BRequestError} from '../../utils/errors'-+import { handleE2BRequestError } from '../../utils/errors'export const configureCommand = new commander.Command('configure').description('configure user')@@ -26,27 +30,29 @@ export const configureCommand = new commander.Command('configure')ensureAccessToken()const signal = connectionConfig.getSignal()- const res = await client.api.GET('/teams', {signal})+ const res = await client.api.GET('/teams', { signal })handleE2BRequestError(res.error, 'Error getting teams')- const team = (await inquirer.default.prompt([- {- name: 'team',- message: chalk.default.underline('Select team'),- type: 'list',- pageSize: 50,- choices: res.data.map((team: e2b.components['schemas']['Team']) => ({- name: asFormattedTeam(team),- value: team,- })),- },- ]))['team']+ const team = (+ await inquirer.default.prompt([+ {+ name: 'team',+ message: chalk.default.underline('Select team'),+ type: 'list',+ pageSize: 50,+ choices: res.data.map((team: e2b.components['schemas']['Team']) => ({+ name: asFormattedTeam(team),+ value: team,+ })),+ },+ ])+ )['team']userConfig.teamName = team.nameuserConfig.teamId = team.teamIDuserConfig.teamApiKey = team.apiKey- fs.mkdirSync(path.dirname(USER_CONFIG_PATH), {recursive: true})+ fs.mkdirSync(path.dirname(USER_CONFIG_PATH), { recursive: true })fs.writeFileSync(USER_CONFIG_PATH, JSON.stringify(userConfig, null, 2))console.log(`Team ${asFormattedTeam(team)} selected.\n`)diff --git a/packages/cli/src/commands/auth/index.ts b/packages/cli/src/commands/auth/index.tsindex 755fcdaef..1cfb43b1e 100644--- a/packages/cli/src/commands/auth/index.ts+++ b/packages/cli/src/commands/auth/index.ts@@ -4,8 +4,8 @@ import { logoutCommand } from './logout'import { infoCommand } from './info'import { configureCommand } from './configure'--export const authCommand = new commander.Command('auth').description('authentication commands')+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.tsindex a99a3a5d5..76fd7a8ef 100644--- a/packages/cli/src/commands/auth/info.ts+++ b/packages/cli/src/commands/auth/info.ts@@ -1,7 +1,7 @@import * as commander from 'commander'import { getUserConfig } from 'src/user'-import { asFormattedConfig, asFormattedError} from 'src/utils/format'+import { asFormattedConfig, asFormattedError } from 'src/utils/format'export const infoCommand = new commander.Command('info').description('get information about the current user')diff --git a/packages/cli/src/commands/auth/login.ts b/packages/cli/src/commands/auth/login.tsindex 7add67126..1d10a419f 100644--- a/packages/cli/src/commands/auth/login.ts+++ b/packages/cli/src/commands/auth/login.ts@@ -7,10 +7,15 @@ import * as path from 'path'import * as e2b from 'e2b'import { pkg } from 'src'-import { DOCS_BASE, getUserConfig, USER_CONFIG_PATH, UserConfig } from 'src/user'+import {+ DOCS_BASE,+ getUserConfig,+ USER_CONFIG_PATH,+ UserConfig,+} from 'src/user'import { asBold, asFormattedConfig, asFormattedError } from 'src/utils/format'-import {client, connectionConfig} from 'src/api'-import {handleE2BRequestError} from '../../utils/errors'+import { client, connectionConfig } from 'src/api'+import { handleE2BRequestError } from '../../utils/errors'export const loginCommand = new commander.Command('login').description('log in to CLI')@@ -23,7 +28,9 @@ export const loginCommand = new commander.Command('login')}if (userConfig) {console.log(- `\nAlready logged in. ${asFormattedConfig(userConfig)}.\n\nIf you want to log in as a different user, log out first by running 'e2b auth logout'.\nTo change the team, run 'e2b auth configure'.\n`,+ `\nAlready logged in. ${asFormattedConfig(+ userConfig,+ )}.\n\nIf you want to log in as a different user, log out first by running 'e2b auth logout'.\nTo change the team, run 'e2b auth configure'.\n`,)return} else if (!userConfig) {@@ -35,26 +42,32 @@ export const loginCommand = new commander.Command('login')}const signal = connectionConfig.getSignal()- const res = await client.api.GET('/teams', {signal})+ const res = await client.api.GET('/teams', { signal })handleE2BRequestError(res.error, 'Error getting teams')- const defaultTeam = res.data.find((team: e2b.components['schemas']['Team']) => team.isDefault)+ const defaultTeam = res.data.find(+ (team: e2b.components['schemas']['Team']) => team.isDefault,+ )if (!defaultTeam) {- console.error(asFormattedError('No default team found, please contact support'))+ console.error(+ asFormattedError('No default team found, please contact support'),+ )process.exit(1)}userConfig.teamName = defaultTeam.nameuserConfig.teamId = defaultTeam.teamIDuserConfig.teamApiKey = defaultTeam.apiKey- fs.mkdirSync(path.dirname(USER_CONFIG_PATH), {recursive: true})+ fs.mkdirSync(path.dirname(USER_CONFIG_PATH), { recursive: true })fs.writeFileSync(USER_CONFIG_PATH, JSON.stringify(userConfig, null, 2))}--- console.log(`Logged in as ${asBold(userConfig.email)} with default team ${asBold(userConfig.teamName)}`)+ console.log(+ `Logged in as ${asBold(userConfig.email)} with default team ${asBold(+ userConfig.teamName,+ )}`,+ )process.exit(0)})@@ -73,9 +86,9 @@ async function signInWithBrowser(): Promise<UserConfig> {const searchParams = new URL(req.url || '/', 'http://localhost').searchParamsconst searchParamsObj = Object.fromEntries(- searchParams.entries()+ searchParams.entries(),) as unknown as UserConfig & {- error?: string;+ error?: string}const { error } = searchParamsObjif (error) {diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.tsindex c0ce99df3..e12eca174 100644--- a/packages/cli/src/commands/index.ts+++ b/packages/cli/src/commands/index.ts@@ -6,10 +6,16 @@ import { sandboxCommand } from './sandbox'import { authCommand } from './auth'export const program = new commander.Command()- .description(`Create sandbox templates from Dockerfiles by running ${asPrimary('e2b template build')} then use our SDKs to create sandboxes from these templates.+ .description(+ `Create sandbox templates from Dockerfiles by running ${asPrimary(+ 'e2b template 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.-`)+Visit ${asPrimary(+ 'E2B docs (https://e2b.dev/docs)',+ )} to learn how to create sandbox templates and start sandboxes.+`,+ ).addCommand(authCommand).addCommand(templateCommand).addCommand(sandboxCommand)diff --git a/packages/cli/src/commands/sandbox/connect.ts b/packages/cli/src/commands/sandbox/connect.tsindex 383095ec6..e71e04120 100644--- a/packages/cli/src/commands/sandbox/connect.ts+++ b/packages/cli/src/commands/sandbox/connect.ts@@ -14,9 +14,7 @@ export const connectCommand = new commander.Command('connect')const apiKey = ensureAPIKey()if (!sandboxID) {- console.error(- 'You need to specify sandbox ID',- )+ console.error('You need to specify sandbox ID')process.exit(1)}@@ -30,11 +28,20 @@ export const connectCommand = new commander.Command('connect')}})--async function connectToSandbox({ apiKey, sandboxID }: { apiKey: string, sandboxID: string }) {+async function connectToSandbox({+ apiKey,+ sandboxID,+}: {+ apiKey: string+ sandboxID: string+}) {const sandbox = await Sandbox.connect(sandboxID, { apiKey })- console.log(`Terminal connecting to sandbox ${asPrimary(`${sandbox.sandboxId}`)}`)+ console.log(+ `Terminal connecting to sandbox ${asPrimary(`${sandbox.sandboxId}`)}`,+ )await spawnConnectedTerminal(sandbox)- console.log(`Closing terminal connection to sandbox ${asPrimary(sandbox.sandboxId)}`)+ console.log(+ `Closing terminal connection to sandbox ${asPrimary(sandbox.sandboxId)}`,+ )}diff --git a/packages/cli/src/commands/sandbox/index.ts b/packages/cli/src/commands/sandbox/index.tsindex aa2e20b5e..538ad5bff 100644--- a/packages/cli/src/commands/sandbox/index.ts+++ b/packages/cli/src/commands/sandbox/index.ts@@ -6,7 +6,8 @@ import { killCommand } from './kill'import { spawnCommand } from './spawn'import { logsCommand } from './logs'-export const sandboxCommand = new commander.Command('sandbox').description('work with sandboxes')+export const sandboxCommand = new commander.Command('sandbox')+ .description('work with sandboxes').alias('sbx').addCommand(connectCommand).addCommand(listCommand)diff --git a/packages/cli/src/commands/sandbox/kill.ts b/packages/cli/src/commands/sandbox/kill.tsindex 6b9845dad..86cd0d494 100644--- a/packages/cli/src/commands/sandbox/kill.ts+++ b/packages/cli/src/commands/sandbox/kill.ts@@ -6,7 +6,10 @@ import * as e2b from 'e2b'export const killCommand = new commander.Command('kill').description('kill sandbox')- .argument('<sandboxID>', `kill the sandbox specified by ${asBold('<sandboxID>')}`)+ .argument(+ '<sandboxID>',+ `kill the sandbox specified by ${asBold('<sandboxID>')}`,+ ).alias('kl').action(async (sandboxID: string) => {try {@@ -17,7 +20,7 @@ export const killCommand = new commander.Command('kill')process.exit(1)}- await e2b.Sandbox.kill(sandboxID, {apiKey})+ await e2b.Sandbox.kill(sandboxID, { apiKey })console.log(`Sandbox ${asBold(sandboxID)} has been killed`)} catch (err: any) {diff --git a/packages/cli/src/commands/sandbox/list.ts b/packages/cli/src/commands/sandbox/list.tsindex 9558f727f..6558dd1b9 100644--- a/packages/cli/src/commands/sandbox/list.ts+++ b/packages/cli/src/commands/sandbox/list.ts@@ -2,8 +2,8 @@ import * as tablePrinter from 'console-table-printer'import * as commander from 'commander'import * as e2b from 'e2b'-import {ensureAPIKey, client, connectionConfig} from 'src/api'-import {handleE2BRequestError} from '../../utils/errors'+import { ensureAPIKey, client, connectionConfig } from 'src/api'+import { handleE2BRequestError } from '../../utils/errors'export const listCommand = new commander.Command('list').description('list all running sandboxes')@@ -28,9 +28,19 @@ export const listCommand = new commander.Command('list'){ name: 'metadata', alignment: 'left', title: 'Metadata' },],disabledColumns: ['clientID'],- rows: sandboxes.map((sandbox) => ({ ...sandbox, sandboxID: `${sandbox.sandboxID}-${sandbox.clientID}`, startedAt: new Date(sandbox.startedAt).toLocaleString(), endAt: new Date(sandbox.endAt).toLocaleString(), metadata: JSON.stringify(sandbox.metadata) })).sort(- (a, b) => a.startedAt.localeCompare(b.startedAt) || a.sandboxID.localeCompare(b.sandboxID)- ),+ rows: sandboxes+ .map((sandbox) => ({+ ...sandbox,+ sandboxID: `${sandbox.sandboxID}-${sandbox.clientID}`,+ startedAt: new Date(sandbox.startedAt).toLocaleString(),+ endAt: new Date(sandbox.endAt).toLocaleString(),+ metadata: JSON.stringify(sandbox.metadata),+ }))+ .sort(+ (a, b) =>+ a.startedAt.localeCompare(b.startedAt) ||+ a.sandboxID.localeCompare(b.sandboxID),+ ),colorMap: {orange: '\x1b[38;5;216m',},@@ -45,11 +55,13 @@ export const listCommand = new commander.Command('list')}})-export async function listSandboxes(): Promise<e2b.components['schemas']['RunningSandbox'][]> {+export async function listSandboxes(): Promise<+ e2b.components['schemas']['RunningSandbox'][]+> {ensureAPIKey()const signal = connectionConfig.getSignal()- const res = await client.api.GET('/sandboxes', {signal})+ const res = await client.api.GET('/sandboxes', { signal })handleE2BRequestError(res.error, 'Error getting running sandboxes')diff --git a/packages/cli/src/commands/sandbox/logs.ts b/packages/cli/src/commands/sandbox/logs.tsindex f56220087..d725edaf0 100644--- a/packages/cli/src/commands/sandbox/logs.ts+++ b/packages/cli/src/commands/sandbox/logs.ts@@ -3,12 +3,11 @@ import * as e2b from 'e2b'import * as util from 'util'import * as chalk from 'chalk'-import {client, connectionConfig} from 'src/api'+import { client, connectionConfig } from 'src/api'import { asBold, asTimestamp, withUnderline } from 'src/utils/format'import { listSandboxes } from './list'import { wait } from 'src/utils/wait'-import {handleE2BRequestError} from '../../utils/errors'-+import { handleE2BRequestError } from '../../utils/errors'const maxRuntime = 24 * 60 * 60 * 1000 // 24 hours in milliseconds@@ -33,7 +32,9 @@ function waitForSandboxEnd(sandboxID: string) {}const response = await listSandboxes()- const sandbox = response.find(s => s.sandboxID === getShortID(sandboxID))+ const sandbox = response.find(+ (s) => s.sandboxID === getShortID(sandboxID),+ )if (!sandbox) {isRunning = falsebreak@@ -63,7 +64,11 @@ function isLevelIncluded(level: LogLevel, allowedLevel?: LogLevel) {case LogLevel.DEBUG:return truecase LogLevel.INFO:- return level === LogLevel.INFO || level === LogLevel.WARN || level === LogLevel.ERROR+ return (+ level === LogLevel.INFO ||+ level === LogLevel.WARN ||+ level === LogLevel.ERROR+ )case LogLevel.WARN:return level === LogLevel.WARN || level === LogLevel.ERRORcase LogLevel.ERROR:@@ -72,7 +77,9 @@ function isLevelIncluded(level: LogLevel, allowedLevel?: LogLevel) {}function formatEnum(e: { [key: string]: string }) {- return Object.values(e).map(level => asBold(level)).join(', ')+ return Object.values(e)+ .map((level) => asBold(level))+ .join(', ')}enum LogFormat {@@ -88,7 +95,6 @@ enum LoggerService {FILE = 'file',}-function cleanLogger(logger?: string) {if (!logger) {return ''@@ -99,52 +105,84 @@ function cleanLogger(logger?: string) {export const logsCommand = new commander.Command('logs').description('show logs for sandbox')- .argument('<sandboxID>', `show logs for sandbox specified by ${asBold('<sandboxID>')}`)+ .argument(+ '<sandboxID>',+ `show logs for sandbox specified by ${asBold('<sandboxID>')}`,+ ).alias('lg')- .option('--level <level>', `filter logs by level (${formatEnum(LogLevel)}). The logs with the higher levels will be also shown.`, LogLevel.INFO)+ .option(+ '--level <level>',+ `filter logs by level (${formatEnum(+ LogLevel,+ )}). The logs with the higher levels will be also shown.`,+ LogLevel.INFO,+ ).option('-f, --follow', 'keep streaming logs until the sandbox is closed')- .option('--format <format>', `specify format for printing logs (${formatEnum(LogFormat)})`, LogFormat.PRETTY)- .option('--loggers [loggers]', `filter logs by loggers. The available loggers are ${formatEnum(LoggerService)}. Specify multiple loggers by separating them with a comma.`, (value) => {- const loggers = value.split(',').map(s => s.trim()) as LoggerService[]- // Check if all loggers are valid- loggers.forEach(s => {- if (!Object.values(LoggerService).includes(s)) {- console.error(`Invalid logger used as argument: "${s}"\nValid loggers are ${formatEnum(LoggerService)}`)- process.exit(1)- }- })- return loggers- }, [LoggerService.PROCESS, LoggerService.FILESYSTEM])- .action(async (sandboxID: string, opts?: {- level: string,- follow: boolean,- format: LogFormat,- loggers: LoggerService[] | boolean,- }) => {- try {- const level = opts?.level.toUpperCase() as LogLevel | undefined- if (level && !Object.values(LogLevel).includes(level)) {- throw new Error(`Invalid log level: ${level}`)- }-- const format = opts?.format.toLowerCase() as LogFormat | undefined- if (format && !Object.values(LogFormat).includes(format)) {- throw new Error(`Invalid log format: ${format}`)- }-- const getIsRunning = opts?.follow ? waitForSandboxEnd(sandboxID) : () => false-- let start: number | undefined- let isFirstRun = true- let firstLogsPrinted = false-- if (format === LogFormat.PRETTY) {- console.log(`\nLogs for sandbox ${asBold(sandboxID)}:`)- }-- const isRunningPromise = listSandboxes().then(r => r.find(s => s.sandboxID === getShortID(sandboxID))).then(s => !!s)-- do {+ .option(+ '--format <format>',+ `specify format for printing logs (${formatEnum(LogFormat)})`,+ LogFormat.PRETTY,+ )+ .option(+ '--loggers [loggers]',+ `filter logs by loggers. The available loggers are ${formatEnum(+ LoggerService,+ )}. Specify multiple loggers by separating them with a comma.`,+ (value) => {+ const loggers = value.split(',').map((s) => s.trim()) as LoggerService[]+ // Check if all loggers are valid+ loggers.forEach((s) => {+ if (!Object.values(LoggerService).includes(s)) {+ console.error(+ `Invalid logger used as argument: "${s}"\nValid loggers are ${formatEnum(+ LoggerService,+ )}`,+ )+ process.exit(1)+ }+ })+ return loggers+ },+ [LoggerService.PROCESS, LoggerService.FILESYSTEM],+ )+ .action(+ async (+ sandboxID: string,+ opts?: {+ level: string+ follow: boolean+ format: LogFormat+ loggers: LoggerService[] | boolean+ },+ ) => {+ try {+ const level = opts?.level.toUpperCase() as LogLevel | undefined+ if (level && !Object.values(LogLevel).includes(level)) {+ throw new Error(`Invalid log level: ${level}`)+ }++ const format = opts?.format.toLowerCase() as LogFormat | undefined+ if (format && !Object.values(LogFormat).includes(format)) {+ throw new Error(`Invalid log format: ${format}`)+ }++ const getIsRunning = opts?.follow+ ? waitForSandboxEnd(sandboxID)+ : () => false++ let start: number | undefined+ let isFirstRun = true+ let firstLogsPrinted = false++ if (format === LogFormat.PRETTY) {+ console.log(`\nLogs for sandbox ${asBold(sandboxID)}:`)+ }++ const isRunningPromise = listSandboxes()+ .then((r) => r.find((s) => s.sandboxID === getShortID(sandboxID)))+ .then((s) => !!s)++ do {const logs = await listSandboxLogs({ sandboxID, start })if (logs.length !== 0 && firstLogsPrinted === false) {@@ -160,14 +198,22 @@ export const logsCommand = new commander.Command('logs')if (!isRunning && logs.length === 0 && isFirstRun) {if (format === LogFormat.PRETTY) {- console.log(`\nStopped printing logs — sandbox ${withUnderline('not found')}`)+ console.log(+ `\nStopped printing logs — sandbox ${withUnderline(+ 'not found',+ )}`,+ )}break}if (!isRunning) {if (format === LogFormat.PRETTY) {- console.log(`\nStopped printing logs — sandbox is ${withUnderline('closed')}`)+ console.log(+ `\nStopped printing logs — sandbox is ${withUnderline(+ 'closed',+ )}`,+ )}break}@@ -178,23 +224,36 @@ export const logsCommand = new commander.Command('logs')start = new Date(lastLog.timestamp).getTime() + 1}- await wait(400)- isFirstRun = false- } while (getIsRunning() && opts?.follow)- } catch (err: any) {- console.error(err)- process.exit(1)- }- })--function printLog(timestamp: string, line: string, allowedLevel: LogLevel | undefined, format: LogFormat | undefined, allowedLoggers?: LoggerService[] | boolean) {+ await wait(400)+ isFirstRun = false+ } while (getIsRunning() && opts?.follow)+ } catch (err: any) {+ console.error(err)+ process.exit(1)+ }+ },+ )++function printLog(+ timestamp: string,+ line: string,+ allowedLevel: LogLevel | undefined,+ format: LogFormat | undefined,+ allowedLoggers?: LoggerService[] | boolean,+) {const log = JSON.parse(line)let level = log['level'].toUpperCase()log.logger = cleanLogger(log.logger)// Check if the current logger startsWith any of the allowed loggers. If there are no specified loggers, print logs from all loggers.- if (allowedLoggers !== true && Array.isArray(allowedLoggers) && !allowedLoggers.some(allowedLogger => log.logger.startsWith(allowedLogger))) {+ if (+ allowedLoggers !== true &&+ Array.isArray(allowedLoggers) &&+ !allowedLoggers.some((allowedLogger) =>+ log.logger.startsWith(allowedLogger),+ )+ ) {return}@@ -227,25 +286,42 @@ function printLog(timestamp: string, line: string, allowedLevel: LogLevel | undedelete log['sandboxID']if (format === LogFormat.JSON) {- console.log(JSON.stringify({- timestamp: new Date(timestamp).toISOString(),- level,- ...log,- }))+ console.log(+ JSON.stringify({+ timestamp: new Date(timestamp).toISOString(),+ level,+ ...log,+ }),+ )} else {- const time = `[${new Date(timestamp).toISOString().replace(/T/, ' ').replace(/\..+/, '')}]`+ const time = `[${new Date(timestamp)+ .toISOString()+ .replace(/T/, ' ')+ .replace(/\..+/, '')}]`delete log['level']- console.log(`${asTimestamp(time)} ${level} ` + util.inspect(log, { colors: true, depth: null, maxArrayLength: Infinity, sorted: true, compact: true, breakLength: Infinity }))+ console.log(+ `${asTimestamp(time)} ${level} ` ++ util.inspect(log, {+ colors: true,+ depth: null,+ maxArrayLength: Infinity,+ sorted: true,+ compact: true,+ breakLength: Infinity,+ }),+ )}}export async function listSandboxLogs({sandboxID,start,-}: { sandboxID: string, start?: number }): Promise<e2b.components['schemas']['SandboxLog'][]> {-+}: {+ sandboxID: string+ start?: number+}): Promise<e2b.components['schemas']['SandboxLog'][]> {const signal = connectionConfig.getSignal()- const res = await client.api.GET('/sandboxes/{sandboxID}/logs', {+ const res = await client.api.GET('/sandboxes/{sandboxID}/logs', {signal,params: {path: {diff --git a/packages/cli/src/commands/sandbox/spawn.ts b/packages/cli/src/commands/sandbox/spawn.tsindex 93cfc41a3..32672c9f1 100644--- a/packages/cli/src/commands/sandbox/spawn.ts+++ b/packages/cli/src/commands/sandbox/spawn.ts@@ -87,12 +87,20 @@ export async function connectSandbox({await sandbox.setTimeout(10_000)}, 5_000)- console.log(`Terminal connecting to template ${asFormattedSandboxTemplate(template)} with sandbox ID ${asBold(`${sandbox.sandboxId}`)}`)+ console.log(+ `Terminal connecting to template ${asFormattedSandboxTemplate(+ template,+ )} with sandbox ID ${asBold(`${sandbox.sandboxId}`)}`,+ )try {await spawnConnectedTerminal(sandbox)} finally {clearInterval(intervalId)await sandbox.kill()- console.log(`Closing terminal connection to template ${asFormattedSandboxTemplate(template)} with sandbox ID ${asBold(`${sandbox.sandboxId}`)}`)+ console.log(+ `Closing terminal connection to template ${asFormattedSandboxTemplate(+ template,+ )} with sandbox ID ${asBold(`${sandbox.sandboxId}`)}`,+ )}}diff --git a/packages/cli/src/commands/template/build.ts b/packages/cli/src/commands/template/build.tsindex 9748d7671..da725172a 100644--- a/packages/cli/src/commands/template/build.ts+++ b/packages/cli/src/commands/template/build.ts@@ -6,7 +6,7 @@ import * as stripAnsi from 'strip-ansi'import * as boxen from 'boxen'import commandExists from 'command-exists'import { wait } from 'src/utils/wait'-import {connectionConfig, ensureAccessToken} from 'src/api'+import { connectionConfig, ensureAccessToken } from 'src/api'import { getRoot } from 'src/utils/filesystem'import {asBold,@@ -28,13 +28,23 @@ import { configName, getConfigPath, loadConfig, saveConfig } from 'src/config'import * as child_process from 'child_process'import { client } from 'src/api'-import {handleE2BRequestError} from '../../utils/errors'+import { handleE2BRequestError } from '../../utils/errors'const templateCheckInterval = 500 // 0.5 sec-async function getTemplateBuildLogs({templateID, buildID, logsOffset}: {templateID: string, buildID: string, logsOffset: number}) {- const signal = connectionConfig.getSignal()- const res = await client.api.GET('/templates/{templateID}/builds/{buildID}/status', {+async function getTemplateBuildLogs({+ templateID,+ buildID,+ logsOffset,+}: {+ templateID: string+ buildID: string+ logsOffset: number+}) {+ const signal = connectionConfig.getSignal()+ const res = await client.api.GET(+ '/templates/{templateID}/builds/{buildID}/status',+ {signal,params: {path: {@@ -43,50 +53,54 @@ async function getTemplateBuildLogs({templateID, buildID, logsOffset}: {template},query: {logsOffset,- }- }-- }- )+ },+ },+ },+ )handleE2BRequestError(res.error, 'Error getting template build status')return res.data as e2b.paths['/templates/{templateID}/builds/{buildID}/status']['get']['responses']['200']['content']['application/json']}--async function requestTemplateBuild(args?: e2b.paths['/templates']['post']['requestBody']['content']['application/json']) {- return await client.api.POST('/templates', {- body: args,- }- )+async function requestTemplateBuild(+ args?: e2b.paths['/templates']['post']['requestBody']['content']['application/json'],+) {+ return await client.api.POST('/templates', {+ body: args,+ })}-async function requestTemplateRebuild(templateID: string, args?: e2b.paths['/templates/{templateID}']['post']['requestBody']['content']['application/json']) {+async function requestTemplateRebuild(+ templateID: string,+ args?: e2b.paths['/templates/{templateID}']['post']['requestBody']['content']['application/json'],+) {return await client.api.POST('/templates/{templateID}', {body: args,params: {path: {- templateID- }- }+ templateID,+ },+ },})}async function triggerTemplateBuild(templateID: string, buildID: string) {- const res = await client.api- .POST('/templates/{templateID}/builds/{buildID}', {+ const res = await client.api.POST(+ '/templates/{templateID}/builds/{buildID}',+ {params: {- path:{- templateID,- buildID}- }- })+ path: {+ templateID,+ buildID,+ },+ },+ },+ )handleE2BRequestError(res.error, 'Error triggering template build')return res.data}-export const buildCommand = new commander.Command('build').description(`build sandbox template defined by ${asLocalRelative(@@ -317,12 +331,13 @@ export const buildCommand = new commander.Command('build')process.stdout.write('\n')console.log('Building docker image...')- const cmd = `docker build . -f ${dockerfileRelativePath} --pull --platform linux/amd64 -t docker.${connectionConfig.domain- }/e2b/custom-envs/${templateID}:${template.buildID} ${Object.entries(- dockerBuildArgs,- )- .map(([key, value]) => `--build-arg="${key}=${value}"`)- .join(' ')}`+ const cmd = `docker build . -f ${dockerfileRelativePath} --pull --platform linux/amd64 -t docker.${+ connectionConfig.domain+ }/e2b/custom-envs/${templateID}:${template.buildID} ${Object.entries(+ dockerBuildArgs,+ )+ .map(([key, value]) => `--build-arg="${key}=${value}"`)+ .join(' ')}`child_process.execSync(cmd, {stdio: 'inherit',cwd: root,@@ -383,11 +398,11 @@ async function waitForBuildFinish(do {await wait(templateCheckInterval)- template = await getTemplateBuildLogs({- templateID,- logsOffset,- buildID,- })+ template = await getTemplateBuildLogs({+ templateID,+ logsOffset,+ buildID,+ })logsOffset += template.logs.length@@ -401,8 +416,9 @@ async function waitForBuildFinish(const pythonExample = asPython(`from e2b import Sandbox# Start sandbox-sandbox = Sandbox(template="${aliases?.length ? aliases[0] : template.templateID- }")+sandbox = Sandbox(template="${+ aliases?.length ? aliases[0] : template.templateID+ }")# Interact with sandbox. Learn more here:# https://e2b.dev/docs/sandbox/overview@@ -413,7 +429,9 @@ sandbox.close()`)const typescriptExample = asTypescript(`import { Sandbox } from 'e2b'// Start sandbox-const sandbox = await Sandbox.create({ template: '${aliases?.length ? aliases[0] : template.templateID}' })+const sandbox = await Sandbox.create({ template: '${+ aliases?.length ? aliases[0] : template.templateID+ }' })// Interact with sandbox. Learn more here:// https://e2b.dev/docs/sandbox/overview@@ -564,11 +582,8 @@ async function requestBuildTemplate(return res.data}-async function triggerBuild(- templateID: string,- buildID: string,-) {- await triggerTemplateBuild( templateID, buildID )+async function triggerBuild(templateID: string, buildID: string) {+ await triggerTemplateBuild(templateID, buildID)return}diff --git a/packages/cli/src/commands/template/delete.ts b/packages/cli/src/commands/template/delete.tsindex eab1215b7..ebfa6fd06 100644--- a/packages/cli/src/commands/template/delete.ts+++ b/packages/cli/src/commands/template/delete.ts@@ -11,7 +11,12 @@ import {asLocal,asLocalRelative,} from 'src/utils/format'-import { configOption, pathOption, selectMultipleOption, teamOption } from 'src/options'+import {+ configOption,+ pathOption,+ selectMultipleOption,+ teamOption,+} from 'src/options'import {E2BConfig,configName,@@ -24,7 +29,7 @@ import { listSandboxTemplates } from './list'import { getPromptTemplates } from 'src/utils/templatePrompt'import { confirm } from 'src/utils/confirm'import { client } from 'src/api'-import {handleE2BRequestError} from '../../utils/errors'+import { handleE2BRequestError } from '../../utils/errors'async function deleteTemplate(templateID: string) {const res = await client.api.DELETE('/templates/{templateID}', {@@ -32,8 +37,7 @@ async function deleteTemplate(templateID: string) {path: {templateID,},- }-+ },})handleE2BRequestError(res.error, 'Error deleting sandbox template')@@ -82,7 +86,7 @@ export const deleteCommand = new commander.Command('delete')})} else if (opts.select) {const allTemplates = await listSandboxTemplates({- teamID: opts.team || userConfig.teamId || userConfig.defaultTeamId! // default team ID is here for backwards compatibility+ teamID: opts.team || userConfig.teamId || userConfig.defaultTeamId!, // default team ID is here for backwards compatibility})const selectedTemplates = await getPromptTemplates(@@ -149,7 +153,8 @@ export const deleteCommand = new commander.Command('delete')if (!opts.yes) {const confirmed = await confirm(- `Do you really want to delete ${templates.length === 1 ? 'this template' : 'these templates'+ `Do you really want to delete ${+ templates.length === 1 ? 'this template' : 'these templates'}?`,)@@ -167,7 +172,7 @@ export const deleteCommand = new commander.Command('delete')e.configPath,)}`,)- await deleteTemplate( e.template_id )+ await deleteTemplate(e.template_id)if (e.configPath) {await deleteConfig(e.configPath)}diff --git a/packages/cli/src/commands/template/index.ts b/packages/cli/src/commands/template/index.tsindex 69252fc12..d60bc2e75 100644--- a/packages/cli/src/commands/template/index.ts+++ b/packages/cli/src/commands/template/index.ts@@ -5,7 +5,8 @@ import { listCommand } from './list'import { initCommand } from './init'import { deleteCommand } from './delete'-export const templateCommand = new commander.Command('template').description('manage sandbox templates')+export const templateCommand = new commander.Command('template')+ .description('manage sandbox templates').alias('tpl').addCommand(buildCommand).addCommand(listCommand)diff --git a/packages/cli/src/commands/template/init.ts b/packages/cli/src/commands/template/init.tsindex b29c230c2..eac75b17a 100644--- a/packages/cli/src/commands/template/init.ts+++ b/packages/cli/src/commands/template/init.ts@@ -10,7 +10,11 @@ import { asLocalRelative, asPrimary } from 'src/utils/format'export const initCommand = new commander.Command('init').description(- `create basic E2B Dockerfile (${asLocalRelative('e2b.Dockerfile')}) in root directory. You can then run ${asPrimary('e2b template build')} to build sandbox template from this Dockerfile`,+ `create basic E2B Dockerfile (${asLocalRelative(+ 'e2b.Dockerfile',+ )}) in root directory. You can then run ${asPrimary(+ 'e2b template build',+ )} to build sandbox template from this Dockerfile`,).addOption(pathOption).alias('it')diff --git a/packages/cli/src/commands/template/list.ts b/packages/cli/src/commands/template/list.tsindex 8778263d4..f8b158a56 100644--- a/packages/cli/src/commands/template/list.ts+++ b/packages/cli/src/commands/template/list.ts@@ -6,24 +6,20 @@ import { listAliases } from '../../utils/format'import { sortTemplatesAliases } from 'src/utils/templateSort'import { client, ensureAccessToken, ensureUserConfig } from 'src/api'import { teamOption } from '../../options'-import {handleE2BRequestError} from '../../utils/errors'+import { handleE2BRequestError } from '../../utils/errors'export const listCommand = new commander.Command('list').description('list sandbox templates').alias('ls').addOption(teamOption)- .action(async (- opts: {- team: string- },- ) => {+ .action(async (opts: { team: string }) => {try {const userConfig = ensureUserConfig()ensureAccessToken()process.stdout.write('\n')const templates = await listSandboxTemplates({- teamID: opts.team || userConfig.teamId || userConfig.defaultTeamId! // default team ID is here for backwards compatibility)+ teamID: opts.team || userConfig.teamId || userConfig.defaultTeamId!, // default team ID is here for backwards compatibility)})for (const template of templates) {@@ -37,12 +33,20 @@ export const listCommand = new commander.Command('list')title: 'Sandbox templates',columns: [{ name: 'templateID', alignment: 'left', title: 'Template ID' },- { name: 'aliases', alignment: 'left', title: 'Template Name', color: 'orange' },+ {+ name: 'aliases',+ alignment: 'left',+ title: 'Template Name',+ color: 'orange',+ },{ name: 'cpuCount', alignment: 'right', title: 'vCPUs' },{ name: 'memoryMB', alignment: 'right', title: 'RAM MiB' },],disabledColumns: ['public', 'buildID'],- rows: templates.map((template) => ({ ...template, aliases: listAliases(template.aliases) })),+ rows: templates.map((template) => ({+ ...template,+ aliases: listAliases(template.aliases),+ })),colorMap: {orange: '\x1b[38;5;216m',},@@ -58,11 +62,15 @@ export const listCommand = new commander.Command('list')})export async function listSandboxTemplates({-teamID}: { teamID: string }): Promise<e2b.components['schemas']['Template'][]> {+ teamID,+}: {+ teamID: string+}): Promise<e2b.components['schemas']['Template'][]> {const templates = await client.api.GET('/templates', {- params: {- query: {teamID- }}})+ params: {+ query: { teamID },+ },+ })handleE2BRequestError(templates.error, 'Error getting templates')return templates.datadiff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex e0c6f36ba..dfdf8f18e 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -9,22 +9,34 @@ import * as stripAnsi from 'strip-ansi'export const pkg = packageJSON-updateNotifier.default({- pkg,- updateCheckInterval: 1000 * 60 * 60 * 8, // 8 hours-}).notify()+updateNotifier+ .default({+ pkg,+ updateCheckInterval: 1000 * 60 * 60 * 8, // 8 hours+ })+ .notify()program.version(packageJSON.version, undefined, 'display E2B CLI version')- .addOption(new Option('-cmd2json').hideHelp()).on('option:-cmd2json', () => {- process.stdout.write(JSON.stringify((program.commands.map((x: any) => ({- command: x.name(),- description: stripAnsi.default(x.description()),- options: x.options.map((y: any) => ({- flags: y.flags,- description: stripAnsi.default(y.description),- defaultValue: y.defaultValue,- })),- })).sort((row1: any, row2: any) => row1.name().localeCompare(row2.name())))))+ .addOption(new Option('-cmd2json').hideHelp())+ .on('option:-cmd2json', () => {+ process.stdout.write(+ JSON.stringify(+ program.commands+ .map((x: any) => ({+ command: x.name(),+ description: stripAnsi.default(x.description()),+ options: x.options.map((y: any) => ({+ flags: y.flags,+ description: stripAnsi.default(y.description),+ defaultValue: y.defaultValue,+ })),+ }))+ .sort((row1: any, row2: any) =>+ row1.name().localeCompare(row2.name()),+ ),+ ),+ )process.exit(0)- }).parse()+ })+ .parse()diff --git a/packages/cli/src/options.ts b/packages/cli/src/options.tsindex bce8f5775..9cd36378f 100644--- a/packages/cli/src/options.ts+++ b/packages/cli/src/options.ts@@ -11,7 +11,9 @@ export const pathOption = new commander.Option(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.`,+ `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(@@ -25,6 +27,6 @@ export const selectMultipleOption = new commander.Option()export const teamOption = new commander.Option(- '-t, --team <team-id>',- 'specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team).',- )+ '-t, --team <team-id>',+ 'specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team).',+)diff --git a/packages/cli/src/terminal.ts b/packages/cli/src/terminal.tsindex 6cef38083..495485c8c 100644--- a/packages/cli/src/terminal.ts+++ b/packages/cli/src/terminal.ts@@ -1,6 +1,5 @@import * as e2b from 'e2b'-function getStdoutSize() {return {cols: process.stdout.columns,@@ -10,7 +9,6 @@ function getStdoutSize() {const ctrlCSequence = '\u0003' // ASCII escape sequence for CTRL+C-export async function spawnConnectedTerminal(sandbox: e2b.Sandbox) {// Clear local terminal emulator before starting terminal// process.stdout.write('\x1b[2J\x1b[0f')@@ -18,17 +16,17 @@ export async function spawnConnectedTerminal(sandbox: e2b.Sandbox) {process.stdin.setRawMode(true)process.stdout.setEncoding('utf-8')-const terminalSession = await sandbox.pty.create({- onData: data => {- process.stdout.write(data)- },- ...getStdoutSize(),- timeoutMs: 0,- })-+ onData: (data) => {+ process.stdout.write(data)+ },+ ...getStdoutSize(),+ timeoutMs: 0,+ })- const resizeListener = process.stdout.on('resize', () => sandbox.pty.resize(terminalSession.pid, getStdoutSize()))+ const resizeListener = process.stdout.on('resize', () =>+ sandbox.pty.resize(terminalSession.pid, getStdoutSize()),+ )const stdinListener = process.stdin.on('data', async (data) => {if (data.toString() === ctrlCSequence) {process.stdout.write('^C')diff --git a/packages/cli/src/utils/errors.ts b/packages/cli/src/utils/errors.tsindex 5417bbebf..0974f474f 100644--- a/packages/cli/src/utils/errors.ts+++ b/packages/cli/src/utils/errors.ts@@ -1,4 +1,3 @@-/*** Thrown when a request to E2B API occurs.*/@@ -9,8 +8,10 @@ export class E2BRequestError extends Error {}}--export function handleE2BRequestError(err?: { code: number; message: string; }, errMsg?: string) {+export function handleE2BRequestError(+ err?: { code: number; message: string },+ errMsg?: string,+) {if (!err) {return}@@ -34,5 +35,9 @@ export function handleE2BRequestError(err?: { code: number; message: string; },break}- throw new E2BRequestError(`${errMsg && `${errMsg}: `}[${err.code}] ${message && `${message}: `}${err.message ?? 'no message'}`)+ throw new E2BRequestError(+ `${errMsg && `${errMsg}: `}[${err.code}] ${message && `${message}: `}${+ err.message ?? 'no message'+ }`,+ )}diff --git a/packages/cli/src/utils/format.ts b/packages/cli/src/utils/format.tsindex 509343840..9a14df161 100644--- a/packages/cli/src/utils/format.ts+++ b/packages/cli/src/utils/format.ts@@ -8,18 +8,16 @@ import { UserConfig } from '../user'export const primaryColor = '#FFB766'-export function asFormattedConfig(- config: UserConfig,-) {+export function asFormattedConfig(config: UserConfig) {const email = asBold(config.email)- const team = config.teamName ? asBold(config.teamName) : asRed('Log out and log in to get team name')+ const team = config.teamName+ ? asBold(config.teamName)+ : asRed('Log out and log in to get team name')const teamId = asBold(config.teamId || config.defaultTeamId!)return `You are logged in as ${email},\nSelected team: ${team} (${teamId})`}-export function asFormattedTeam(- team: e2b.components['schemas']['Team'],-) {+export function asFormattedTeam(team: e2b.components['schemas']['Team']) {const name = asBold(team.name)const id = asBold(team.teamID)const isDefault = team.isDefault ? asPrimary(' (default team)') : ''@@ -27,7 +25,10 @@ export function asFormattedTeam(}export function asFormattedSandboxTemplate(- template: Pick<e2b.components['schemas']['Template'], 'templateID' | 'aliases'>,+ template: Pick<+ e2b.components['schemas']['Template'],+ 'templateID' | 'aliases'+ >,configLocalPath?: string,) {const aliases = listAliases(template.aliases)@@ -42,7 +43,6 @@ export function asFormattedSandboxTemplate(return `${id}${name}${configPath}`.trim()}-export function asRed(text: string) {return chalk.default.redBright(text)}@@ -92,7 +92,6 @@ export function asHeadline(content: string) {export function withUnderline(content: string) {return chalk.default.underline(content)-}export function listAliases(aliases: string[] | undefined) {@@ -101,7 +100,10 @@ export function listAliases(aliases: string[] | undefined) {}export function asTypescript(code: string) {- return highlight.default(code, { language: 'typescript', ignoreIllegals: true })+ return highlight.default(code, {+ language: 'typescript',+ ignoreIllegals: true,+ })}export function asPython(code: string) {@@ -116,13 +118,17 @@ export const borderStyle = {top: '',bottom: '',left: '',- right: ''+ right: '',} as constconst horizontalPadding = 2const verticalPadding = 1-export function withDelimiter(content: string, title: string, isLast?: boolean) {+export function withDelimiter(+ content: string,+ title: string,+ isLast?: boolean,+) {return boxen.default(content, {borderStyle: {...borderStyle,@@ -138,7 +144,7 @@ export function withDelimiter(content: string, title: string, isLast?: boolean)left: 1,right: 0,},- fullscreen: w => [w, 0],+ fullscreen: (w) => [w, 0],padding: {bottom: isLast ? verticalPadding : 0,left: horizontalPadding,diff --git a/packages/cli/src/utils/templatePrompt.ts b/packages/cli/src/utils/templatePrompt.tsindex 362c4a768..8126afcfa 100644--- a/packages/cli/src/utils/templatePrompt.ts+++ b/packages/cli/src/utils/templatePrompt.ts@@ -14,12 +14,14 @@ export async function getPromptTemplates(message: chalk.default.underline(text),type: 'checkbox',pageSize: 50,- choices: templates.map(e => ({+ choices: templates.map((e) => ({name: asFormattedSandboxTemplate(e),value: e,})),},])- return templatesAnwsers['templates'] as e2b.components['schemas']['Template'][]+ return templatesAnwsers[+ 'templates'+ ] as e2b.components['schemas']['Template'][]}diff --git a/packages/cli/src/utils/templateSort.ts b/packages/cli/src/utils/templateSort.tsindex d497f157d..17dfd2f1f 100644--- a/packages/cli/src/utils/templateSort.ts+++ b/packages/cli/src/utils/templateSort.ts@@ -1,5 +1,7 @@import * as sdk from 'e2b'-export function sortTemplatesAliases<E extends sdk.components['schemas']['Template']['aliases']>(aliases: E) {+export function sortTemplatesAliases<+ E extends sdk.components['schemas']['Template']['aliases'],+>(aliases: E) {aliases?.sort()}diff --git a/packages/cli/src/utils/wait.ts b/packages/cli/src/utils/wait.tsindex d9f64ac82..dd7e92f7b 100644--- a/packages/cli/src/utils/wait.ts+++ b/packages/cli/src/utils/wait.ts@@ -1,3 +1,3 @@export async function wait(ms: number) {- return new Promise(resolve => setTimeout(resolve, ms))+ return new Promise((resolve) => setTimeout(resolve, ms))}