Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Revert CLI changes

Tomas Valentacd4e059c7030
diff --git a/packages/cli/src/api.ts b/packages/cli/src/api.ts
index 6df8294c7..b080dae6c 100644
--- a/packages/cli/src/api.ts
+++ b/packages/cli/src/api.ts
@@ -1,4 +1,5 @@
import * as boxen from 'boxen'
+import * as e2b from 'e2b'
import { getUserConfig } from './user'
import { asBold, asPrimary } from './utils/format'
@@ -50,3 +51,5 @@ export function ensureAccessToken() {
return accessToken
}
}
+
+export const client = new e2b.APIClient()
diff --git a/packages/cli/src/commands/sandbox/connect.ts b/packages/cli/src/commands/sandbox/connect.ts
index 03af120ee..ed7547e46 100644
--- a/packages/cli/src/commands/sandbox/connect.ts
+++ b/packages/cli/src/commands/sandbox/connect.ts
@@ -1,9 +1,9 @@
-import * as commander from 'commander'
import * as e2b from 'e2b'
+import * as commander from 'commander'
-import { asBold } from 'src/utils/format'
+import { spawnConnectedTerminal } from 'src/terminal'
+import { asBold, asPrimary } from 'src/utils/format'
import { ensureAPIKey } from '../../api'
-import { connectSandbox } from './create'
export const connectCommand = new commander.Command('connect')
.description('connect terminal to already running sandbox')
@@ -20,37 +20,7 @@ export const connectCommand = new commander.Command('connect')
process.exit(1)
}
-
- const sandbox = await e2b.Sandbox.connect(sandboxID, {
- apiKey,
- })
-
- const refresh = setInterval(async () => {
- await sandbox.setTimeout(15_000)
- }, 5_000)
-
- console.log(
- `Created sandbox with ID ${asBold(
- `${sandbox.sandboxID}`,
- )}`,
- )
-
- try {
- await connectSandbox(sandbox)
- } catch (err) {
- await sandbox.kill()
- throw err
- } finally {
- console.log(
- `Closed sandbox with ID ${asBold(
- `${sandbox.sandboxID}`,
- )}`,
- )
-
- clearInterval(refresh)
- }
-
-
+ await connectToSandbox({ apiKey, sandboxID })
// We explicitly call exit because the sandbox is keeping the program alive.
// We also don't want to call sandbox.close because that would disconnect other users from the edit session.
process.exit(0)
@@ -59,3 +29,29 @@ export const connectCommand = new commander.Command('connect')
process.exit(1)
}
})
+
+
+async function connectToSandbox({ apiKey, sandboxID }: { apiKey: string, sandboxID: string }) {
+ const sandbox = await e2b.Sandbox.reconnect({ sandboxID, apiKey })
+
+ if (sandbox.terminal) {
+ const { exited } = await spawnConnectedTerminal(
+ sandbox.terminal,
+ `Terminal connected to sandbox ${asPrimary(
+ sandboxID,
+ )}\nwith sandbox URL ${asBold(`${sandbox.getProtocol()}://${sandbox.getHostname()}`)}`,
+ `Disconnecting terminal from sandbox ${asPrimary(
+ sandboxID,
+ )}`,
+ )
+
+ await exited
+ console.log(
+ `Closing terminal connection to sandbox ${asPrimary(
+ sandboxID,
+ )}`,
+ )
+ } else {
+ throw new Error('Cannot start terminal - no sandbox')
+ }
+}
diff --git a/packages/cli/src/commands/sandbox/index.ts b/packages/cli/src/commands/sandbox/index.ts
index 9ab743ec9..aa2e20b5e 100644
--- a/packages/cli/src/commands/sandbox/index.ts
+++ b/packages/cli/src/commands/sandbox/index.ts
@@ -3,7 +3,7 @@ import * as commander from 'commander'
import { connectCommand } from './connect'
import { listCommand } from './list'
import { killCommand } from './kill'
-import { createCommand } from './create'
+import { spawnCommand } from './spawn'
import { logsCommand } from './logs'
export const sandboxCommand = new commander.Command('sandbox').description('work with sandboxes')
@@ -11,5 +11,5 @@ export const sandboxCommand = new commander.Command('sandbox').description('work
.addCommand(connectCommand)
.addCommand(listCommand)
.addCommand(killCommand)
- .addCommand(createCommand)
+ .addCommand(spawnCommand)
.addCommand(logsCommand)
diff --git a/packages/cli/src/commands/sandbox/kill.ts b/packages/cli/src/commands/sandbox/kill.ts
index 5a7f571d5..25dfded8f 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 56824d8e4..22ba18ad8 100644
--- a/packages/cli/src/commands/sandbox/list.ts
+++ b/packages/cli/src/commands/sandbox/list.ts
@@ -2,7 +2,11 @@ import * as tablePrinter from 'console-table-printer'
import * as commander from 'commander'
import * as e2b from 'e2b'
-import { ensureAPIKey } from 'src/api'
+import { ensureAPIKey, client } from 'src/api'
+
+const listRunningSandboxes = e2b.withAPIKey(
+ client.api.path('/sandboxes').method('get').create(),
+)
export const listCommand = new commander.Command('list')
.description('list all running sandboxes')
@@ -10,7 +14,7 @@ export const listCommand = new commander.Command('list')
.action(async () => {
try {
const apiKey = ensureAPIKey()
- const sandboxes = await e2b.Sandbox.list({ apiKey })
+ const sandboxes = await listSandboxes({ apiKey })
if (!sandboxes?.length) {
console.log('No running sandboxes.')
@@ -27,7 +31,7 @@ export const listCommand = new commander.Command('list')
{ name: 'metadata', alignment: 'left', title: 'Metadata' },
],
disabledColumns: ['clientID'],
- rows: sandboxes.map((sandbox) => ({ ...sandbox, sandboxID: `${sandbox.sandboxID}`, startedAt: new Date(sandbox.startedAt).toLocaleString(), metadata: JSON.stringify(sandbox.metadata) })).sort(
+ rows: sandboxes.map((sandbox) => ({ ...sandbox, sandboxID: `${sandbox.sandboxID}-${sandbox.clientID}`, startedAt: new Date(sandbox.startedAt).toLocaleString(), metadata: JSON.stringify(sandbox.metadata) })).sort(
(a, b) => a.startedAt.localeCompare(b.startedAt) || a.sandboxID.localeCompare(b.sandboxID)
),
colorMap: {
@@ -43,3 +47,10 @@ export const listCommand = new commander.Command('list')
process.exit(1)
}
})
+
+export async function listSandboxes({
+ apiKey,
+}: { apiKey: string }): Promise<e2b.components['schemas']['RunningSandboxes'][]> {
+ const response = await listRunningSandboxes(apiKey, {})
+ return response.data
+}
diff --git a/packages/cli/src/commands/sandbox/logs.ts b/packages/cli/src/commands/sandbox/logs.ts
index 85e0ace9e..89e01408b 100644
--- a/packages/cli/src/commands/sandbox/logs.ts
+++ b/packages/cli/src/commands/sandbox/logs.ts
@@ -273,9 +273,6 @@ export async function listSandboxLogs({
sandboxID,
start,
}: { apiKey: string, sandboxID: string, start?: number }): Promise<e2b.components['schemas']['SandboxLog'][]> {
- const client = new e2b.ApiClient({})
-
-
const response = await getSandboxLogs(apiKey, { sandboxID, start })
return response.data.logs
}
diff --git a/packages/cli/src/commands/sandbox/create.ts b/packages/cli/src/commands/sandbox/spawn.ts
similarity index 50%
rename from packages/cli/src/commands/sandbox/create.ts
rename to packages/cli/src/commands/sandbox/spawn.ts
index 6809ba9d6..65049218f 100644
--- a/packages/cli/src/commands/sandbox/create.ts
+++ b/packages/cli/src/commands/sandbox/spawn.ts
@@ -3,21 +3,22 @@ import * as commander from 'commander'
import * as path from 'path'
import { ensureAPIKey } from 'src/api'
+import { spawnConnectedTerminal } from 'src/terminal'
import { asBold, asFormattedSandboxTemplate } from 'src/utils/format'
import { getRoot } from '../../utils/filesystem'
import { getConfigPath, loadConfig } from '../../config'
import fs from 'fs'
import { configOption, pathOption } from '../../options'
-export const createCommand = new commander.Command('create')
- .description('create sandbox and connect terminal to it')
+export const spawnCommand = new commander.Command('spawn')
+ .description('spawn sandbox and connect terminal to it')
.argument(
'[template]',
- `create and connect to sandbox specified by ${asBold('[template]')}`,
+ `spawn and connect to sandbox specified by ${asBold('[template]')}`,
)
.addOption(pathOption)
.addOption(configOption)
- .alias('cr')
+ .alias('sp')
.action(
async (
template: string | undefined,
@@ -61,36 +62,7 @@ export const createCommand = new commander.Command('create')
process.exit(1)
}
- const sandbox = await e2b.Sandbox.create(templateID, {
- apiKey,
- timeoutMs: 15_000,
- })
-
- const refresh = setInterval(async () => {
- await sandbox.setTimeout(15_000)
- }, 5_000)
-
- console.log(
- `Created sandbox with ID ${asBold(
- `${sandbox.sandboxID}`,
- )}`,
- )
-
- try {
- await connectSandbox(sandbox)
- } catch (err) {
- await sandbox.kill()
- throw err
- } finally {
- console.log(
- `Closed sandbox with ID ${asBold(
- `${sandbox.sandboxID}`,
- )}`,
- )
-
- clearInterval(refresh)
- }
-
+ await connectSandbox({ apiKey, template: { templateID } })
// We explicitly call exit because the sandbox is keeping the program alive.
// We also don't want to call sandbox.close because that would disconnect other users from the edit session.
process.exit(0)
@@ -101,54 +73,38 @@ export const createCommand = new commander.Command('create')
},
)
-export async function connectSandbox(sandbox: e2b.Sandbox) {
- // Clear local terminal emulator before starting terminal
- // process.stdout.write('\x1b[2J\x1b[0f')
-
- process.stdin.setEncoding('binary')
- process.stdin.setRawMode(true)
-
- process.stdout.setEncoding('binary')
-
- const { cols, rows } = getStdoutSize()
-
- const terminal = await sandbox.pty.create({
- cols,
- rows,
- onData: (data) => {
- process.stdout.write(data)
- },
- timeout: 0,
- })
-
- const terminalInput = await sandbox.pty.streamInput(terminal.pid, {
- timeout: 0,
+export async function connectSandbox({
+ apiKey,
+ template,
+}: {
+ apiKey: string
+ template: Pick<e2b.components['schemas']['Template'], 'templateID'>
+}) {
+ const sandbox = await e2b.Sandbox.create({
+ apiKey,
+ template: template.templateID,
})
- const resizeListener = process.stdout.on('resize', () =>
- sandbox.pty.resize(terminal.pid, getStdoutSize()),
- )
-
- const stdinListener = process.stdin.on('data', (data) =>
- terminalInput.sendData(data),
- )
-
- await terminal.wait()
-
- resizeListener.destroy()
- stdinListener.destroy()
-
- console.log(
- `Disconnected terminal from sandbox with ID ${asBold(
- `${sandbox.sandboxID}`,
+ 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,
+ )}`,
)
- } `,
- )
-}
-function getStdoutSize() {
- return {
- cols: process.stdout.columns,
- rows: process.stdout.rows,
+ await exited
+ console.log(
+ `Closing terminal connection to sandbox ${asFormattedSandboxTemplate(
+ template,
+ )}`,
+ )
+ } else {
+ throw new Error('Cannot start terminal - no sandbox')
}
}
diff --git a/packages/cli/src/commands/template/build.ts b/packages/cli/src/commands/template/build.ts
index 62fb69ebd..b89abd9b4 100644
--- a/packages/cli/src/commands/template/build.ts
+++ b/packages/cli/src/commands/template/build.ts
@@ -249,7 +249,7 @@ export const buildCommand = new commander.Command('build')
try {
child_process.execSync(
- `echo "${accessToken}" | docker login docker.${e2b.DOMAIN} -u _e2b_access_token --password-stdin`,
+ `echo "${accessToken}" | docker login docker.${e2b.SANDBOX_DOMAIN} -u _e2b_access_token --password-stdin`,
{
stdio: 'inherit',
cwd: root,
@@ -265,7 +265,7 @@ export const buildCommand = new commander.Command('build')
console.log('Building docker image...')
child_process.execSync(
- `docker build . -f ${dockerfileRelativePath} --platform linux/amd64 -t docker.${e2b.DOMAIN}/e2b/custom-envs/${templateID}:${template.buildID}`,
+ `docker build . -f ${dockerfileRelativePath} --platform linux/amd64 -t docker.${e2b.SANDBOX_DOMAIN}/e2b/custom-envs/${templateID}:${template.buildID}`,
{
stdio: 'inherit',
cwd: root,
@@ -279,7 +279,7 @@ export const buildCommand = new commander.Command('build')
console.log('Pushing docker image...')
child_process.execSync(
- `docker push docker.${e2b.DOMAIN}/e2b/custom-envs/${templateID}:${template.buildID}`,
+ `docker push docker.${e2b.SANDBOX_DOMAIN}/e2b/custom-envs/${templateID}:${template.buildID}`,
{
stdio: 'inherit',
cwd: root,
diff --git a/packages/cli/src/commands/template/list.ts b/packages/cli/src/commands/template/list.ts
index ba7f04012..bd41896e2 100644
--- a/packages/cli/src/commands/template/list.ts
+++ b/packages/cli/src/commands/template/list.ts
@@ -7,6 +7,10 @@ import { listAliases } from '../../utils/format'
import { sortTemplatesAliases } from 'src/utils/templateSort'
import { client } from 'src/api'
+const listTemplates = e2b.withAccessToken(
+ client.api.path('/templates').method('get').create(),
+)
+
export const listCommand = new commander.Command('list')
.description('list sandbox templates')
.alias('ls')
@@ -51,10 +55,6 @@ export const listCommand = new commander.Command('list')
export async function listSandboxTemplates({
accessToken,
}: { accessToken: string }): Promise<e2b.components['schemas']['Template'][]> {
-
- e2b.Sandbox.list()
-
-
const templates = await listTemplates(accessToken, {})
return templates.data
}
diff --git a/packages/cli/src/terminal.ts b/packages/cli/src/terminal.ts
new file mode 100644
index 000000000..f2cde3cc4
--- /dev/null
+++ b/packages/cli/src/terminal.ts
@@ -0,0 +1,58 @@
+import * as e2b from 'e2b'
+
+import { createDeferredPromise } from './utils/promise'
+
+function getStdoutSize() {
+ return {
+ cols: process.stdout.columns,
+ rows: process.stdout.rows,
+ }
+}
+
+export async function spawnConnectedTerminal(
+ terminal: e2b.TerminalManager,
+ 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) => {
+ process.stdout.write(data)
+ },
+ size: getStdoutSize(),
+ onExit,
+ envVars: {
+ TERM: 'xterm-256color',
+ },
+ })
+
+ process.stdin.setEncoding('utf8')
+ process.stdin.setRawMode(true)
+
+ process.stdout.setEncoding('utf8')
+
+ const resizeListener = process.stdout.on('resize', () =>
+ terminalSession.resize(getStdoutSize()),
+ )
+
+ const stdinListener = process.stdin.on('data', (data) =>
+ terminalSession.sendData(data.toString('utf8')),
+ )
+
+ exited.then(() => {
+ console.log(exitText)
+ resizeListener.destroy()
+ stdinListener.destroy()
+ })
+
+ return {
+ kill: terminalSession.kill.bind(terminalSession),
+ exited,
+ }
+}