Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Migrate CLI to Beta SDK

Jakub Novak11ab055d39e7
diff --git a/packages/cli/.eslintrc.cjs b/packages/cli/.eslintrc.cjs
index e29f055f3..b7ecaaf3c 100644
--- a/packages/cli/.eslintrc.cjs
+++ b/packages/cli/.eslintrc.cjs
@@ -1,4 +1,4 @@
module.exports = {
root: true,
- extends: '../../.eslintrc.cjs'
+ extends: '../../.eslintrc.cjs',
}
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 541723415..4597695a6 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -43,7 +43,7 @@ FROM ubuntu:22.04
```
3. Run `e2b build` inside the directory with the `Dockerfile` to create and
- build the sandbox template. You will get *_template ID_* that you use for
+ build the sandbox template. You will get _*template ID*_ that you use for
connecting to the sandbox via SDKs and for rebuilding the sandbox template
4. Use the **template ID** that you got during the `e2b build` with the Python
@@ -58,6 +58,6 @@ All commands can be called with a `--path <path-to-dir>` flag that changes the
directory where the command will be called, without the need to call `cd`.
```md
--V, --version Display E2B CLI version
--h, --help display help for command
+-V, --version Display E2B CLI version
+-h, --help display help for command
```
diff --git a/packages/cli/package.json b/packages/cli/package.json
index bc5ee0fd2..45919f8ab 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -55,7 +55,7 @@
"command-exists": "^1.2.9",
"commander": "^11.1.0",
"console-table-printer": "^2.11.2",
- "e2b": "^0.16.2",
+ "e2b": "^0.16.2-beta.44",
"inquirer": "^9.2.12",
"open": "^9.1.0",
"strip-ansi": "^7.1.0",
diff --git a/packages/cli/src/api.ts b/packages/cli/src/api.ts
index e8530630c..4ab0dba09 100644
--- a/packages/cli/src/api.ts
+++ b/packages/cli/src/api.ts
@@ -3,6 +3,7 @@ import * as e2b from 'e2b'
import { getUserConfig } from './user'
import { asBold, asPrimary } from './utils/format'
+import {ConnectionConfig} from 'e2b'
export let apiKey = process.env.E2B_API_KEY
export let accessToken = process.env.E2B_ACCESS_TOKEN
@@ -61,4 +62,8 @@ export function ensureAccessToken() {
}
}
-export const client = new e2b.APIClient()
+
+const userConfig = getUserConfig()
+
+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.ts
index 6c7fa4327..faf74aa48 100644
--- a/packages/cli/src/commands/auth/configure.ts
+++ b/packages/cli/src/commands/auth/configure.ts
@@ -5,10 +5,10 @@ import * as e2b from 'e2b'
import * as path from 'path'
import { USER_CONFIG_PATH } from 'src/user'
-import { client, ensureAccessToken, ensureUserConfig } from 'src/api'
+import {client, connectionConfig, ensureAccessToken, ensureUserConfig} from 'src/api'
import { asFormattedTeam } from '../../utils/format'
+import {handleE2BRequestError} from '../../utils/errors'
-const getTeams = e2b.withAccessToken(client.api.path('/teams').method('get').create())
export const configureCommand = new commander.Command('configure')
.description('configure user')
@@ -23,16 +23,12 @@ export const configureCommand = new commander.Command('configure')
}
const userConfig = ensureUserConfig()
- const accessToken = ensureAccessToken()
- const res = await getTeams(accessToken, {})
- if (!res.ok) {
- const error: e2b.paths['/teams']['get']['responses']['500']['content']['application/json'] = res.data as any
+ ensureAccessToken()
+ const signal = connectionConfig.getSignal()
- throw new Error(
- `Error getting user teams: ${res.statusText}, ${error.message ?? 'no message'
- }`,
- )
- }
+ const res = await client.api.GET('/teams', {signal})
+
+ handleE2BRequestError(res.error, 'Error getting teams')
const team = (await inquirer.default.prompt([
{
@@ -40,7 +36,7 @@ export const configureCommand = new commander.Command('configure')
message: chalk.default.underline('Select team'),
type: 'list',
pageSize: 50,
- choices: res.data.map(team => ({
+ choices: res.data.map((team: e2b.components['schemas']['Team']) => ({
name: asFormattedTeam(team),
value: team,
})),
diff --git a/packages/cli/src/commands/auth/login.ts b/packages/cli/src/commands/auth/login.ts
index 6efa1bd01..7add67126 100644
--- a/packages/cli/src/commands/auth/login.ts
+++ b/packages/cli/src/commands/auth/login.ts
@@ -9,9 +9,8 @@ import * as e2b from 'e2b'
import { pkg } from 'src'
import { DOCS_BASE, getUserConfig, USER_CONFIG_PATH, UserConfig } from 'src/user'
import { asBold, asFormattedConfig, asFormattedError } from 'src/utils/format'
-import { client } from 'src/api'
-
-const getTeams = e2b.withAccessToken(client.api.path('/teams').method('get').create())
+import {client, connectionConfig} from 'src/api'
+import {handleE2BRequestError} from '../../utils/errors'
export const loginCommand = new commander.Command('login')
.description('log in to CLI')
@@ -35,18 +34,12 @@ export const loginCommand = new commander.Command('login')
return
}
- const accessToken = userConfig.accessToken
- const res = await getTeams(accessToken, {})
- if (!res.ok) {
- const error: e2b.paths['/teams']['get']['responses']['500']['content']['application/json'] = res.data as any
+ const signal = connectionConfig.getSignal()
+ const res = await client.api.GET('/teams', {signal})
- throw new Error(
- `Error getting user teams: ${res.statusText}, ${error.message ?? 'no message'
- }`,
- )
- }
+ handleE2BRequestError(res.error, 'Error getting teams')
- const defaultTeam = res.data.find((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'))
process.exit(1)
diff --git a/packages/cli/src/commands/sandbox/connect.ts b/packages/cli/src/commands/sandbox/connect.ts
index ed7547e46..da4c5b5c5 100644
--- a/packages/cli/src/commands/sandbox/connect.ts
+++ b/packages/cli/src/commands/sandbox/connect.ts
@@ -1,4 +1,4 @@
-import * as e2b from 'e2b'
+import { Sandbox } from 'e2b'
import * as commander from 'commander'
import { spawnConnectedTerminal } from 'src/terminal'
@@ -32,14 +32,13 @@ export const connectCommand = new commander.Command('connect')
async function connectToSandbox({ apiKey, sandboxID }: { apiKey: string, sandboxID: string }) {
- const sandbox = await e2b.Sandbox.reconnect({ sandboxID, apiKey })
+ const sandbox = await Sandbox.connect(sandboxID, { apiKey })
- if (sandbox.terminal) {
const { exited } = await spawnConnectedTerminal(
- sandbox.terminal,
+ sandbox,
`Terminal connected to sandbox ${asPrimary(
sandboxID,
- )}\nwith sandbox URL ${asBold(`${sandbox.getProtocol()}://${sandbox.getHostname()}`)}`,
+ )}\nwith sandbox ID ${asBold(`${sandbox.sandboxId}`)}`,
`Disconnecting terminal from sandbox ${asPrimary(
sandboxID,
)}`,
@@ -51,7 +50,4 @@ async function connectToSandbox({ apiKey, sandboxID }: { apiKey: string, sandbox
sandboxID,
)}`,
)
- } else {
- throw new Error('Cannot start terminal - no sandbox')
- }
}
diff --git a/packages/cli/src/commands/sandbox/kill.ts b/packages/cli/src/commands/sandbox/kill.ts
index 25dfded8f..6b9845dad 100644
--- a/packages/cli/src/commands/sandbox/kill.ts
+++ b/packages/cli/src/commands/sandbox/kill.ts
@@ -17,7 +17,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.ts
index d1f49cab9..9558f727f 100644
--- a/packages/cli/src/commands/sandbox/list.ts
+++ b/packages/cli/src/commands/sandbox/list.ts
@@ -2,19 +2,15 @@ import * as tablePrinter from 'console-table-printer'
import * as commander from 'commander'
import * as e2b from 'e2b'
-import { ensureAPIKey, client } from 'src/api'
-
-const listRunningSandboxes = e2b.withAPIKey(
- client.api.path('/sandboxes').method('get').create(),
-)
+import {ensureAPIKey, client, connectionConfig} from 'src/api'
+import {handleE2BRequestError} from '../../utils/errors'
export const listCommand = new commander.Command('list')
.description('list all running sandboxes')
.alias('ls')
.action(async () => {
try {
- const apiKey = ensureAPIKey()
- const sandboxes = await listSandboxes({ apiKey })
+ const sandboxes = await listSandboxes()
if (!sandboxes?.length) {
console.log('No running sandboxes.')
@@ -49,9 +45,13 @@ export const listCommand = new commander.Command('list')
}
})
-export async function listSandboxes({
- apiKey,
-}: { apiKey: string }): Promise<e2b.components['schemas']['RunningSandbox'][]> {
- const response = await listRunningSandboxes(apiKey, {})
- return response.data
+export async function listSandboxes(): Promise<e2b.components['schemas']['RunningSandbox'][]> {
+ ensureAPIKey()
+
+ const signal = connectionConfig.getSignal()
+ const res = await client.api.GET('/sandboxes', {signal})
+
+ handleE2BRequestError(res.error, 'Error getting running sandboxes')
+
+ return res.data
}
diff --git a/packages/cli/src/commands/sandbox/logs.ts b/packages/cli/src/commands/sandbox/logs.ts
index 82b3ed53e..f56220087 100644
--- a/packages/cli/src/commands/sandbox/logs.ts
+++ b/packages/cli/src/commands/sandbox/logs.ts
@@ -3,14 +3,12 @@ import * as e2b from 'e2b'
import * as util from 'util'
import * as chalk from 'chalk'
-import { client, ensureAPIKey } 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'
-const getSandboxLogs = e2b.withAPIKey(
- client.api.path('/sandboxes/{sandboxID}/logs').method('get').create(),
-)
const maxRuntime = 24 * 60 * 60 * 1000 // 24 hours in milliseconds
@@ -18,7 +16,7 @@ function getShortID(sandboxID: string) {
return sandboxID.split('-')[0]
}
-function waitForSandboxEnd(apiKey: string, sandboxID: string) {
+function waitForSandboxEnd(sandboxID: string) {
let isRunning = true
async function monitor() {
@@ -34,7 +32,7 @@ function waitForSandboxEnd(apiKey: string, sandboxID: string) {
break
}
- const response = await listSandboxes({ apiKey })
+ const response = await listSandboxes()
const sandbox = response.find(s => s.sandboxID === getShortID(sandboxID))
if (!sandbox) {
isRunning = false
@@ -134,9 +132,7 @@ export const logsCommand = new commander.Command('logs')
throw new Error(`Invalid log format: ${format}`)
}
- const apiKey = ensureAPIKey()
-
- const getIsRunning = opts?.follow ? waitForSandboxEnd(apiKey, sandboxID) : () => false
+ const getIsRunning = opts?.follow ? waitForSandboxEnd(sandboxID) : () => false
let start: number | undefined
let isFirstRun = true
@@ -146,11 +142,10 @@ export const logsCommand = new commander.Command('logs')
console.log(`\nLogs for sandbox ${asBold(sandboxID)}:`)
}
- const isRunningPromise = listSandboxes({ apiKey }).then(r => r.find(s => s.sandboxID === getShortID(sandboxID))).then(s => !!s)
+ const isRunningPromise = listSandboxes().then(r => r.find(s => s.sandboxID === getShortID(sandboxID))).then(s => !!s)
do {
- try {
- const logs = await listSandboxLogs({ apiKey, sandboxID, start })
+ const logs = await listSandboxLogs({ sandboxID, start })
if (logs.length !== 0 && firstLogsPrinted === false) {
firstLogsPrinted = true
@@ -182,27 +177,6 @@ export const logsCommand = new commander.Command('logs')
// TODO: Use the timestamp from the last log instead of the current time?
start = new Date(lastLog.timestamp).getTime() + 1
}
- } catch (e) {
- if (e instanceof getSandboxLogs.Error) {
- const error = e.getActualType()
- if (error.status === 401) {
- throw new Error(
- `Error getting sandbox logs - (${error.status}) bad request: ${error}`,
- )
- }
- if (error.status === 404) {
- throw new Error(
- `Error getting sandbox logs - (${error.status}) not found: ${error}`,
- )
- }
- if (error.status === 500) {
- throw new Error(
- `Error getting sandbox logs - (${error.status}) server error: ${error}`,
- )
- }
- }
- throw e
- }
await wait(400)
isFirstRun = false
@@ -266,10 +240,24 @@ function printLog(timestamp: string, line: string, allowedLevel: LogLevel | unde
}
export async function listSandboxLogs({
- apiKey,
sandboxID,
start,
-}: { apiKey: string, sandboxID: string, start?: number }): Promise<e2b.components['schemas']['SandboxLog'][]> {
- const response = await getSandboxLogs(apiKey, { sandboxID, start })
- return response.data.logs
+}: { sandboxID: string, start?: number }): Promise<e2b.components['schemas']['SandboxLog'][]> {
+
+ const signal = connectionConfig.getSignal()
+ const res = await client.api.GET('/sandboxes/{sandboxID}/logs', {
+ signal,
+ params: {
+ path: {
+ sandboxID,
+ },
+ query: {
+ start,
+ },
+ },
+ })
+
+ handleE2BRequestError(res.error, 'Error while getting sandbox logs')
+
+ return res.data.logs
}
diff --git a/packages/cli/src/commands/sandbox/spawn.ts b/packages/cli/src/commands/sandbox/spawn.ts
index 65049218f..172f6ac7b 100644
--- a/packages/cli/src/commands/sandbox/spawn.ts
+++ b/packages/cli/src/commands/sandbox/spawn.ts
@@ -80,31 +80,26 @@ export async function connectSandbox({
apiKey: string
template: Pick<e2b.components['schemas']['Template'], 'templateID'>
}) {
- const sandbox = await e2b.Sandbox.create({
+ const sandbox = await e2b.Sandbox.create(template.templateID, {
apiKey,
- template: template.templateID,
})
- if (sandbox.terminal) {
- const { exited } = await spawnConnectedTerminal(
- sandbox.terminal,
- `Terminal connected to sandbox ${asFormattedSandboxTemplate(
- template,
- )}\nwith sandbox URL ${asBold(
- `${sandbox.getProtocol()}://${sandbox.getHostname()}`,
- )}`,
- `Disconnecting terminal from sandbox ${asFormattedSandboxTemplate(
- template,
- )}`,
- )
+ const { exited } = await spawnConnectedTerminal(
+ sandbox,
+ `Terminal connected to sandbox ${asFormattedSandboxTemplate(
+ template,
+ )}\nwith sandbox ID ${asBold(
+ `${sandbox.sandboxId}`,
+ )}`,
+ `Disconnecting terminal from sandbox ${asFormattedSandboxTemplate(
+ template,
+ )}`,
+ )
- await exited
- console.log(
- `Closing terminal connection to sandbox ${asFormattedSandboxTemplate(
- template,
- )}`,
- )
- } else {
- throw new Error('Cannot start terminal - no sandbox')
- }
+ await exited
+ console.log(
+ `Closing terminal connection to sandbox ${asFormattedSandboxTemplate(
+ template,
+ )}`,
+ )
}
diff --git a/packages/cli/src/commands/template/build.ts b/packages/cli/src/commands/template/build.ts
index f4f66bc3d..9748d7671 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 { ensureAccessToken } from 'src/api'
+import {connectionConfig, ensureAccessToken} from 'src/api'
import { getRoot } from 'src/utils/filesystem'
import {
asBold,
@@ -28,30 +28,64 @@ 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'
const templateCheckInterval = 500 // 0.5 sec
-const getTemplate = e2b.withAccessToken(
- client.api
- .path('/templates/{templateID}/builds/{buildID}/status')
- .method('get')
- .create(),
-)
+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: {
+ templateID,
+ buildID,
+ },
+ 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 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
+ }
+ }
+ })
+}
-const requestTemplateBuild = e2b.withAccessToken(
- client.api.path('/templates').method('post').create(),
-)
+async function triggerTemplateBuild(templateID: string, buildID: string) {
+ const res = await client.api
+ .POST('/templates/{templateID}/builds/{buildID}', {
+ params: {
+ path:{
+ templateID,
+ buildID}
+ }
+ })
-const requestTemplateRebuild = e2b.withAccessToken(
- client.api.path('/templates/{templateID}').method('post').create(),
-)
+ handleE2BRequestError(res.error, 'Error triggering template build')
+ return res.data
+}
-const triggerTemplateBuild = e2b.withAccessToken(
- client.api
- .path('/templates/{templateID}/builds/{buildID}')
- .method('post')
- .create(),
-)
export const buildCommand = new commander.Command('build')
.description(
@@ -268,7 +302,7 @@ export const buildCommand = new commander.Command('build')
try {
child_process.execSync(
- `echo "${accessToken}" | docker login docker.${e2b.SANDBOX_DOMAIN} -u _e2b_access_token --password-stdin`,
+ `echo "${accessToken}" | docker login docker.${connectionConfig.domain} -u _e2b_access_token --password-stdin`,
{
stdio: 'inherit',
cwd: root,
@@ -283,7 +317,7 @@ 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.${e2b.SANDBOX_DOMAIN
+ const cmd = `docker build . -f ${dockerfileRelativePath} --pull --platform linux/amd64 -t docker.${connectionConfig.domain
}/e2b/custom-envs/${templateID}:${template.buildID} ${Object.entries(
dockerBuildArgs,
)
@@ -301,7 +335,7 @@ export const buildCommand = new commander.Command('build')
console.log('Pushing docker image...')
child_process.execSync(
- `docker push docker.${e2b.SANDBOX_DOMAIN}/e2b/custom-envs/${templateID}:${template.buildID}`,
+ `docker push docker.${connectionConfig.domain}/e2b/custom-envs/${templateID}:${template.buildID}`,
{
stdio: 'inherit',
cwd: root,
@@ -310,7 +344,7 @@ export const buildCommand = new commander.Command('build')
console.log('Docker image pushed.\n')
console.log('Triggering build...')
- await triggerBuild(accessToken, templateID, template.buildID)
+ await triggerBuild(templateID, template.buildID)
console.log(
`Triggered build for the sandbox template ${asFormattedSandboxTemplate(
@@ -342,46 +376,24 @@ async function waitForBuildFinish(
) {
let logsOffset = 0
- let template: Awaited<ReturnType<typeof getTemplate>> | undefined
+ let template: Awaited<ReturnType<typeof getTemplateBuildLogs>> | undefined
const aliases = name ? [name] : undefined
process.stdout.write('\n')
do {
await wait(templateCheckInterval)
- try {
- template = await getTemplate(accessToken, {
+ template = await getTemplateBuildLogs({
templateID,
logsOffset,
buildID,
})
- } catch (e) {
- if (e instanceof getTemplate.Error) {
- const error = e.getActualType()
- if (error.status === 401) {
- throw new Error(
- `Error getting build info - (${error.status}) bad request: ${error.data.message}`,
- )
- }
- if (error.status === 404) {
- throw new Error(
- `Error getting build info - (${error.status}) not found: ${error.data.message}`,
- )
- }
- if (error.status === 500) {
- throw new Error(
- `Error getting build info - (${error.status}) server error: ${error.data.message}`,
- )
- }
- }
- throw e
- }
- logsOffset += template.data.logs.length
+ logsOffset += template.logs.length
- switch (template.data.status) {
+ switch (template.status) {
case 'building':
- template.data.logs.forEach((line) =>
+ template.logs.forEach((line) =>
process.stdout.write(asBuildLogs(stripAnsi.default(line))),
)
break
@@ -389,7 +401,7 @@ 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.templateID
}")
# Interact with sandbox. Learn more here:
@@ -401,7 +413,7 @@ 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.templateID}' })
// Interact with sandbox. Learn more here:
// https://e2b.dev/docs/sandbox/overview
@@ -441,25 +453,25 @@ Find more here - ${asPrimary(
console.log(
`\n✅ Building sandbox template ${asFormattedSandboxTemplate({
aliases,
- ...template.data,
+ ...template,
})} finished.\n${exampleHeader}\n${exampleUsage}\n`,
)
break
}
case 'error':
- template.data.logs.forEach((line) =>
+ template.logs.forEach((line) =>
process.stdout.write(asBuildLogs(stripAnsi.default(line))),
)
throw new Error(
`\n❌ Building sandbox template ${asFormattedSandboxTemplate({
aliases,
- ...template.data,
+ ...template,
})} failed.\nCheck the logs above for more details or contact us ${asPrimary(
'(https://e2b.dev/docs/getting-help)',
)} to get help.\n`,
)
}
- } while (template.data.status === 'building')
+ } while (template.status === 'building')
}
function loadFile(filePath: string) {
@@ -543,82 +555,20 @@ async function requestBuildTemplate(
> {
let res
if (templateID) {
- res = await requestTemplateRebuild(accessToken, { templateID, ...args })
+ res = await requestTemplateRebuild(templateID, args)
} else {
- res = await requestTemplateBuild(accessToken, args)
+ res = await requestTemplateBuild(args)
}
- if (!res.ok) {
- const error:
- | e2b.paths['/templates']['post']['responses']['401']['content']['application/json']
- | e2b.paths['/templates']['post']['responses']['500']['content']['application/json'] =
- res.data as any
-
- if (error.code === 401) {
- throw new Error(
- `Authentication error: ${res.statusText}, ${error.message ?? 'no message'
- }`,
- )
- }
-
- if (error.code === 404) {
- throw new Error(
- `Sandbox template you want to build ${templateID ? `(${templateID})` : ''
- } not found: ${res.statusText}, ${error.message ?? 'no message'}\n${hasConfig
- ? `This could be caused by ${asLocalRelative(
- configPath,
- )} belonging to a deleted template or a template that you don't own. If so you can delete the ${asLocalRelative(
- configPath,
- )} and start building the template again.`
- : ''
- }`,
- )
- }
-
- if (error.code === 500) {
- throw new Error(
- `Server error: ${res.statusText}, ${error.message ?? 'no message'}`,
- )
- }
-
- throw new Error(
- `API request failed: ${res.statusText}, ${error.message ?? 'no message'}`,
- )
- }
-
- return res.data as any
+ handleE2BRequestError(res.error, 'Error requesting template build')
+ return res.data
}
async function triggerBuild(
- accessToken: string,
templateID: string,
buildID: string,
) {
- const res = await triggerTemplateBuild(accessToken, { templateID, buildID })
-
- if (!res.ok) {
- const error:
- | e2b.paths['/templates/{templateID}/builds/{buildID}']['post']['responses']['401']['content']['application/json']
- | e2b.paths['/templates/{templateID}/builds/{buildID}']['post']['responses']['500']['content']['application/json'] =
- res.data as any
-
- if (error.code === 401) {
- throw new Error(
- `Authentication error: ${res.statusText}, ${error.message ?? 'no message'
- }`,
- )
- }
-
- if (error.code === 500) {
- throw new Error(
- `Server error: ${res.statusText}, ${error.message ?? 'no message'}`,
- )
- }
-
- throw new Error(
- `API request failed: ${res.statusText}, ${error.message ?? 'no message'}`,
- )
- }
+ await triggerTemplateBuild( templateID, buildID )
return
}
diff --git a/packages/cli/src/commands/template/delete.ts b/packages/cli/src/commands/template/delete.ts
index 3bd3379be..eab1215b7 100644
--- a/packages/cli/src/commands/template/delete.ts
+++ b/packages/cli/src/commands/template/delete.ts
@@ -1,6 +1,5 @@
import * as commander from 'commander'
import * as chalk from 'chalk'
-import * as e2b from 'e2b'
import * as fs from 'fs'
import { ensureAccessToken, ensureUserConfig } from 'src/api'
@@ -25,10 +24,21 @@ 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'
-const deleteTemplate = e2b.withAccessToken(
- client.api.path('/templates/{templateID}').method('delete').create(),
-)
+async function deleteTemplate(templateID: string) {
+ const res = await client.api.DELETE('/templates/{templateID}', {
+ params: {
+ path: {
+ templateID,
+ },
+ }
+
+ })
+
+ handleE2BRequestError(res.error, 'Error deleting sandbox template')
+ return
+}
export const deleteCommand = new commander.Command('delete')
.description(`delete sandbox template and ${asLocal(configName)} config`)
@@ -72,9 +82,9 @@ export const deleteCommand = new commander.Command('delete')
})
} else if (opts.select) {
const allTemplates = await listSandboxTemplates({
- accessToken: accessToken,
teamID: opts.team || userConfig.teamId || userConfig.defaultTeamId! // default team ID is here for backwards compatibility
})
+
const selectedTemplates = await getPromptTemplates(
allTemplates,
'Select sandbox templates to delete',
@@ -157,7 +167,7 @@ export const deleteCommand = new commander.Command('delete')
e.configPath,
)}`,
)
- await deleteTemplate(accessToken, { templateID: e.template_id })
+ await deleteTemplate( e.template_id )
if (e.configPath) {
await deleteConfig(e.configPath)
}
diff --git a/packages/cli/src/commands/template/list.ts b/packages/cli/src/commands/template/list.ts
index e33916624..8778263d4 100644
--- a/packages/cli/src/commands/template/list.ts
+++ b/packages/cli/src/commands/template/list.ts
@@ -6,10 +6,7 @@ import { listAliases } from '../../utils/format'
import { sortTemplatesAliases } from 'src/utils/templateSort'
import { client, ensureAccessToken, ensureUserConfig } from 'src/api'
import { teamOption } from '../../options'
-
-const listTemplates = e2b.withAccessToken(
- client.api.path('/templates').method('get').create(),
-)
+import {handleE2BRequestError} from '../../utils/errors'
export const listCommand = new commander.Command('list')
.description('list sandbox templates')
@@ -22,12 +19,11 @@ export const listCommand = new commander.Command('list')
) => {
try {
const userConfig = ensureUserConfig()
- const accessToken = ensureAccessToken()
+ ensureAccessToken()
process.stdout.write('\n')
const templates = await listSandboxTemplates({
- accessToken: accessToken,
- 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) {
@@ -62,8 +58,12 @@ export const listCommand = new commander.Command('list')
})
export async function listSandboxTemplates({
- accessToken, teamID
-}: { accessToken: string, teamID: string }): Promise<e2b.components['schemas']['Template'][]> {
- const templates = await listTemplates(accessToken, {teamID})
+teamID}: { teamID: string }): Promise<e2b.components['schemas']['Template'][]> {
+ const templates = await client.api.GET('/templates', {
+ params: {
+ query: {teamID
+ }}})
+
+ handleE2BRequestError(templates.error, 'Error getting templates')
return templates.data
}
diff --git a/packages/cli/src/terminal.ts b/packages/cli/src/terminal.ts
index f2cde3cc4..494ff5312 100644
--- a/packages/cli/src/terminal.ts
+++ b/packages/cli/src/terminal.ts
@@ -1,6 +1,5 @@
import * as e2b from 'e2b'
-import { createDeferredPromise } from './utils/promise'
function getStdoutSize() {
return {
@@ -10,26 +9,20 @@ function getStdoutSize() {
}
export async function spawnConnectedTerminal(
- terminal: e2b.TerminalManager,
+ sandbox: e2b.Sandbox,
introText: string,
exitText: string,
) {
- const { promise: exited, resolve: onExit } = createDeferredPromise()
-
// Clear local terminal emulator before starting terminal
// process.stdout.write('\x1b[2J\x1b[0f')
console.log(introText)
- const terminalSession = await terminal.start({
- onData: (data: any) => {
+ const terminalSession = await sandbox.pty.create({
+ onData: (data: Uint8Array) => {
process.stdout.write(data)
},
- size: getStdoutSize(),
- onExit,
- envVars: {
- TERM: 'xterm-256color',
- },
+ ...getStdoutSize()
})
process.stdin.setEncoding('utf8')
@@ -38,18 +31,19 @@ export async function spawnConnectedTerminal(
process.stdout.setEncoding('utf8')
const resizeListener = process.stdout.on('resize', () =>
- terminalSession.resize(getStdoutSize()),
+ sandbox.pty.resize(terminalSession.pid, getStdoutSize()),
)
- const stdinListener = process.stdin.on('data', (data) =>
- terminalSession.sendData(data.toString('utf8')),
- )
+ const input = await sandbox.pty.streamInput(terminalSession.pid)
+ const stdinListener = process.stdin.on('data', (data) => input.sendData(data))
- exited.then(() => {
+ const exited = async () => {
+ await terminalSession.wait()
+ await input.stop()
console.log(exitText)
resizeListener.destroy()
stdinListener.destroy()
- })
+ }
return {
kill: terminalSession.kill.bind(terminalSession),
diff --git a/packages/cli/src/utils/errors.ts b/packages/cli/src/utils/errors.ts
new file mode 100644
index 000000000..5417bbebf
--- /dev/null
+++ b/packages/cli/src/utils/errors.ts
@@ -0,0 +1,38 @@
+
+/**
+ * Thrown when a request to E2B API occurs.
+ */
+export class E2BRequestError extends Error {
+ constructor(message: any) {
+ super(message)
+ this.name = 'E2BRequestError'
+ }
+}
+
+
+export function handleE2BRequestError(err?: { code: number; message: string; }, errMsg?: string) {
+ if (!err) {
+ return
+ }
+
+ let message = ''
+ switch (err.code) {
+ case 400:
+ message = 'bad request'
+ break
+ case 401:
+ message = 'unauthorized'
+ break
+ case 403:
+ message = 'forbidden'
+ break
+ case 404:
+ message = 'not found'
+ break
+ case 500:
+ message = 'internal server error'
+ break
+ }
+
+ throw new E2BRequestError(`${errMsg && `${errMsg}: `}[${err.code}] ${message && `${message}: `}${err.message ?? 'no message'}`)
+}
diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.json
index 6658bdec9..1f1388610 100644
--- a/packages/cli/tsconfig.json
+++ b/packages/cli/tsconfig.json
@@ -2,11 +2,7 @@
"compilerOptions": {
"target": "es2022",
"module": "es2022",
- "lib": [
- "es2022",
- "dom",
- "dom.iterable",
- ],
+ "lib": ["es2022", "dom", "dom.iterable"],
"allowJs": true,
"declaration": true,
"declarationMap": true,
@@ -27,13 +23,9 @@
"allowSyntheticDefaultImports": true,
"outDir": "dist",
"baseUrl": ".",
- "rootDirs": [
- "src"
- ],
+ "rootDirs": ["src"],
"paths": {
- "e2b": [
- "../js-sdk/src"
- ]
+ "e2b": ["../js-sdk/src"]
}
}
}
diff --git a/packages/cli/tsup.config.js b/packages/cli/tsup.config.js
index 39596e1c2..34906078b 100644
--- a/packages/cli/tsup.config.js
+++ b/packages/cli/tsup.config.js
@@ -13,7 +13,7 @@ export default defineConfig({
sourcemap: true,
clean: true,
noExternal: Object.keys(packageJSON.dependencies).filter(
- f => !excludedPackages.includes(f)
+ (f) => !excludedPackages.includes(f)
),
esbuildOptions: (options) => {
options.legalComments = 'none'
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index bbc8d4374..5a5c6082b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -266,7 +266,7 @@ importers:
specifier: ^2.11.2
version: 2.11.2
e2b:
- specifier: ^0.16.2
+ specifier: ^0.16.2-beta.44
version: 0.16.2
inquirer:
specifier: ^9.2.12
@@ -6846,11 +6846,6 @@ packages:
engines: {node: '>=14.17'}
hasBin: true
- resolution: {integrity: sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==}
- engines: {node: '>=14.17'}
- hasBin: true
-
resolution: {integrity: sha512-/hreyEujaB0w76zKo6717l3L0o/qEUtRgdvUBvlkhoWeOVMjMuHNHk0BRBzikzuGDqNmPQbg5ifMEqsHLiIUcQ==}
engines: {node: '>=14.17'}
@@ -9821,20 +9816,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- '@typescript-eslint/scope-manager': 6.7.2
- '@typescript-eslint/types': 6.7.2
- '@typescript-eslint/typescript-estree': 6.7.2([email protected])
- '@typescript-eslint/visitor-keys': 6.7.2
- debug: 4.3.4
- eslint: 8.49.0
- optionalDependencies:
- typescript: 5.4.5
- transitivePeerDependencies:
- - supports-color
- optional: true
-
dependencies:
'@typescript-eslint/scope-manager': 6.7.2
@@ -9941,21 +9922,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@typescript-eslint/[email protected]([email protected])':
- dependencies:
- '@typescript-eslint/types': 6.7.2
- '@typescript-eslint/visitor-keys': 6.7.2
- debug: 4.3.4
- globby: 11.1.0
- is-glob: 4.0.3
- semver: 7.5.4
- ts-api-utils: 1.0.3([email protected])
- optionalDependencies:
- typescript: 5.4.5
- transitivePeerDependencies:
- - supports-color
- optional: true
-
'@typescript-eslint/[email protected]([email protected])':
dependencies:
'@typescript-eslint/types': 6.7.2
@@ -11287,7 +11253,7 @@ snapshots:
eslint: 8.49.0
eslint-import-resolver-node: 0.3.9
eslint-import-resolver-typescript: 3.6.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])
- eslint-plugin-import: 2.28.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])
+ eslint-plugin-import: 2.28.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])
eslint-plugin-jsx-a11y: 6.7.1([email protected])
eslint-plugin-react: 7.33.2([email protected])
eslint-plugin-react-hooks: 4.6.0([email protected])
@@ -11311,7 +11277,7 @@ snapshots:
enhanced-resolve: 5.15.0
eslint: 8.49.0
- eslint-plugin-import: 2.28.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])
+ eslint-plugin-import: 2.28.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])
fast-glob: 3.3.1
get-tsconfig: 4.7.0
is-core-module: 2.13.0
@@ -11322,6 +11288,16 @@ snapshots:
- eslint-import-resolver-webpack
- supports-color
+ dependencies:
+ debug: 3.2.7
+ optionalDependencies:
+ '@typescript-eslint/parser': 6.7.2([email protected])([email protected])
+ eslint: 8.49.0
+ eslint-import-resolver-node: 0.3.9
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
debug: 3.2.7
@@ -11333,7 +11309,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
array-includes: 3.1.7
array.prototype.findlastindex: 1.2.3
@@ -11343,7 +11319,7 @@ snapshots:
doctrine: 2.1.0
eslint: 8.49.0
eslint-import-resolver-node: 0.3.9
has: 1.0.3
is-core-module: 2.13.0
is-glob: 4.0.3
@@ -11354,7 +11330,7 @@ snapshots:
semver: 6.3.1
tsconfig-paths: 3.14.2
optionalDependencies:
- '@typescript-eslint/parser': 6.7.2([email protected])([email protected])
+ '@typescript-eslint/parser': 6.7.2([email protected])([email protected])
transitivePeerDependencies:
- eslint-import-resolver-typescript
- eslint-import-resolver-webpack
@@ -14819,11 +14795,6 @@ snapshots:
dependencies:
typescript: 5.1.6
- dependencies:
- typescript: 5.4.5
- optional: true
-
dependencies:
typescript: 5.5.3
@@ -14978,9 +14949,6 @@ snapshots:
- optional: true
-