Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Update JS SDK docstrings

Tomas Valenta7a3dd7c632d6
diff --git a/packages/js-sdk/example.mts b/packages/js-sdk/example.mts
index d75cc1841..041f21f29 100644
--- a/packages/js-sdk/example.mts
+++ b/packages/js-sdk/example.mts
@@ -6,6 +6,6 @@ dotenv.config()
for (let i = 0; i < 10; i++) {
const start = Date.now()
- const sbx = await Sandbox.create({ timeout: 10 })
+ const sbx = await Sandbox.create({ timeoutMs: 10000 })
console.log('time', Date.now() - start)
}
diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.ts
index 0c9c1f07f..6747bca84 100644
--- a/packages/js-sdk/src/api/index.ts
+++ b/packages/js-sdk/src/api/index.ts
@@ -30,15 +30,15 @@ class ApiClient {
if (!opts?.requireApiKey && !config.apiKey) {
throw new AuthenticationError(
'API key is required, please visit https://e2b.dev/docs to get your API key. ' +
- 'You can either set the environment variable `E2B_API_KEY` ' +
- "or you can pass it directly to the sandbox like Sandbox.create({ apiKey: 'e2b_...' })"
+ 'You can either set the environment variable `E2B_API_KEY` ' +
+ "or you can pass it directly to the sandbox like Sandbox.create({ apiKey: 'e2b_...' })"
)
}
if (opts?.requireAccessToken && !config.accessToken) {
throw new AuthenticationError(
'Access token is required, please visit https://e2b.dev/docs to get your access token. ' +
- 'You can set the environment variable `E2B_ACCESS_TOKEN` or pass the `accessToken` in options.'
+ 'You can set the environment variable `E2B_ACCESS_TOKEN` or pass the `accessToken` in options.'
)
}
diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.ts
index defc8f8ca..c57dbfd30 100644
--- a/packages/js-sdk/src/connectionConfig.ts
+++ b/packages/js-sdk/src/connectionConfig.ts
@@ -1,8 +1,8 @@
import { Logger } from './logs'
import { getEnvVar } from './api/metadata'
-const REQUEST_TIMEOUT_MS = 30_000 // 30s
-export const KEEPALIVE_PING_INTERVAL_SEC = 50 // 50s
+const REQUEST_TIMEOUT_MS = 30_000 // 30 seconds
+export const KEEPALIVE_PING_INTERVAL_SEC = 50 // 50 seconds
export const KEEPALIVE_PING_HEADER = 'Keepalive-Ping-Interval'
@@ -10,11 +10,39 @@ export const KEEPALIVE_PING_HEADER = 'Keepalive-Ping-Interval'
* Connection options for requests to the API.
*/
export interface ConnectionOpts {
+ /**
+ * E2B API key to use for authentication.
+ *
+ * @default `E2B_API_KEY` environment variable
+ */
apiKey?: string
+ /**
+ * E2B access token to use for authentication.
+ *
+ * @default `E2B_ACCESS_TOKEN` environment variable
+ */
accessToken?: string
+ /**
+ * Domain to use for the API.
+ *
+ * @default `E2B_DOMAIN` environment variable or `e2b.dev`
+ */
domain?: string
+ /**
+ * If true the SDK starts in the debug mode and **connects to the local envd API server**.
+ *
+ * @default `E2B_DEBUG` environment variable or `false`
+ */
debug?: boolean
+ /**
+ * Timeout for requests to the API in **milliseconds**.
+ *
+ * @default 30_000
+ */
requestTimeoutMs?: number
+ /**
+ * Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, {@link console}.
+ */
logger?: Logger
}
@@ -69,7 +97,7 @@ export class ConnectionConfig {
}
/**
- * Username for the user in the sandbox.
+ * User used for the operation in the sandbox.
*/
export type Username = 'root' | 'user'
diff --git a/packages/js-sdk/src/envd/rpc.ts b/packages/js-sdk/src/envd/rpc.ts
index e4d468191..b654f0df5 100644
--- a/packages/js-sdk/src/envd/rpc.ts
+++ b/packages/js-sdk/src/envd/rpc.ts
@@ -22,7 +22,7 @@ export function handleRpcError(err: unknown): Error {
)
case Code.DeadlineExceeded:
return new TimeoutError(
- `${err.message}: This error is likely due to exceeding 'timeoutMs' — the total time a long running request (like process or directory watch) can be active. It can be modified by passing 'timeoutMs' when making the request. Use '0' to disable the timeout.`
+ `${err.message}: This error is likely due to exceeding 'timeoutMs' — the total time a long running request (like command execution or directory watch) can be active. It can be modified by passing 'timeoutMs' when making the request. Use '0' to disable the timeout.`
)
default:
return new SandboxError(`${err.code}: ${err.message}`)
diff --git a/packages/js-sdk/src/errors.ts b/packages/js-sdk/src/errors.ts
index f3b016596..e571bed40 100644
--- a/packages/js-sdk/src/errors.ts
+++ b/packages/js-sdk/src/errors.ts
@@ -6,9 +6,9 @@ export function formatSandboxTimeoutError(message: string) {
}
/**
- * Thrown when a sandbox error occurs.
- *
* Base class for all sandbox errors.
+ *
+ * Thrown when general sandbox errors occur.
*/
export class SandboxError extends Error {
constructor(message: any) {
@@ -24,7 +24,7 @@ export class SandboxError extends Error {
*
* The [canceled] error type is caused by exceeding request timeout.
*
- * The [deadline_exceeded] error type is caused by exceeding the timeout for process, watch, etc.
+ * The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc.
*
* The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly.
*/
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index 7491d0f45..61541c133 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -22,24 +22,24 @@ export type {
export type { EntryInfo, Filesystem, WatchOpts } from './sandbox/filesystem'
export { FileType } from './sandbox/filesystem'
-export { ProcessExitError } from './sandbox/process/processHandle'
+export { CommandExitError } from './sandbox/commands/commandHandle'
export type {
- ProcessResult,
+ CommandResult,
Stdout,
Stderr,
PtyOutput,
- ProcessHandle,
-} from './sandbox/process/processHandle'
+ CommandHandle,
+} from './sandbox/commands/commandHandle'
export type { SandboxApiOpts } from './sandbox/sandboxApi'
export type {
ProcessInfo,
- ProcessRequestOpts,
- ProcessConnectOpts,
- ProcessStartOpts,
- Process,
+ CommandRequestOpts,
+ CommandConnectOpts,
+ CommandStartOpts,
+ Commands,
Pty,
-} from './sandbox/process'
+} from './sandbox/commands'
export type { SandboxInfo } from './sandbox/sandboxApi'
export type { SandboxOpts } from './sandbox'
diff --git a/packages/js-sdk/src/logs.ts b/packages/js-sdk/src/logs.ts
index a5422dd06..87422b95f 100644
--- a/packages/js-sdk/src/logs.ts
+++ b/packages/js-sdk/src/logs.ts
@@ -2,12 +2,20 @@ import type { Interceptor } from '@connectrpc/connect'
import type { Middleware } from 'openapi-fetch'
/**
- * Logger interface compatible with `console` that can be used in places that accept `Logger`
- * to log messages into the console.
+ * Logger interface compatible with {@link console} used for logging Sandbox messages.
*/
export interface Logger {
+ /**
+ * Debug level logging method.
+ */
debug?: (...args: any[]) => void
+ /**
+ * Info level logging method.
+ */
info?: (...args: any[]) => void
+ /**
+ * Error level logging method.
+ */
error?: (...args: any[]) => void
}
diff --git a/packages/js-sdk/src/sandbox/process/processHandle.ts b/packages/js-sdk/src/sandbox/commands/commandHandle.ts
similarity index 62%
rename from packages/js-sdk/src/sandbox/process/processHandle.ts
rename to packages/js-sdk/src/sandbox/commands/commandHandle.ts
index 13eba08b5..740cd3454 100644
--- a/packages/js-sdk/src/sandbox/process/processHandle.ts
+++ b/packages/js-sdk/src/sandbox/commands/commandHandle.ts
@@ -11,57 +11,92 @@ export type Stderr = Branded<string, 'stderr'>
export type PtyOutput = Branded<Uint8Array, 'pty'>
/**
- * Result of a process execution.
+ * Command execution result.
*/
-export interface ProcessResult {
+export interface CommandResult {
+ /**
+ * Command execution exit code.
+ * `0` if the command finished successfully.
+ */
exitCode: number
+ /**
+ * Error message from command execution if it failed.
+ */
error?: string
+ /**
+ * Command stdout output.
+ */
stdout: string
+ /**
+ * Command stderr output.
+ */
stderr: string
}
/**
- * Error thrown when a process exits with a non-zero exit code.
+ * Error thrown when a command exits with a non-zero exit code.
*/
-export class ProcessExitError extends SandboxError implements ProcessResult {
- constructor(private readonly result: ProcessResult) {
+export class CommandExitError extends SandboxError implements CommandResult {
+ constructor(private readonly result: CommandResult) {
super(result.error)
- this.name = 'ProcessExitError'
+ this.name = 'CommandExitError'
}
+ /**
+ * Command execution exit code.
+ * `0` if the command finished successfully.
+ */
get exitCode() {
return this.result.exitCode
}
+ /**
+ * Error message from command execution.
+ */
get error() {
return this.result.error
}
+ /**
+ * Command execution stdout output.
+ */
get stdout() {
return this.result.stdout
}
+ /**
+ * Command execution stderr output.
+ */
get stderr() {
return this.result.stderr
}
}
/**
- * Represents a process object. It provides methods for waiting for the finish and killing the process.
+ * Command execution handle.
+ *
+ * It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command.
+ *
+ * @property {number} pid process ID of the command.
*/
-export class ProcessHandle
+export class CommandHandle
implements
- Omit<ProcessResult, 'exitCode' | 'error'>,
- Partial<Pick<ProcessResult, 'exitCode' | 'error'>>
+ Omit<CommandResult, 'exitCode' | 'error'>,
+ Partial<Pick<CommandResult, 'exitCode' | 'error'>>
{
private _stdout = ''
private _stderr = ''
- private result?: ProcessResult
+ private result?: CommandResult
private iterationError?: Error
private readonly _wait: Promise<void>
+ /**
+ * @hidden
+ * @internal
+ * @access protected
+ */
constructor(
readonly pid: number,
private readonly handleDisconnect: () => void,
@@ -75,37 +110,41 @@ export class ProcessHandle
}
/**
- * Exit code of the process. It is `undefined` if the process is still running.
+ * Command execution exit code.
+ * `0` if the command finished successfully.
+ *
+ * It is `undefined` if the command is still running.
*/
get exitCode() {
return this.result?.exitCode
}
/**
- * Error message of the process. It is `undefined` if the process is still running.
+ * Error message from command execution.
*/
get error() {
return this.result?.error
}
/**
- * Stderr of the process.
+ * Command execution stderr output.
*/
get stderr() {
return this._stderr
}
/**
- * Stdout of the process.
+ * Command execution stdout output.
*/
get stdout() {
return this._stdout
}
/**
- * Waits for the process to finish and returns the result.
- * If the process exits with a non-zero exit code, it throws a `ProcessExitError`.
- * @returns Process result
+ * Waits for the command to finish and returns the result.
+ * If the command exits with a non-zero exit code, it throws a `CommandExitError`.
+ *
+ * @returns `CommandResult` result of command execution.
*/
async wait() {
await this._wait
@@ -119,25 +158,30 @@ export class ProcessHandle
}
if (this.result.exitCode !== 0) {
- throw new ProcessExitError(this.result)
+ throw new CommandExitError(this.result)
}
return this.result
}
/**
- * Disconnects from the process. It does not kill the process. It only stops receiving events from the process.
+ * Disconnect from the command.
+ *
+ * The command is not killed, but SDK stops receiving events from the command.
+ * You can reconnect to the command using {@link Commands.connect}.
*/
async disconnect() {
this.handleDisconnect()
}
/**
- * Kills the process.
- * @returns Whether the process was killed successfully
+ * Kill the command.
+ * It uses `SIGKILL` signal to kill the command.
+ *
+ * @returns `true` if the command was killed successfully, `false` if the command was not found.
*/
async kill() {
- await this.handleKill()
+ return await this.handleKill()
}
private async *iterateEvents(): AsyncGenerator<
diff --git a/packages/js-sdk/src/sandbox/process/index.ts b/packages/js-sdk/src/sandbox/commands/index.ts
similarity index 58%
rename from packages/js-sdk/src/sandbox/process/index.ts
rename to packages/js-sdk/src/sandbox/commands/index.ts
index 820cc9774..f346f2677 100644
--- a/packages/js-sdk/src/sandbox/process/index.ts
+++ b/packages/js-sdk/src/sandbox/commands/index.ts
@@ -17,50 +17,88 @@ import {
KEEPALIVE_PING_HEADER,
} from '../../connectionConfig'
import { authenticationHeader, handleRpcError } from '../../envd/rpc'
-import { ProcessHandle, ProcessResult } from './processHandle'
+import { CommandHandle, CommandResult } from './commandHandle'
import { handleProcessStartEvent } from '../../envd/api'
export { Pty } from './pty'
/**
- * Options for sending a request to a process.
+ * Options for sending a command request.
*/
-export interface ProcessRequestOpts
- extends Partial<Pick<ConnectionOpts, 'requestTimeoutMs'>> {}
+export interface CommandRequestOpts
+ extends Partial<Pick<ConnectionOpts, 'requestTimeoutMs'>> { }
/**
- * Options for starting a new process.
+ * Options for starting a new command.
*/
-export interface ProcessStartOpts extends ProcessRequestOpts {
+export interface CommandStartOpts extends CommandRequestOpts {
+ /**
+ * If true, starts command in the background and the method returns immediately.
+ * You can use {@link CommandHandle.wait} to wait for the command to finish.
+ */
background?: boolean
+ /**
+ * Working directory for the command.
+ *
+ * @default `HOMEDIR` of the user
+ */
cwd?: string
+ /**
+ * User to run the command as.
+ *
+ * @default `user`
+ */
user?: Username
+ /**
+ * Environment variables used for the command.
+ *
+ * This overrides the default environment variables from `Sandbox` constructor.
+ *
+ * @default `{}`
+ */
envs?: Record<string, string>
+ /**
+ * Callback for command stdout output.
+ */
onStdout?: (data: string) => void | Promise<void>
+ /**
+ * Callback for command stderr output.
+ */
onStderr?: (data: string) => void | Promise<void>
+ /**
+ * Timeout for the command in **milliseconds**.
+ *
+ * @default 60_000 (60 seconds)
+ */
timeoutMs?: number
}
/**
- * Options for connecting to a process.
+ * Options for connecting to a command.
*/
-export type ProcessConnectOpts = Pick<
- ProcessStartOpts,
+export type CommandConnectOpts = Pick<
+ CommandStartOpts,
'onStderr' | 'onStdout' | 'timeoutMs'
> &
- ProcessRequestOpts
+ CommandRequestOpts
/**
- * Process information.
+ * Information about a command, PTY session or start command running in the sandbox as process.
*/
export interface ProcessInfo extends PlainMessage<ProcessConfig> {
+ /**
+ * Process ID.
+ */
pid: number
+ /**
+ * Custom tag used for identifying special commands like start command in the custom template.
+ */
tag?: string
}
/**
- * Manager for starting and interacting with processes in the sandbox.
+ * Module for starting and interacting with commands in the sandbox.
*/
-export class Process {
+export class Commands {
protected readonly rpc: PromiseClient<typeof ProcessService>
private readonly defaultProcessConnectionTimeout = 60_000 // 60 seconds
@@ -73,12 +111,13 @@ export class Process {
}
/**
- * Lists all running processes.
+ * List all running commands and PTY sessions.
*
- * @param opts Options for the request
- * @returns List of running processes
+ * @param opts connection options.
+ *
+ * @returns list of running commands and PTY sessions.
*/
- async list(opts?: ProcessRequestOpts): Promise<ProcessInfo[]> {
+ async list(opts?: CommandRequestOpts): Promise<ProcessInfo[]> {
try {
const res = await this.rpc.list(
{},
@@ -101,16 +140,16 @@ export class Process {
}
/**
- * Sends data to the stdin of a process
- * .
- * @param pid Process ID to send data to. You can get the list of processes using `sandbox.commands.list()`.
- * @param data Data to send to the process
- * @param opts Options for the request
+ * Send data to command stdin.
+ *
+ * @param pid process ID of the command. You can get the list of running commands using {@link Commands.list}.
+ * @param data data to send to the command.
+ * @param opts connection options.
*/
async sendStdin(
pid: number,
data: string,
- opts?: ProcessRequestOpts
+ opts?: CommandRequestOpts
): Promise<void> {
try {
await this.rpc.sendInput(
@@ -138,13 +177,15 @@ export class Process {
}
/**
- * Kills a process.
+ * Kill a running command specified by its process ID.
+ * It uses `SIGKILL` signal to kill the command.
*
- * @param pid Process ID to kill. You can get the list of processes using `sandbox.commands.list()`.
- * @param opts Options for the request
- * @returns `true` if the process was killed, `false` if the process was not found
+ * @param pid process ID of the command. You can get the list of running commands using {@link Commands.list}.
+ * @param opts connection options.
+ *
+ * @returns `true` if the command was killed, `false` if the command was not found.
*/
- async kill(pid: number, opts?: ProcessRequestOpts): Promise<boolean> {
+ async kill(pid: number, opts?: CommandRequestOpts): Promise<boolean> {
try {
await this.rpc.sendSignal(
{
@@ -174,15 +215,18 @@ export class Process {
}
/**
- * Connects to an existing process.
+ * Connect to an existing command.
+ * You can use {@link CommandHandle.wait} to wait for the command to finish and get execution results.
*
- * @param pid Process ID to connect to. You can get the list of processes using `sandbox.commands.list()`.
- * @param opts Options for connecting to the process
+ * @param pid process ID of the command to connect to. You can get the list of running commands using {@link Commands.list}.
+ * @param opts connection options.
+ *
+ * @returns `CommandHandle` handle to interact with the running command.
*/
async connect(
pid: number,
- opts?: ProcessConnectOpts
- ): Promise<ProcessHandle> {
+ opts?: CommandConnectOpts
+ ): Promise<CommandHandle> {
const requestTimeoutMs =
opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
@@ -190,8 +234,8 @@ export class Process {
const reqTimeout = requestTimeoutMs
? setTimeout(() => {
- controller.abort()
- }, requestTimeoutMs)
+ controller.abort()
+ }, requestTimeoutMs)
: undefined
const events = this.rpc.connect(
@@ -217,7 +261,7 @@ export class Process {
clearTimeout(reqTimeout)
- return new ProcessHandle(
+ return new CommandHandle(
pid,
() => controller.abort(),
() => this.kill(pid),
@@ -232,45 +276,43 @@ export class Process {
}
/**
- * Starts a new process without waiting for it to finish.
- * @param cmd Command to execute
- * @param opts Options for starting the process
- * @returns New process
+ * Start a new command and wait until it finishes executing.
+ *
+ * @param cmd command to execute.
+ * @param opts options for starting the command.
+ *
+ * @returns `CommandResult` result of the command execution.
*/
async run(
cmd: string,
- opts?: ProcessStartOpts & { background?: false }
- ): Promise<ProcessResult>
+ opts?: CommandStartOpts & { background?: false }
+ ): Promise<CommandResult>
/**
- * Starts a new process and waits until it finishes.
- * @param cmd Command to execute
- * @param opts Options for starting the process
- * @returns New process
+ * Start a new command in the background.
+ * You can use {@link CommandHandle.wait} to wait for the command to finish and get its result.
+ *
+ * @param cmd command to execute.
+ * @param opts options for starting the command
+ *
+ * @returns `CommandHandle` handle to interact with the running command.
*/
async run(
cmd: string,
- opts?: ProcessStartOpts & { background: true }
- ): Promise<ProcessHandle>
+ opts?: CommandStartOpts & { background: true }
+ ): Promise<CommandHandle>
async run(
cmd: string,
- opts?: ProcessStartOpts & { background?: boolean }
+ opts?: CommandStartOpts & { background?: boolean }
): Promise<unknown> {
const proc = await this.start(cmd, opts)
return opts?.background ? proc : proc.wait()
}
- /**
- * Use `run` instead.
- * @hidden
- * @hide
- * @internal
- * @access protected
- */
private async start(
cmd: string,
- opts?: ProcessStartOpts
- ): Promise<ProcessHandle> {
+ opts?: CommandStartOpts
+ ): Promise<CommandHandle> {
const requestTimeoutMs =
opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
@@ -278,8 +320,8 @@ export class Process {
const reqTimeout = requestTimeoutMs
? setTimeout(() => {
- controller.abort()
- }, requestTimeoutMs)
+ controller.abort()
+ }, requestTimeoutMs)
: undefined
const events = this.rpc.start(
@@ -306,7 +348,7 @@ export class Process {
clearTimeout(reqTimeout)
- return new ProcessHandle(
+ return new CommandHandle(
pid,
() => controller.abort(),
() => this.kill(pid),
diff --git a/packages/js-sdk/src/sandbox/process/pty.ts b/packages/js-sdk/src/sandbox/commands/pty.ts
similarity index 74%
rename from packages/js-sdk/src/sandbox/process/pty.ts
rename to packages/js-sdk/src/sandbox/commands/pty.ts
index aaa8519df..b99e3213d 100644
--- a/packages/js-sdk/src/sandbox/process/pty.ts
+++ b/packages/js-sdk/src/sandbox/commands/pty.ts
@@ -15,23 +15,52 @@ import {
KEEPALIVE_PING_HEADER,
KEEPALIVE_PING_INTERVAL_SEC,
} from '../../connectionConfig'
-import { ProcessHandle } from './processHandle'
+import { CommandHandle } from './commandHandle'
import { authenticationHeader, handleRpcError } from '../../envd/rpc'
import { handleProcessStartEvent } from '../../envd/api'
export interface PtyCreateOpts
extends Pick<ConnectionOpts, 'requestTimeoutMs'> {
+ /**
+ * Number of columns for the PTY.
+ */
cols: number
+ /**
+ * Number of rows for the PTY.
+ */
rows: number
+ /**
+ * Callback to handle PTY data.
+ */
onData: (data: Uint8Array) => void | Promise<void>
+ /**
+ * Timeout for the PTY in **milliseconds**.
+ *
+ * @default 60_000 (60 seconds)
+ */
timeoutMs?: number
+ /**
+ * User to use for the PTY.
+ *
+ * @default `user`
+ */
user?: Username
+ /**
+ * Environment variables for the PTY.
+ *
+ * @default {}
+ */
envs?: Record<string, string>
+ /**
+ * Working directory for the PTY.
+ *
+ * @default `HOMEDIR` of the user.
+ */
cwd?: string
}
/**
- * Manager for starting and interacting with PTY (pseudo-terminal) processes in the sandbox.
+ * Module for interacting with PTYs (pseudo-terminals) in the sandbox.
*/
export class Pty {
private readonly rpc: PromiseClient<typeof ProcessService>
@@ -44,10 +73,11 @@ export class Pty {
}
/**
- * Starts a new process with a PTY (pseudo-terminal).
+ * Create a new PTY (pseudo-terminal).
*
- * @param opts Options for creating the PTY process
- * @returns New process
+ * @param opts options for creating the PTY.
+ *
+ * @returns handle to interact with the PTY.
*/
async create(opts: PtyCreateOpts) {
const requestTimeoutMs =
@@ -90,7 +120,7 @@ export class Pty {
clearTimeout(reqTimeout)
- return new ProcessHandle(
+ return new CommandHandle(
pid,
() => controller.abort(),
() => this.kill(pid),
@@ -105,11 +135,11 @@ export class Pty {
}
/**
- * Sends input to a PTY process.
+ * Send input to a PTY process.
*
- * @param pid Process ID of the PTY process
- * @param data Input data to send
- * @param opts Connection options for the request
+ * @param pid process ID of the PTY.
+ * @param data input data to send to the PTY.
+ * @param opts connection options.
*/
async sendInput(
pid: number,
@@ -142,11 +172,12 @@ export class Pty {
}
/**
- * Resizes a PTY process (changes the number of columns and rows in the terminal).
+ * Resize a PTY.
+ * Call this when the terminal window is resized and the number of columns and rows has changed.
*
- * @param pid Process ID of the PTY process
- * @param size New size of the PTY
- * @param opts Connection options for the request
+ * @param pid process ID of the PTY.
+ * @param size new size of the PTY.
+ * @param opts connection options.
*/
async resize(
pid: number,
@@ -179,11 +210,13 @@ export class Pty {
}
/**
- * Kills a process.
+ * Kill a running PTY specified by process ID.
+ * It uses `SIGKILL` signal to kill the PTY.
*
- * @param pid Process ID to kill
- * @param opts Options for the request
- * @returns `true` if the process was killed, `false` if the process was not found
+ * @param pid process ID of the PTY.
+ * @param opts connection options.
+ *
+ * @returns `true` if the PTY was killed, `false` if the PTY was not found.
*/
async kill(
pid: number,
diff --git a/packages/js-sdk/src/sandbox/filesystem/index.ts b/packages/js-sdk/src/sandbox/filesystem/index.ts
index 146a7c9ee..ed05d0795 100644
--- a/packages/js-sdk/src/sandbox/filesystem/index.ts
+++ b/packages/js-sdk/src/sandbox/filesystem/index.ts
@@ -24,19 +24,34 @@ import { FileType as FsFileType } from '../../envd/filesystem/filesystem_pb'
import { WatchHandle, FilesystemEvent } from './watchHandle'
/**
- * Information about a filesystem object.
+ * Sandbox filesystem object information.
*/
export interface EntryInfo {
+ /**
+ * Name of the filesystem object.
+ */
name: string
+ /**
+ * Type of the filesystem object.
+ */
type?: FileType
+ /**
+ * Path to the filesystem object.
+ */
path: string
}
/**
- * Type of filesystem object.
+ * Sandbox filesystem object type.
*/
export const enum FileType {
+ /**
+ * Filesystem object is a file.
+ */
FILE = 'file',
+ /**
+ * Filesystem object is a directory.
+ */
DIR = 'dir',
}
@@ -50,10 +65,14 @@ function mapFileType(fileType: FsFileType) {
}
/**
- * Options for sending a request to the filesystem.
+ * Options for the sandbox filesystem operations.
*/
export interface FilesystemRequestOpts
extends Partial<Pick<ConnectionOpts, 'requestTimeoutMs'>> {
+ /**
+ * User to use for the operation in the sandbox.
+ * This affects the resolution of relative paths and ownership of the created filesystem objects.
+ */
user?: Username
}
@@ -61,12 +80,21 @@ export interface FilesystemRequestOpts
* Options for watching a directory.
*/
export interface WatchOpts extends FilesystemRequestOpts {
- timeout?: number
- onExit?: (err: Error) => void
+ /**
+ * Timeout for the watch operation in **milliseconds**.
+ * You can pass `0` to disable the timeout.
+ *
+ * @default 60_000 (60 seconds)
+ */
+ timeoutMs?: number
+ /**
+ * Callback to call when the watch operation stops.
+ */
+ onExit?: (err?: Error) => void | Promise<void>
}
/**
- * Manager for interacting with the filesystem in the sandbox.
+ * Module for interacting with the sandbox filesystem.
*/
export class Filesystem {
private readonly rpc: PromiseClient<typeof FilesystemService>
@@ -82,25 +110,61 @@ export class Filesystem {
}
/**
- * Reads a whole file content and returns it in requested format (text by default).
- *
- * @param path Path to the file
- * @param opts Options for the request
- * @param {format} [opts.format] Format of the file content. Default is 'text'.
- * @returns File content in requested format
+ * Read file content and return it as a `string`.
+ *
+ * You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.
+ *
+ * @param path path to the file.
+ * @param opts connection options.
+ * @param [opts.format] format of the file content—`text` by default.
+ *
+ * @returns file content as string
*/
async read(
path: string,
opts?: FilesystemRequestOpts & { format?: 'text' }
): Promise<string>
+ /**
+ * Read file content and return it as a `Uint8Array`.
+ *
+ * You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.
+ *
+ * @param path path to the file.
+ * @param opts connection options.
+ * @param [opts.format] format of the file content—`bytes`.
+ *
+ * @returns file content as `Uint8Array`
+ */
async read(
path: string,
opts?: FilesystemRequestOpts & { format: 'bytes' }
): Promise<Uint8Array>
+ /**
+ * Read file content and return it as a `Blob`.
+ *
+ * You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.
+ *
+ * @param path path to the file.
+ * @param opts connection options.
+ * @param [opts.format] format of the file content—`blob`.
+ *
+ * @returns file content as `Blob`
+ */
async read(
path: string,
opts?: FilesystemRequestOpts & { format: 'blob' }
): Promise<Blob>
+ /**
+ * Read file content and return it as a `ReadableStream`.
+ *
+ * You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.
+ *
+ * @param path path to the file.
+ * @param opts connection options.
+ * @param [opts.format] format of the file content—`stream`.
+ *
+ * @returns file content as `ReadableStream`
+ */
async read(
path: string,
opts?: FilesystemRequestOpts & { format: 'stream' }
@@ -142,15 +206,20 @@ export class Filesystem {
}
/**
- * Writes content to a file on the path.
- * When writing to a file that doesn't exist, the file will get created.
- * When writing to a file that already exists, the file will get overwritten.
- * When writing to a file that's in a directory that doesn't exist, the directory will get created.
+ * Write content to a file.
+ *
+ *
+ * Writing to a file that doesn't exist creates the file.
+ *
+ * Writing to a file that already exists overwrites the file.
+ *
+ * Writing to a file at path that doesn't exist creates the necessary directories.
*
- * @param path Path to a new file. For example '/dirA/dirB/newFile.txt' when creating 'newFile.txt'
- * @param data Data to write to a new file
- * @param opts Options for the request
- * @returns Information about the written file
+ * @param path path to file.
+ * @param data data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`.
+ * @param opts connection options.
+ *
+ * @returns information about the written file
*/
async write(
path: string,
@@ -191,11 +260,12 @@ export class Filesystem {
}
/**
- * Lists entries in a directory.
+ * List entries in a directory.
*
- * @param path Path to the directory
- * @param opts Options for the request
- * @returns List of entries in the directory
+ * @param path path to the directory.
+ * @param opts connection options.
+ *
+ * @returns list of entries in the sandbox filesystem directory.
*/
async list(path: string, opts?: FilesystemRequestOpts): Promise<EntryInfo[]> {
try {
@@ -228,11 +298,12 @@ export class Filesystem {
}
/**
- * Creates a new directory and all directories along the way if needed on the specified pth.
+ * Create a new directory and all directories along the way if needed on the specified path.
*
- * @param path Path to a new directory. For example '/dirA/dirB' when creating 'dirB'.
- * @param opts Options for the request
- * @returns True if the directory was created, false if it already exists
+ * @param path path to a new directory. For example '/dirA/dirB' when creating 'dirB'.
+ * @param opts connection options.
+ *
+ * @returns `true` if the directory was created, `false` if it already exists.
*/
async makeDir(path: string, opts?: FilesystemRequestOpts): Promise<boolean> {
try {
@@ -257,12 +328,13 @@ export class Filesystem {
}
/**
- * Renames a file or directory from one path to another.
+ * Rename a file or directory.
*
- * @param oldPath Path to the file or directory to move
- * @param newPath Path to move the file or directory to
- * @param opts Options for the request
- * @returns Information about the moved object
+ * @param oldPath path to the file or directory to rename.
+ * @param newPath new path for the file or directory.
+ * @param opts connection options.
+ *
+ * @returns information about renamed file or directory.
*/
async rename(
oldPath: string,
@@ -297,9 +369,10 @@ export class Filesystem {
}
/**
- * Removes a file or a directory.
- * @param path Path to a file or a directory
- * @param opts Options for the request
+ * Remove a file or directory.
+ *
+ * @param path path to a file or directory.
+ * @param opts connection options.
*/
async remove(path: string, opts?: FilesystemRequestOpts): Promise<void> {
try {
@@ -316,11 +389,12 @@ export class Filesystem {
}
/**
- * Checks if a file or a directory exists.
+ * Check if a file or a directory exists.
*
- * @param path Path to a file or a directory
- * @param opts Options for the request
- * @returns True if the file or directory exists, false otherwise
+ * @param path path to a file or a directory
+ * @param opts connection options.
+ *
+ * @returns `true` if the file or directory exists, `false` otherwise
*/
async exists(path: string, opts?: FilesystemRequestOpts): Promise<boolean> {
try {
@@ -345,20 +419,18 @@ export class Filesystem {
}
/**
- * Watches directory for filesystem events.
+ * Start watching a directory for filesystem events.
*
- * @param path Path to a directory that will be watched
- * @param onEvent Callback that will be called when an event in the directory occurs
- * @param opts Options for the request
- * @returns New watcher
+ * @param path path to directory to watch.
+ * @param onEvent callback to call when an event in the directory occurs.
+ * @param opts connection options.
+ *
+ * @returns `WatchHandle` object that for stopping watching directory.
*/
async watchDir(
path: string,
onEvent: (event: FilesystemEvent) => void | Promise<void>,
- opts?: FilesystemRequestOpts & {
- timeout?: number
- onExit?: (err?: Error) => void | Promise<void>
- }
+ opts?: WatchOpts,
): Promise<WatchHandle> {
const requestTimeoutMs =
opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
@@ -367,8 +439,8 @@ export class Filesystem {
const reqTimeout = requestTimeoutMs
? setTimeout(() => {
- controller.abort()
- }, requestTimeoutMs)
+ controller.abort()
+ }, requestTimeoutMs)
: undefined
const events = this.rpc.watchDir(
@@ -379,7 +451,7 @@ export class Filesystem {
[KEEPALIVE_PING_HEADER]: KEEPALIVE_PING_INTERVAL_SEC.toString(),
},
signal: controller.signal,
- timeoutMs: opts?.timeout ?? this.defaultWatchTimeout,
+ timeoutMs: opts?.timeoutMs ?? this.defaultWatchTimeout,
}
)
diff --git a/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts b/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
index 5ef32e11f..5d8b0d4a8 100644
--- a/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
+++ b/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
@@ -5,13 +5,28 @@ import {
} from '../../envd/filesystem/filesystem_pb'
/**
- * Type of filesystem event.
+ * Sandbox filesystem event types.
*/
export const enum FilesystemEventType {
+ /**
+ * Filesystem object permissions were changed.
+ */
CHMOD = 'chmod',
+ /**
+ * Filesystem object was created.
+ */
CREATE = 'create',
+ /**
+ * Filesystem object was removed.
+ */
REMOVE = 'remove',
+ /**
+ * Filesystem object was renamed.
+ */
RENAME = 'rename',
+ /**
+ * Filesystem object was written to.
+ */
WRITE = 'write',
}
@@ -34,12 +49,20 @@ function mapEventType(type: EventType) {
* Information about a filesystem event.
*/
export interface FilesystemEvent {
+ /**
+ * Relative path to the filesystem object.
+ */
name: string
+ /**
+ * Filesystem operation event type.
+ */
type: FilesystemEventType
}
/**
- * Handle for watching a directory in the sandbox filesystem. It provides a method to close the watcher.
+ * Handle for watching a directory in the sandbox filesystem.
+ *
+ * Use {@link WatchHandle.stop} to stop watching the directory.
*/
export class WatchHandle {
constructor(
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index 36d13da82..1a56cd26d 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -7,7 +7,7 @@ import {
} from '../connectionConfig'
import { createRpcLogger } from '../logs'
import { Filesystem } from './filesystem'
-import { Process, Pty } from './process'
+import { Commands, Pty } from './commands'
import { SandboxApi } from './sandboxApi'
import { EnvdApiClient, handleEnvdApiError } from '../envd/api'
@@ -15,30 +15,46 @@ import { EnvdApiClient, handleEnvdApiError } from '../envd/api'
* Options for creating a new Sandbox.
*/
export interface SandboxOpts extends ConnectionOpts {
+ /**
+ * Custom metadata for the sandbox.
+ *
+ * @default {}
+ */
metadata?: Record<string, string>
+ /**
+ * Custom environment variables for the sandbox.
+ *
+ * Used when executing commands and code in the sandbox.
+ * Can be overridden with the `envs` argument when executing commands or code.
+ *
+ * @default {}
+ */
envs?: Record<string, string>
+ /**
+ * Timeout for the sandbox in **milliseconds**.
+ *
+ * @default 300_000
+ */
timeoutMs?: number
}
/**
- * E2B cloud sandbox gives your agent a full cloud development environment that's sandboxed.
+ * E2B cloud sandbox is a secure and isolated cloud environment.
*
- * That means:
- * - Access to Linux OS
- * - Using filesystem (create, list, and delete files and dirs)
+ * That allows you to:
+ * - Access Linux OS
+ * - Create, list, and delete files and directories
* - Run commands
- * - Sandboxed - you can run any code
- * - Access to the internet
- *
- * Check usage docs - https://e2b.dev/docs/sandbox/overview
+ * - Run isolated code
+ * - Access the internet
*
- * These cloud sandboxes are meant to be used for agents. Like a sandboxed playgrounds, where the agent can do whatever it wants.
+ * Check docs [here](https://e2b.dev/docs).
*
- * Use the {@link Sandbox.create} method to create a new sandbox.
+ * Use {@link Sandbox.create} method to create a new sandbox.
*
* @example
* ```ts
- * import { Sandbox } from '@e2b/sdk'
+ * import { Sandbox } from 'e2b'
*
* const sandbox = await Sandbox.create()
* ```
@@ -48,15 +64,15 @@ export class Sandbox extends SandboxApi {
protected static readonly defaultSandboxTimeoutMs = 300_000
/**
- * Filesystem module for interacting with the sandbox's filesystem
+ * Module for interacting with the sandbox filesystem
*/
readonly files: Filesystem
/**
- * Commands module for interacting with the sandbox's processes
+ * Module for running commands in the sandbox
*/
- readonly commands: Process
+ readonly commands: Commands
/**
- * PTY module for interacting with the sandbox's pseudo-terminal
+ * Module for interacting with the sandbox pseudo-terminals
*/
readonly pty: Pty
@@ -72,7 +88,7 @@ export class Sandbox extends SandboxApi {
private readonly envdApi: EnvdApiClient
/**
- * Use `Sandbox.create()` instead.
+ * Use {@link Sandbox.create} to create a new Sandbox instead.
*
* @hidden
* @hide
@@ -88,9 +104,8 @@ export class Sandbox extends SandboxApi {
this.sandboxId = opts.sandboxId
this.connectionConfig = new ConnectionConfig(opts)
- this.envdApiUrl = `${
- this.connectionConfig.debug ? 'http' : 'https'
- }://${this.getHost(this.envdPort)}`
+ this.envdApiUrl = `${this.connectionConfig.debug ? 'http' : 'https'
+ }://${this.getHost(this.envdPort)}`
const rpcTransport = createConnectTransport({
baseUrl: this.envdApiUrl,
@@ -107,14 +122,16 @@ export class Sandbox extends SandboxApi {
this.envdApi,
this.connectionConfig
)
- this.commands = new Process(rpcTransport, this.connectionConfig)
+ this.commands = new Commands(rpcTransport, this.connectionConfig)
this.pty = new Pty(rpcTransport, this.connectionConfig)
}
/**
- * Creates a new Sandbox from the default `base` sandbox template.
- * @param opts Connection options
- * @returns New Sandbox
+ * Create a new sandbox from the default `base` sandbox template.
+ *
+ * @param opts connection options.
+ *
+ * @returns sandbox instance for the new sandbox.
*
* @example
* ```ts
@@ -126,6 +143,21 @@ export class Sandbox extends SandboxApi {
this: S,
opts?: SandboxOpts
): Promise<InstanceType<S>>
+
+ /**
+ * Create a new sandbox from the specified sandbox template.
+ *
+ * @param template sandbox template name or ID.
+ * @param opts connection options.
+ *
+ * @returns sandbox instance for the new sandbox.
+ *
+ * @example
+ * ```ts
+ * const sandbox = await Sandbox.create('<template-name-or-id>')
+ * ```
+ * @constructs Sandbox
+ */
static async create<S extends typeof Sandbox>(
this: S,
template: string,
@@ -146,27 +178,30 @@ export class Sandbox extends SandboxApi {
const sandboxId = config.debug
? 'debug_sandbox_id'
: await this.createSandbox(
- template,
- sandboxOpts?.timeoutMs ?? this.defaultSandboxTimeoutMs,
- sandboxOpts
- )
+ template,
+ sandboxOpts?.timeoutMs ?? this.defaultSandboxTimeoutMs,
+ sandboxOpts
+ )
const sbx = new this({ sandboxId, ...config }) as InstanceType<S>
return sbx
}
/**
- * Connects to an existing Sandbox.
- * @param sandboxId Sandbox ID
- * @param opts Connection options
- * @returns Existing Sandbox
+ * Connect to an existing sandbox.
+ * With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc).
+ *
+ * @param sandboxId sandbox ID.
+ * @param opts connection options.
+ *
+ * @returns sandbox instance for the existing sandbox.
*
* @example
* ```ts
* const sandbox = await Sandbox.create()
* const sandboxId = sandbox.sandboxId
*
- * // Another code block
+ * // Connect to the same sandbox.
* const sameSandbox = await Sandbox.connect(sandboxId)
* ```
*/
@@ -182,10 +217,13 @@ export class Sandbox extends SandboxApi {
}
/**
- * Get the hostname for the specified sandbox's port.
+ * Get the host address for the specified sandbox port.
+ * You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket.
+ *
+ * @param port number of the port in the sandbox.
*
- * @param port Port number of a specific port in the sandbox
- * @returns Hostname of the sandbox's port
+ * @returns host address of the sandbox port
+ *
* @example
* ```ts
* const sandbox = await Sandbox.create()
@@ -206,7 +244,8 @@ export class Sandbox extends SandboxApi {
/**
* Check if the sandbox is running.
*
- * @returns `true` if the sandbox is running, `false` otherwise
+ * @returns `true` if the sandbox is running, `false` otherwise.
+ *
* @example
* ```ts
* const sandbox = await Sandbox.create()
@@ -238,13 +277,13 @@ export class Sandbox extends SandboxApi {
}
/**
- * Set the sandbox's timeout, after which the sandbox will be automatically killed.
- * The sandbox can be kept alive for a maximum of 24 hours from the time of creation.
- * If you try to set the timeout to a period, which exceeds the maximum limit, the timeout will be set to the maximum limit.
+ * Set the timeout of the sandbox.
+ * After the timeout expires the sandbox will be automatically killed.
+ *
+ * This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`.
*
- * @param timeoutMs Duration in milliseconds. Must be between 0 and 86400000 milliseconds (24 hours).
- * @param opts Connection options
- * @returns Promise that resolves when the sandbox is kept alive
+ * @param timeoutMs timeout in **milliseconds**.
+ * @param opts connection options.
*/
async setTimeout(
timeoutMs: number,
@@ -264,8 +303,7 @@ export class Sandbox extends SandboxApi {
/**
* Kill the sandbox.
*
- * @param opts Connection options
- * @returns Promise that resolves when the sandbox is killed
+ * @param opts connection options.
*/
async kill(opts?: Pick<SandboxOpts, 'requestTimeoutMs'>) {
if (this.connectionConfig.debug) {
@@ -278,11 +316,12 @@ export class Sandbox extends SandboxApi {
/**
* Get the URL to upload a file to the sandbox.
- * You have to send a POST request to this URL with the file as the field in the form data.
- * You can find the specification for this API at https://github.com/e2b-dev/E2B/blob/main/spec/envd/envd.yaml.
- *
- * @param path Path to the directory where the file will be uploaded, defaults to user's home directory
- * @returns URL to upload the file
+ *
+ * You have to send a POST request to this URL with the file as multipart/form-data.
+ *
+ * @param path the directory where to upload the file, defaults to user's home directory.
+ *
+ * @returns URL for uploading file.
*/
uploadUrl(path?: string) {
return this.fileUrl(path)
@@ -291,19 +330,14 @@ export class Sandbox extends SandboxApi {
/**
* Get the URL to download a file from the sandbox.
*
- * @param path Path to the file
- * @returns URL to download the file
+ * @param path path to the file to download.
+ *
+ * @returns URL for downloading file.
*/
downloadUrl(path: string) {
return this.fileUrl(path)
}
- /**
- * Get the URL to a file in the sandbox.
- *
- * @param path Path to the file
- * @returns URL to the file
- */
private fileUrl(path?: string) {
const url = new URL('/files', this.envdApiUrl)
url.searchParams.set('username', defaultUsername)
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index 684eb98ea..3a8299ced 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -4,12 +4,12 @@ import { compareVersions } from 'compare-versions'
import { TemplateError } from '../errors'
/**
- * Options for request to the sandbox orchestration API.
+ * Options for request to the Sandbox API.
*/
export interface SandboxApiOpts
extends Partial<
Pick<ConnectionOpts, 'apiKey' | 'debug' | 'domain' | 'requestTimeoutMs'>
- > {}
+ > { }
/**
* Information about a sandbox.
@@ -26,7 +26,7 @@ export interface SandboxInfo {
templateId: string
/**
- * Sandbox name.
+ * Template name.
*/
name?: string
@@ -42,13 +42,15 @@ export interface SandboxInfo {
}
export class SandboxApi {
- protected constructor() {}
+ protected constructor() { }
/**
- * Kills sandbox specified by sandbox ID.
+ * Kill sandbox specified by sandbox ID.
*
- * @param sandboxId - Sandbox ID.
- * @param opts - Connection options.
+ * @param sandboxId sandbox ID.
+ * @param opts connection options.
+ *
+ * @returns `true` if the sandbox was found and killed, `false` otherwise.
*/
static async kill(
sandboxId: string,
@@ -78,6 +80,13 @@ export class SandboxApi {
return true
}
+ /**
+ * List all running sandboxes.
+ *
+ * @param opts connection options.
+ *
+ * @returns list of running sandboxes.
+ */
static async list(opts?: SandboxApiOpts): Promise<SandboxInfo[]> {
const config = new ConnectionConfig(opts)
const client = new ApiClient(config)
@@ -105,6 +114,16 @@ export class SandboxApi {
)
}
+ /**
+ * Set the timeout of the specified sandbox.
+ * After the timeout expires the sandbox will be automatically killed.
+ *
+ * This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to {@link Sandbox.setTimeout}.
+ *
+ * @param sandboxId sandbox ID.
+ * @param timeoutMs timeout in **milliseconds**.
+ * @param opts connection options.
+ */
static async setTimeout(
sandboxId: string,
timeoutMs: number,
@@ -167,7 +186,7 @@ export class SandboxApi {
)
throw new TemplateError(
'You need to update the template to use the new SDK. ' +
- 'You can do this by running `e2b template build` in the directory with the template.'
+ 'You can do this by running `e2b template build` in the directory with the template.'
)
}
return this.getSandboxId({