Skip to content

armgit / E2B

Public Imported from GitHub
0

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

[WIP] Update CLI; Fix pty; Change default timeouts

Tomas Valentace08da3c1173
diff --git a/packages/cli/src/api.ts b/packages/cli/src/api.ts
index b080dae6c..6df8294c7 100644
--- a/packages/cli/src/api.ts
+++ b/packages/cli/src/api.ts
@@ -1,5 +1,4 @@
import * as boxen from 'boxen'
-import * as e2b from 'e2b'
import { getUserConfig } from './user'
import { asBold, asPrimary } from './utils/format'
@@ -51,5 +50,3 @@ 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 ed7547e46..03af120ee 100644
--- a/packages/cli/src/commands/sandbox/connect.ts
+++ b/packages/cli/src/commands/sandbox/connect.ts
@@ -1,9 +1,9 @@
-import * as e2b from 'e2b'
import * as commander from 'commander'
+import * as e2b from 'e2b'
-import { spawnConnectedTerminal } from 'src/terminal'
-import { asBold, asPrimary } from 'src/utils/format'
+import { asBold } 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,7 +20,37 @@ export const connectCommand = new commander.Command('connect')
process.exit(1)
}
- await connectToSandbox({ apiKey, sandboxID })
+
+ 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)
+ }
+
+
// 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)
@@ -29,29 +59,3 @@ 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/spawn.ts b/packages/cli/src/commands/sandbox/create.ts
similarity index 50%
rename from packages/cli/src/commands/sandbox/spawn.ts
rename to packages/cli/src/commands/sandbox/create.ts
index 65049218f..6809ba9d6 100644
--- a/packages/cli/src/commands/sandbox/spawn.ts
+++ b/packages/cli/src/commands/sandbox/create.ts
@@ -3,22 +3,21 @@ 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 spawnCommand = new commander.Command('spawn')
- .description('spawn sandbox and connect terminal to it')
+export const createCommand = new commander.Command('create')
+ .description('create sandbox and connect terminal to it')
.argument(
'[template]',
- `spawn and connect to sandbox specified by ${asBold('[template]')}`,
+ `create and connect to sandbox specified by ${asBold('[template]')}`,
)
.addOption(pathOption)
.addOption(configOption)
- .alias('sp')
+ .alias('cr')
.action(
async (
template: string | undefined,
@@ -62,7 +61,36 @@ export const spawnCommand = new commander.Command('spawn')
process.exit(1)
}
- await connectSandbox({ apiKey, template: { templateID } })
+ 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)
+ }
+
// 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)
@@ -73,38 +101,54 @@ export const spawnCommand = new commander.Command('spawn')
},
)
-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,
+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,
})
- 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 terminalInput = await sandbox.pty.streamInput(terminal.pid, {
+ timeout: 0,
+ })
+
+ 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()
- await exited
- console.log(
- `Closing terminal connection to sandbox ${asFormattedSandboxTemplate(
- template,
- )}`,
+ console.log(
+ `Disconnected terminal from sandbox with ID ${asBold(
+ `${sandbox.sandboxID}`,
)
- } else {
- throw new Error('Cannot start terminal - no sandbox')
+ } `,
+ )
+}
+
+function getStdoutSize() {
+ return {
+ cols: process.stdout.columns,
+ rows: process.stdout.rows,
}
}
diff --git a/packages/cli/src/commands/sandbox/index.ts b/packages/cli/src/commands/sandbox/index.ts
index aa2e20b5e..9ab743ec9 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 { spawnCommand } from './spawn'
+import { createCommand } from './create'
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(spawnCommand)
+ .addCommand(createCommand)
.addCommand(logsCommand)
diff --git a/packages/cli/src/commands/sandbox/kill.ts b/packages/cli/src/commands/sandbox/kill.ts
index 25dfded8f..5a7f571d5 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 22ba18ad8..56824d8e4 100644
--- a/packages/cli/src/commands/sandbox/list.ts
+++ b/packages/cli/src/commands/sandbox/list.ts
@@ -2,11 +2,7 @@ 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 } from 'src/api'
export const listCommand = new commander.Command('list')
.description('list all running sandboxes')
@@ -14,7 +10,7 @@ export const listCommand = new commander.Command('list')
.action(async () => {
try {
const apiKey = ensureAPIKey()
- const sandboxes = await listSandboxes({ apiKey })
+ const sandboxes = await e2b.Sandbox.list({ apiKey })
if (!sandboxes?.length) {
console.log('No running sandboxes.')
@@ -31,7 +27,7 @@ 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(), metadata: JSON.stringify(sandbox.metadata) })).sort(
+ rows: sandboxes.map((sandbox) => ({ ...sandbox, sandboxID: `${sandbox.sandboxID}`, 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: {
@@ -47,10 +43,3 @@ 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 89e01408b..85e0ace9e 100644
--- a/packages/cli/src/commands/sandbox/logs.ts
+++ b/packages/cli/src/commands/sandbox/logs.ts
@@ -273,6 +273,9 @@ 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/template/build.ts b/packages/cli/src/commands/template/build.ts
index b89abd9b4..62fb69ebd 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.SANDBOX_DOMAIN} -u _e2b_access_token --password-stdin`,
+ `echo "${accessToken}" | docker login docker.${e2b.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.SANDBOX_DOMAIN}/e2b/custom-envs/${templateID}:${template.buildID}`,
+ `docker build . -f ${dockerfileRelativePath} --platform linux/amd64 -t docker.${e2b.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.SANDBOX_DOMAIN}/e2b/custom-envs/${templateID}:${template.buildID}`,
+ `docker push docker.${e2b.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 bd41896e2..ba7f04012 100644
--- a/packages/cli/src/commands/template/list.ts
+++ b/packages/cli/src/commands/template/list.ts
@@ -7,10 +7,6 @@ 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')
@@ -55,6 +51,10 @@ 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
deleted file mode 100644
index f2cde3cc4..000000000
--- a/packages/cli/src/terminal.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-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,
- }
-}
diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.ts
index 403a0c271..b09247fcc 100644
--- a/packages/js-sdk/src/connectionConfig.ts
+++ b/packages/js-sdk/src/connectionConfig.ts
@@ -1,8 +1,8 @@
-const DOMAIN = process?.env?.E2B_DOMAIN || 'e2b.dev'
+export const DOMAIN = process?.env?.E2B_DOMAIN || 'e2b.dev'
const DEBUG = (process?.env?.E2B_DEBUG || 'false').toLowerCase() === 'true'
const API_KEY = process?.env?.E2B_API_KEY
const ACCESS_TOKEN = process?.env?.E2B_ACCESS_TOKEN
-const REQUEST_TIMEOUT_MS = 30_000 // 30s
+const REQUEST_TIMEOUT_MS = 15_000 // 15s
export interface ConnectionOpts {
apiKey?: string
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index d3992916f..0d7ceae18 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -4,7 +4,7 @@ export {
} from './api'
export type { components, paths } from './api'
-export { ConnectionConfig, SandboxError } from './connectionConfig'
+export { ConnectionConfig, SandboxError, DOMAIN } from './connectionConfig'
export type { ConnectionOpts, Username } from './connectionConfig'
export type { FilesystemEvent, WatchHandle, FilesystemEventType, } from './sandbox/filesystem/watchHandle'
diff --git a/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts b/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
index 28362ce31..a9f942fe8 100644
--- a/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
+++ b/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
@@ -49,8 +49,6 @@ export class WatchHandle {
async stop() {
this.handleStop()
-
- await this._wait
}
private async* iterateEvents() {
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index e06e6c5d1..576840820 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -24,7 +24,7 @@ export interface SandboxOpts extends ConnectionOpts {
export class Sandbox extends SandboxApi {
protected static readonly defaultTemplate = 'base-v1'
- protected static readonly defaultSandboxTimeoutMs = 60_000
+ protected static readonly defaultSandboxTimeoutMs = 300_000
readonly files: Filesystem
readonly commands: Process
diff --git a/packages/js-sdk/src/sandbox/pty.ts b/packages/js-sdk/src/sandbox/pty.ts
index 7966c6341..87e5853f3 100644
--- a/packages/js-sdk/src/sandbox/pty.ts
+++ b/packages/js-sdk/src/sandbox/pty.ts
@@ -10,7 +10,7 @@ import {
StartResponse,
StreamInputRequest,
} from '../envd/process/process_pb'
-import { ConnectionConfig, ConnectionOpts, defaultUsername } from '../connectionConfig'
+import { ConnectionConfig, ConnectionOpts, defaultUsername, Username } from '../connectionConfig'
import { PartialMessage } from '@bufbuild/protobuf'
import { ProcessHandle } from './process/processHandle'
@@ -19,6 +19,7 @@ export interface PtyCreateOpts extends Pick<ConnectionOpts, 'requestTimeoutMs'>
rows: number
onData: (data: Uint8Array) => (void | Promise<void>)
timeout?: number
+ username?: Username
}
export class Pty {
@@ -41,14 +42,14 @@ export class Pty {
user: {
selector: {
case: 'username',
- value: defaultUsername,
+ value: opts.username ?? defaultUsername,
},
},
process: {
cmd: '/bin/bash',
args: ['-i', '-l'],
envs: {
- 'TERM': 'xterm',
+ 'TERM': 'xterm-256color',
},
},
pty: {
diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.py
index 0a1f86ea5..7d111fe51 100644
--- a/packages/python-sdk/e2b/api/__init__.py
+++ b/packages/python-sdk/e2b/api/__init__.py
@@ -1,10 +1,10 @@
from importlib.metadata import version
-from e2b.connection_config import ConnectionConfig
+from e2b.connection_config import ConnectionConfig, SandboxException
from e2b.api.metadata import default_headers
-class AuthenticationException(Exception):
+class AuthenticationException(SandboxException):
pass
diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.py
index 4a273cf3f..89fd246e9 100644
--- a/packages/python-sdk/e2b/connection_config.py
+++ b/packages/python-sdk/e2b/connection_config.py
@@ -8,7 +8,11 @@ DEBUG = os.getenv("E2B_DEBUG", "false") == "true"
API_KEY = os.getenv("E2B_API_KEY")
ACCESS_TOKEN = os.getenv("E2B_ACCESS_TOKEN")
-REQUEST_TIMEOUT: float = 30 # 30s
+REQUEST_TIMEOUT: float = 15 # 15s
+
+
+class SandboxException(Exception):
+ pass
class ConnectionConfig:
diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.py
index adf3661ac..c38d69210 100644
--- a/packages/python-sdk/e2b/sandbox/main.py
+++ b/packages/python-sdk/e2b/sandbox/main.py
@@ -5,7 +5,7 @@ from typing import Optional, Dict
from e2b.sandbox.filesystem.filesystem import Filesystem
from e2b.sandbox.process.main import Process
from e2b.sandbox.sandbox_api import SandboxApi
-from e2b.connection_config import ConnectionConfig
+from e2b.connection_config import ConnectionConfig, SandboxException
from e2b.envd.api import ENVD_API_FILES_ROUTE
@@ -23,7 +23,7 @@ class Sandbox(SandboxApi):
def __init__(
self,
template: str = "base-v1",
- timeout: int = 60,
+ timeout: int = 300,
metadata: Optional[Dict[str, str]] = None,
api_key: Optional[str] = None,
domain: Optional[str] = None,
@@ -33,6 +33,12 @@ class Sandbox(SandboxApi):
):
super().__init__()
+ if sandbox_id and (metadata or timeout is not None):
+ raise SandboxException(
+ "Cannot set metadata or timeout when connection to an existing sandbox. "
+ "Use Sandbox.connect method instead.",
+ )
+
self._connection_config = ConnectionConfig(
api_key=api_key,
domain=domain,