Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Add docstrings to SDKs

Jakub Novak506f70c7b8f4
diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.ts
index 4f1a75a75..0c9c1f07f 100644
--- a/packages/js-sdk/src/api/index.ts
+++ b/packages/js-sdk/src/api/index.ts
@@ -6,7 +6,7 @@ import { ConnectionConfig } from '../connectionConfig'
import { AuthenticationError, SandboxError } from '../errors'
import { createApiLogger } from '../logs'
-export function handleApiError(err?: { code: number; message: string; }) {
+export function handleApiError(err?: { code: number; message: string }) {
if (!err) {
return
}
@@ -14,6 +14,9 @@ export function handleApiError(err?: { code: number; message: string; }) {
return new SandboxError(`${err.code}: ${err.message}`)
}
+/**
+ * Client for interacting with the E2B API.
+ */
class ApiClient {
readonly api: ReturnType<typeof createClient<paths>>
@@ -22,20 +25,20 @@ class ApiClient {
opts: {
requireAccessToken?: boolean
requireApiKey?: boolean
- } = { requireAccessToken: false, requireApiKey: true },
+ } = { requireAccessToken: false, requireApiKey: true }
) {
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.'
)
}
@@ -44,8 +47,10 @@ class ApiClient {
// keepalive: true, // TODO: Return keepalive
headers: {
...defaultHeaders,
- ...config.apiKey && { 'X-API-KEY': config.apiKey },
- ...config.accessToken && { Authorization: `Bearer ${config.accessToken}` },
+ ...(config.apiKey && { 'X-API-KEY': config.apiKey }),
+ ...(config.accessToken && {
+ Authorization: `Bearer ${config.accessToken}`,
+ }),
},
})
diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.ts
index 42f8e591e..defc8f8ca 100644
--- a/packages/js-sdk/src/connectionConfig.ts
+++ b/packages/js-sdk/src/connectionConfig.ts
@@ -1,11 +1,14 @@
import { Logger } from './logs'
import { getEnvVar } from './api/metadata'
-const REQUEST_TIMEOUT_MS = 30_000 // 30s
+const REQUEST_TIMEOUT_MS = 30_000 // 30s
export const KEEPALIVE_PING_INTERVAL_SEC = 50 // 50s
export const KEEPALIVE_PING_HEADER = 'Keepalive-Ping-Interval'
+/**
+ * Connection options for requests to the API.
+ */
export interface ConnectionOpts {
apiKey?: string
accessToken?: string
@@ -15,6 +18,9 @@ export interface ConnectionOpts {
logger?: Logger
}
+/**
+ * Configuration for connecting to the API.
+ */
export class ConnectionConfig {
readonly debug: boolean
readonly domain: string
@@ -34,7 +40,9 @@ export class ConnectionConfig {
this.requestTimeoutMs = opts?.requestTimeoutMs ?? REQUEST_TIMEOUT_MS
this.logger = opts?.logger
- this.apiUrl = this.debug ? 'http://localhost:3000' : `https://api.${this.domain}`
+ this.apiUrl = this.debug
+ ? 'http://localhost:3000'
+ : `https://api.${this.domain}`
}
private static get domain() {
@@ -60,6 +68,9 @@ export class ConnectionConfig {
}
}
+/**
+ * Username for the user in the sandbox.
+ */
export type Username = 'root' | 'user'
export const defaultUsername: Username = 'user'
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index 0425b7097..7491d0f45 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -1,6 +1,4 @@
-export {
- ApiClient,
-} from './api'
+export { ApiClient } from './api'
export type { components, paths } from './api'
export {
@@ -12,21 +10,17 @@ export {
InvalidArgumentError,
TemplateError,
} from './errors'
-export {
- ConnectionConfig,
-} from './connectionConfig'
+export { ConnectionConfig } from './connectionConfig'
export type { Logger } from './logs'
export type { ConnectionOpts, Username } from './connectionConfig'
export { FilesystemEventType } from './sandbox/filesystem/watchHandle'
-export type { FilesystemEvent, WatchHandle } from './sandbox/filesystem/watchHandle'
export type {
- EntryInfo,
- Filesystem,
-} from './sandbox/filesystem'
-export {
- FileType,
-} from './sandbox/filesystem'
+ FilesystemEvent,
+ WatchHandle,
+} from './sandbox/filesystem/watchHandle'
+export type { EntryInfo, Filesystem, WatchOpts } from './sandbox/filesystem'
+export { FileType } from './sandbox/filesystem'
export { ProcessExitError } from './sandbox/process/processHandle'
export type {
@@ -44,10 +38,9 @@ export type {
ProcessConnectOpts,
ProcessStartOpts,
Process,
+ Pty,
} from './sandbox/process'
-export type { Pty } from './sandbox/pty'
-
export type { SandboxInfo } from './sandbox/sandboxApi'
export type { SandboxOpts } from './sandbox'
import { Sandbox } from './sandbox'
diff --git a/packages/js-sdk/src/sandbox/filesystem/index.ts b/packages/js-sdk/src/sandbox/filesystem/index.ts
index a9f3ef838..ccadaacce 100644
--- a/packages/js-sdk/src/sandbox/filesystem/index.ts
+++ b/packages/js-sdk/src/sandbox/filesystem/index.ts
@@ -23,12 +23,18 @@ import { FileType as FsFileType } from '../../envd/filesystem/filesystem_pb'
import { WatchHandle, FilesystemEvent } from './watchHandle'
+/**
+ * Information about a filesystem object.
+ */
export interface EntryInfo {
name: string
type?: FileType
path: string
}
+/**
+ * Type of filesystem object.
+ */
export const enum FileType {
FILE = 'file',
DIR = 'dir',
@@ -43,15 +49,25 @@ function mapFileType(fileType: FsFileType) {
}
}
-export interface FilesystemRequestOpts extends Partial<Pick<ConnectionOpts, 'requestTimeoutMs'>> {
+/**
+ * Options for sending a request to the filesystem.
+ */
+export interface FilesystemRequestOpts
+ extends Partial<Pick<ConnectionOpts, 'requestTimeoutMs'>> {
user?: Username
}
+/**
+ * Options for watching a directory.
+ */
export interface WatchOpts extends FilesystemRequestOpts {
timeout?: number
onExit?: (err: Error) => void
}
+/**
+ * Manager for interacting with the filesystem in the sandbox.
+ */
export class Filesystem {
private readonly rpc: PromiseClient<typeof FilesystemService>
@@ -60,16 +76,41 @@ export class Filesystem {
constructor(
transport: Transport,
private readonly envdApi: EnvdApiClient,
- private readonly connectionConfig: ConnectionConfig,
+ private readonly connectionConfig: ConnectionConfig
) {
this.rpc = createPromiseClient(FilesystemService, transport)
}
- async read(path: string, opts?: FilesystemRequestOpts & { format?: 'text' }): Promise<string>
- async read(path: string, opts?: FilesystemRequestOpts & { format: 'bytes' }): Promise<Uint8Array>
- async read(path: string, opts?: FilesystemRequestOpts & { format: 'blob' }): Promise<Blob>
- async read(path: string, opts?: FilesystemRequestOpts & { format: 'stream' }): Promise<ReadableStream<Uint8Array>>
- async read(path: string, opts?: FilesystemRequestOpts & { format?: 'text' | 'stream' | 'bytes' | 'blob' }): Promise<unknown> {
+ /**
+ * 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
+ */
+ async read(
+ path: string,
+ opts?: FilesystemRequestOpts & { format?: 'text' }
+ ): Promise<string>
+ async read(
+ path: string,
+ opts?: FilesystemRequestOpts & { format: 'bytes' }
+ ): Promise<Uint8Array>
+ async read(
+ path: string,
+ opts?: FilesystemRequestOpts & { format: 'blob' }
+ ): Promise<Blob>
+ async read(
+ path: string,
+ opts?: FilesystemRequestOpts & { format: 'stream' }
+ ): Promise<ReadableStream<Uint8Array>>
+ async read(
+ path: string,
+ opts?: FilesystemRequestOpts & {
+ format?: 'text' | 'stream' | 'bytes' | 'blob'
+ }
+ ): Promise<unknown> {
const format = opts?.format ?? 'text'
const res = await this.envdApi.api.GET('/files', {
@@ -95,7 +136,22 @@ export class Filesystem {
return res.data
}
- async write(path: string, data: string | ArrayBuffer | Blob | ReadableStream, opts?: FilesystemRequestOpts): Promise<EntryInfo> {
+ /**
+ * 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, you'll get an error.
+ *
+ * @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
+ */
+ async write(
+ path: string,
+ data: string | ArrayBuffer | Blob | ReadableStream,
+ opts?: FilesystemRequestOpts
+ ): Promise<EntryInfo> {
const blob = await new Response(data).blob()
const res = await this.envdApi.api.POST('/files', {
@@ -129,12 +185,22 @@ export class Filesystem {
return files[0] as EntryInfo
}
+ /**
+ * Lists entries in a directory.
+ *
+ * @param path Path to the directory
+ * @param opts Options for the request
+ * @returns List of entries in the directory
+ */
async list(path: string, opts?: FilesystemRequestOpts): Promise<EntryInfo[]> {
try {
- const res = await this.rpc.listDir({ path }, {
- headers: authenticationHeader(opts?.user),
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
- })
+ const res = await this.rpc.listDir(
+ { path },
+ {
+ headers: authenticationHeader(opts?.user),
+ signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ }
+ )
const entries: EntryInfo[] = []
@@ -156,12 +222,22 @@ export class Filesystem {
}
}
+ /**
+ * Creates a new directory and all directories along the way if needed on the specified pth.
+ *
+ * @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
+ */
async makeDir(path: string, opts?: FilesystemRequestOpts): Promise<boolean> {
try {
- await this.rpc.makeDir({ path }, {
- headers: authenticationHeader(opts?.user),
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
- })
+ await this.rpc.makeDir(
+ { path },
+ {
+ headers: authenticationHeader(opts?.user),
+ signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ }
+ )
return true
} catch (err) {
@@ -175,15 +251,30 @@ export class Filesystem {
}
}
- async rename(oldPath: string, newPath: string, opts?: FilesystemRequestOpts): Promise<EntryInfo> {
+ /**
+ * Renames a file or directory from one path to another.
+ *
+ * @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
+ */
+ async rename(
+ oldPath: string,
+ newPath: string,
+ opts?: FilesystemRequestOpts
+ ): Promise<EntryInfo> {
try {
- const res = await this.rpc.move({
- source: oldPath,
- destination: newPath,
- }, {
- headers: authenticationHeader(opts?.user),
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
- })
+ const res = await this.rpc.move(
+ {
+ source: oldPath,
+ destination: newPath,
+ },
+ {
+ headers: authenticationHeader(opts?.user),
+ signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ }
+ )
const entry = res.entry
if (!entry) {
@@ -200,23 +291,41 @@ export class Filesystem {
}
}
+ /**
+ * Removes a file or a directory.
+ * @param path Path to a file or a directory
+ * @param opts Options for the request
+ */
async remove(path: string, opts?: FilesystemRequestOpts): Promise<void> {
try {
- await this.rpc.remove({ path }, {
- headers: authenticationHeader(opts?.user),
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
- })
+ await this.rpc.remove(
+ { path },
+ {
+ headers: authenticationHeader(opts?.user),
+ signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ }
+ )
} catch (err) {
throw handleRpcError(err)
}
}
+ /**
+ * Checks 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
+ */
async exists(path: string, opts?: FilesystemRequestOpts): Promise<boolean> {
try {
- await this.rpc.stat({ path }, {
- headers: authenticationHeader(opts?.user),
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
- })
+ await this.rpc.stat(
+ { path },
+ {
+ headers: authenticationHeader(opts?.user),
+ signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ }
+ )
return true
} catch (err) {
@@ -230,29 +339,44 @@ export class Filesystem {
}
}
+ /**
+ * Watches 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
+ */
async watch(
path: string,
onEvent: (event: FilesystemEvent) => void | Promise<void>,
- opts?: FilesystemRequestOpts & { timeout?: number, onExit?: (err?: Error) => void | Promise<void> },
+ opts?: FilesystemRequestOpts & {
+ timeout?: number
+ onExit?: (err?: Error) => void | Promise<void>
+ }
): Promise<WatchHandle> {
- const requestTimeoutMs = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
+ const requestTimeoutMs =
+ opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
const controller = new AbortController()
const reqTimeout = requestTimeoutMs
? setTimeout(() => {
- controller.abort()
- }, requestTimeoutMs)
+ controller.abort()
+ }, requestTimeoutMs)
: undefined
- const events = this.rpc.watchDir({ path }, {
- headers: {
- ...authenticationHeader(opts?.user),
- [KEEPALIVE_PING_HEADER]: KEEPALIVE_PING_INTERVAL_SEC.toString(),
- },
- signal: controller.signal,
- timeoutMs: opts?.timeout ?? this.defaultWatchTimeout,
- })
+ const events = this.rpc.watchDir(
+ { path },
+ {
+ headers: {
+ ...authenticationHeader(opts?.user),
+ [KEEPALIVE_PING_HEADER]: KEEPALIVE_PING_INTERVAL_SEC.toString(),
+ },
+ signal: controller.signal,
+ timeoutMs: opts?.timeout ?? this.defaultWatchTimeout,
+ }
+ )
try {
await handleWatchDirStartEvent(events)
@@ -263,7 +387,7 @@ export class Filesystem {
() => controller.abort(),
events,
onEvent,
- opts?.onExit,
+ opts?.onExit
)
} catch (err) {
throw handleRpcError(err)
diff --git a/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts b/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
index b97446bc4..71f3091b5 100644
--- a/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
+++ b/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
@@ -4,6 +4,9 @@ import {
WatchDirResponse,
} from '../../envd/filesystem/filesystem_pb'
+/**
+ * Type of filesystem event.
+ */
export const enum FilesystemEventType {
CHMOD = 'chmod',
CREATE = 'create',
@@ -27,26 +30,35 @@ function mapEventType(type: EventType) {
}
}
+/**
+ * Information about a filesystem event.
+ */
export interface FilesystemEvent {
name: string
type: FilesystemEventType
}
+/**
+ * Handle for watching a directory in the sandbox filesystem. It provides a method to close the watcher.
+ */
export class WatchHandle {
constructor(
private readonly handleStop: () => void,
private readonly events: AsyncIterable<WatchDirResponse>,
private readonly onEvent?: (event: FilesystemEvent) => void | Promise<void>,
- private readonly onExit?: (err?: Error) => void | Promise<void>,
+ private readonly onExit?: (err?: Error) => void | Promise<void>
) {
this.handleEvents()
}
+ /**
+ * Stop watching the directory.
+ */
async close() {
this.handleStop()
}
- private async* iterateEvents() {
+ private async *iterateEvents() {
try {
for await (const event of this.events) {
switch (event.event.case) {
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index f5021d4fa..36d13da82 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -1,27 +1,68 @@
import { createConnectTransport } from '@connectrpc/connect-web'
-import { ConnectionOpts, ConnectionConfig, defaultUsername } from '../connectionConfig'
+import {
+ ConnectionOpts,
+ ConnectionConfig,
+ defaultUsername,
+} from '../connectionConfig'
import { createRpcLogger } from '../logs'
import { Filesystem } from './filesystem'
-import { Process } from './process'
-import { Pty } from './pty'
+import { Process, Pty } from './process'
import { SandboxApi } from './sandboxApi'
import { EnvdApiClient, handleEnvdApiError } from '../envd/api'
+/**
+ * Options for creating a new Sandbox.
+ */
export interface SandboxOpts extends ConnectionOpts {
metadata?: Record<string, string>
envs?: Record<string, string>
timeoutMs?: number
}
+/**
+ * E2B cloud sandbox gives your agent a full cloud development environment that's sandboxed.
+ *
+ * That means:
+ * - Access to Linux OS
+ * - Using filesystem (create, list, and delete files and dirs)
+ * - Run commands
+ * - Sandboxed - you can run any code
+ * - Access to the internet
+ *
+ * Check usage docs - https://e2b.dev/docs/sandbox/overview
+ *
+ * These cloud sandboxes are meant to be used for agents. Like a sandboxed playgrounds, where the agent can do whatever it wants.
+ *
+ * Use the {@link Sandbox.create} method to create a new sandbox.
+ *
+ * @example
+ * ```ts
+ * import { Sandbox } from '@e2b/sdk'
+ *
+ * const sandbox = await Sandbox.create()
+ * ```
+ */
export class Sandbox extends SandboxApi {
protected static readonly defaultTemplate: string = 'base'
protected static readonly defaultSandboxTimeoutMs = 300_000
+ /**
+ * Filesystem module for interacting with the sandbox's filesystem
+ */
readonly files: Filesystem
+ /**
+ * Commands module for interacting with the sandbox's processes
+ */
readonly commands: Process
+ /**
+ * PTY module for interacting with the sandbox's pseudo-terminal
+ */
readonly pty: Pty
+ /**
+ * Unique identifier of the sandbox.
+ */
readonly sandboxId: string
protected readonly envdPort = 49983
@@ -30,12 +71,26 @@ export class Sandbox extends SandboxApi {
private readonly envdApiUrl: string
private readonly envdApi: EnvdApiClient
- constructor(opts: Omit<SandboxOpts, 'timeoutMs' | 'envs' | 'metadata'> & { sandboxId: string }) {
+ /**
+ * Use `Sandbox.create()` instead.
+ *
+ * @hidden
+ * @hide
+ * @internal
+ * @access protected
+ */
+ constructor(
+ opts: Omit<SandboxOpts, 'timeoutMs' | 'envs' | 'metadata'> & {
+ sandboxId: string
+ }
+ ) {
super()
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,
@@ -43,36 +98,103 @@ export class Sandbox extends SandboxApi {
interceptors: opts?.logger ? [createRpcLogger(opts.logger)] : undefined,
})
- this.envdApi = new EnvdApiClient({ apiUrl: this.envdApiUrl, logger: opts?.logger })
- this.files = new Filesystem(rpcTransport, this.envdApi, this.connectionConfig)
+ this.envdApi = new EnvdApiClient({
+ apiUrl: this.envdApiUrl,
+ logger: opts?.logger,
+ })
+ this.files = new Filesystem(
+ rpcTransport,
+ this.envdApi,
+ this.connectionConfig
+ )
this.commands = new Process(rpcTransport, this.connectionConfig)
this.pty = new Pty(rpcTransport, this.connectionConfig)
}
- static async create<S extends typeof Sandbox>(this: S, opts?: SandboxOpts): Promise<InstanceType<S>>
- static async create<S extends typeof Sandbox>(this: S, template: string, opts?: SandboxOpts): Promise<InstanceType<S>>
- static async create<S extends typeof Sandbox>(this: S, templateOrOpts?: SandboxOpts | string, opts?: SandboxOpts): Promise<InstanceType<S>> {
- const { template, sandboxOpts } = typeof templateOrOpts === 'string'
- ? { template: templateOrOpts, sandboxOpts: opts }
- : { template: this.defaultTemplate, sandboxOpts: templateOrOpts }
+ /**
+ * Creates a new Sandbox from the default `base` sandbox template.
+ * @param opts Connection options
+ * @returns New Sandbox
+ *
+ * @example
+ * ```ts
+ * const sandbox = await Sandbox.create()
+ * ```
+ * @constructs Sandbox
+ */
+ static async create<S extends typeof Sandbox>(
+ this: S,
+ opts?: SandboxOpts
+ ): Promise<InstanceType<S>>
+ static async create<S extends typeof Sandbox>(
+ this: S,
+ template: string,
+ opts?: SandboxOpts
+ ): Promise<InstanceType<S>>
+ static async create<S extends typeof Sandbox>(
+ this: S,
+ templateOrOpts?: SandboxOpts | string,
+ opts?: SandboxOpts
+ ): Promise<InstanceType<S>> {
+ const { template, sandboxOpts } =
+ typeof templateOrOpts === 'string'
+ ? { template: templateOrOpts, sandboxOpts: opts }
+ : { template: this.defaultTemplate, sandboxOpts: templateOrOpts }
const config = new ConnectionConfig(sandboxOpts)
const sandboxId = config.debug
? 'debug_sandbox_id'
- : await this.createSandbox(template, sandboxOpts?.timeoutMs ?? this.defaultSandboxTimeoutMs, sandboxOpts)
+ : await this.createSandbox(
+ template,
+ sandboxOpts?.timeoutMs ?? this.defaultSandboxTimeoutMs,
+ sandboxOpts
+ )
const sbx = new this({ sandboxId, ...config }) as InstanceType<S>
return sbx
}
- static async connect<S extends typeof Sandbox>(this: S, sandboxId: string, opts?: Omit<SandboxOpts, 'metadata' | 'envs' | 'timeoutMs'>): Promise<InstanceType<S>> {
+ /**
+ * Connects to an existing Sandbox.
+ * @param sandboxId Sandbox ID
+ * @param opts Connection options
+ * @returns Existing Sandbox
+ *
+ * @example
+ * ```ts
+ * const sandbox = await Sandbox.create()
+ * const sandboxId = sandbox.sandboxId
+ *
+ * // Another code block
+ * const sameSandbox = await Sandbox.connect(sandboxId)
+ * ```
+ */
+ static async connect<S extends typeof Sandbox>(
+ this: S,
+ sandboxId: string,
+ opts?: Omit<SandboxOpts, 'metadata' | 'envs' | 'timeoutMs'>
+ ): Promise<InstanceType<S>> {
const config = new ConnectionConfig(opts)
const sbx = new this({ sandboxId, ...config }) as InstanceType<S>
return sbx
}
+ /**
+ * Get the hostname for the specified sandbox's port.
+ *
+ * @param port Port number of a specific port in the sandbox
+ * @returns Hostname of the sandbox's port
+ * @example
+ * ```ts
+ * const sandbox = await Sandbox.create()
+ * // Start an HTTP server
+ * await sandbox.commands.exec('python3 -m http.server 3000')
+ * // Get the hostname of the HTTP server
+ * const serverURL = sandbox.getHost(3000)
+ * ``
+ */
getHost(port: number) {
if (this.connectionConfig.debug) {
return `localhost:${port}`
@@ -81,7 +203,22 @@ export class Sandbox extends SandboxApi {
return `${port}-${this.sandboxId}.${this.connectionConfig.domain}`
}
- async isRunning(opts?: Pick<ConnectionOpts, 'requestTimeoutMs'>): Promise<boolean> {
+ /**
+ * Check if the sandbox is running.
+ *
+ * @returns `true` if the sandbox is running, `false` otherwise
+ * @example
+ * ```ts
+ * const sandbox = await Sandbox.create()
+ * await sandbox.isRunning() // Returns true
+ *
+ * await sandbox.kill()
+ * await sandbox.isRunning() // Returns false
+ * ```
+ */
+ async isRunning(
+ opts?: Pick<ConnectionOpts, 'requestTimeoutMs'>
+ ): Promise<boolean> {
const signal = this.connectionConfig.getSignal(opts?.requestTimeoutMs)
const res = await this.envdApi.api.GET('/health', {
@@ -100,15 +237,36 @@ export class Sandbox extends SandboxApi {
return true
}
- async setTimeout(timeoutMs: number, opts?: Pick<SandboxOpts, 'requestTimeoutMs'>) {
+ /**
+ * 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.
+ *
+ * @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
+ */
+ async setTimeout(
+ timeoutMs: number,
+ opts?: Pick<SandboxOpts, 'requestTimeoutMs'>
+ ) {
if (this.connectionConfig.debug) {
// Skip timeout in debug mode
return
}
- await Sandbox.setTimeout(this.sandboxId, timeoutMs, { ...this.connectionConfig, ...opts })
+ await Sandbox.setTimeout(this.sandboxId, timeoutMs, {
+ ...this.connectionConfig,
+ ...opts,
+ })
}
+ /**
+ * Kill the sandbox.
+ *
+ * @param opts Connection options
+ * @returns Promise that resolves when the sandbox is killed
+ */
async kill(opts?: Pick<SandboxOpts, 'requestTimeoutMs'>) {
if (this.connectionConfig.debug) {
// Skip killing in debug mode
@@ -118,14 +276,34 @@ export class Sandbox extends SandboxApi {
await Sandbox.kill(this.sandboxId, { ...this.connectionConfig, ...opts })
}
+ /**
+ * 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
+ */
uploadUrl(path?: string) {
return this.fileUrl(path)
}
+ /**
+ * Get the URL to download a file from the sandbox.
+ *
+ * @param path Path to the file
+ * @returns URL to download the 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/process/index.ts b/packages/js-sdk/src/sandbox/process/index.ts
index e21f571eb..820cc9774 100644
--- a/packages/js-sdk/src/sandbox/process/index.ts
+++ b/packages/js-sdk/src/sandbox/process/index.ts
@@ -8,34 +8,58 @@ import {
import { PlainMessage } from '@bufbuild/protobuf'
import { Process as ProcessService } from '../../envd/process/process_connect'
+import { Signal, ProcessConfig } from '../../envd/process/process_pb'
import {
- Signal,
- ProcessConfig,
-} from '../../envd/process/process_pb'
-import { ConnectionConfig, Username, ConnectionOpts, KEEPALIVE_PING_INTERVAL_SEC, KEEPALIVE_PING_HEADER } from '../../connectionConfig'
+ ConnectionConfig,
+ Username,
+ ConnectionOpts,
+ KEEPALIVE_PING_INTERVAL_SEC,
+ KEEPALIVE_PING_HEADER,
+} from '../../connectionConfig'
import { authenticationHeader, handleRpcError } from '../../envd/rpc'
import { ProcessHandle, ProcessResult } from './processHandle'
import { handleProcessStartEvent } from '../../envd/api'
+export { Pty } from './pty'
-export interface ProcessRequestOpts extends Partial<Pick<ConnectionOpts, 'requestTimeoutMs'>> { }
+/**
+ * Options for sending a request to a process.
+ */
+export interface ProcessRequestOpts
+ extends Partial<Pick<ConnectionOpts, 'requestTimeoutMs'>> {}
+/**
+ * Options for starting a new process.
+ */
export interface ProcessStartOpts extends ProcessRequestOpts {
background?: boolean
cwd?: string
user?: Username
envs?: Record<string, string>
- onStdout?: ((data: string) => void | Promise<void>)
- onStderr?: ((data: string) => void | Promise<void>)
+ onStdout?: (data: string) => void | Promise<void>
+ onStderr?: (data: string) => void | Promise<void>
timeoutMs?: number
}
-export type ProcessConnectOpts = Pick<ProcessStartOpts, 'onStderr' | 'onStdout' | 'timeoutMs'> & ProcessRequestOpts
+/**
+ * Options for connecting to a process.
+ */
+export type ProcessConnectOpts = Pick<
+ ProcessStartOpts,
+ 'onStderr' | 'onStdout' | 'timeoutMs'
+> &
+ ProcessRequestOpts
+/**
+ * Process information.
+ */
export interface ProcessInfo extends PlainMessage<ProcessConfig> {
pid: number
tag?: string
}
+/**
+ * Manager for starting and interacting with processes in the sandbox.
+ */
export class Process {
protected readonly rpc: PromiseClient<typeof ProcessService>
@@ -43,66 +67,99 @@ export class Process {
constructor(
transport: Transport,
- private readonly connectionConfig: ConnectionConfig,
+ private readonly connectionConfig: ConnectionConfig
) {
this.rpc = createPromiseClient(ProcessService, transport)
}
+ /**
+ * Lists all running processes.
+ *
+ * @param opts Options for the request
+ * @returns List of running processes
+ */
async list(opts?: ProcessRequestOpts): Promise<ProcessInfo[]> {
try {
- const res = await this.rpc.list({}, {
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
- })
+ const res = await this.rpc.list(
+ {},
+ {
+ signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ }
+ )
return res.processes.map((p) => ({
pid: p.pid,
- ...p.tag && { tag: p.tag },
+ ...(p.tag && { tag: p.tag }),
args: p.config!.args,
envs: p.config!.envs,
cmd: p.config!.cmd,
- ...p.config!.cwd && { cwd: p.config!.cwd },
+ ...(p.config!.cwd && { cwd: p.config!.cwd }),
}))
} catch (err) {
throw handleRpcError(err)
}
}
- async sendStdin(pid: number, data: string, opts?: ProcessRequestOpts): Promise<void> {
+ /**
+ * 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
+ */
+ async sendStdin(
+ pid: number,
+ data: string,
+ opts?: ProcessRequestOpts
+ ): Promise<void> {
try {
- await this.rpc.sendInput({
- process: {
- selector: {
- case: 'pid',
- value: pid,
- }
- },
- input: {
+ await this.rpc.sendInput(
+ {
+ process: {
+ selector: {
+ case: 'pid',
+ value: pid,
+ },
+ },
input: {
- case: 'stdin',
- value: new TextEncoder().encode(data),
- }
+ input: {
+ case: 'stdin',
+ value: new TextEncoder().encode(data),
+ },
+ },
+ },
+ {
+ signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
}
- }, {
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
- })
+ )
} catch (err) {
throw handleRpcError(err)
}
}
+ /**
+ * Kills a process.
+ *
+ * @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
+ */
async kill(pid: number, opts?: ProcessRequestOpts): Promise<boolean> {
try {
- await this.rpc.sendSignal({
- process: {
- selector: {
- case: 'pid',
- value: pid,
- }
+ await this.rpc.sendSignal(
+ {
+ process: {
+ selector: {
+ case: 'pid',
+ value: pid,
+ },
+ },
+ signal: Signal.SIGKILL,
},
- signal: Signal.SIGKILL,
- }, {
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
- })
+ {
+ signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ }
+ )
return true
} catch (err) {
@@ -116,31 +173,44 @@ export class Process {
}
}
- async connect(pid: number, opts?: ProcessConnectOpts): Promise<ProcessHandle> {
- const requestTimeoutMs = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
+ /**
+ * Connects to an existing process.
+ *
+ * @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
+ */
+ async connect(
+ pid: number,
+ opts?: ProcessConnectOpts
+ ): Promise<ProcessHandle> {
+ const requestTimeoutMs =
+ opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
const controller = new AbortController()
const reqTimeout = requestTimeoutMs
? setTimeout(() => {
- controller.abort()
- }, requestTimeoutMs)
+ controller.abort()
+ }, requestTimeoutMs)
: undefined
- const events = this.rpc.connect({
- process: {
- selector: {
- case: 'pid',
- value: pid,
- }
- },
- }, {
- signal: controller.signal,
- headers: {
- [KEEPALIVE_PING_HEADER]: KEEPALIVE_PING_INTERVAL_SEC.toString(),
+ const events = this.rpc.connect(
+ {
+ process: {
+ selector: {
+ case: 'pid',
+ value: pid,
+ },
+ },
},
- timeoutMs: opts?.timeoutMs ?? this.defaultProcessConnectionTimeout,
- })
+ {
+ signal: controller.signal,
+ headers: {
+ [KEEPALIVE_PING_HEADER]: KEEPALIVE_PING_INTERVAL_SEC.toString(),
+ },
+ timeoutMs: opts?.timeoutMs ?? this.defaultProcessConnectionTimeout,
+ }
+ )
try {
const pid = await handleProcessStartEvent(events)
@@ -154,49 +224,82 @@ export class Process {
events,
opts?.onStdout,
opts?.onStderr,
- undefined,
+ undefined
)
} catch (err) {
throw handleRpcError(err)
}
}
- async run(cmd: string, opts?: ProcessStartOpts & { background?: false }): Promise<ProcessResult>
- async run(cmd: string, opts?: ProcessStartOpts & { background: true }): Promise<ProcessHandle>
- async run(cmd: string, opts?: ProcessStartOpts & { background?: boolean }): Promise<unknown> {
+ /**
+ * 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
+ */
+ async run(
+ cmd: string,
+ opts?: ProcessStartOpts & { background?: false }
+ ): Promise<ProcessResult>
+ /**
+ * Starts a new process and waits until it finishes.
+ * @param cmd Command to execute
+ * @param opts Options for starting the process
+ * @returns New process
+ */
+ async run(
+ cmd: string,
+ opts?: ProcessStartOpts & { background: true }
+ ): Promise<ProcessHandle>
+ async run(
+ cmd: string,
+ opts?: ProcessStartOpts & { background?: boolean }
+ ): Promise<unknown> {
const proc = await this.start(cmd, opts)
- return opts?.background
- ? proc
- : proc.wait()
+ return opts?.background ? proc : proc.wait()
}
- private async start(cmd: string, opts?: ProcessStartOpts): Promise<ProcessHandle> {
- const requestTimeoutMs = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
+ /**
+ * Use `run` instead.
+ * @hidden
+ * @hide
+ * @internal
+ * @access protected
+ */
+ private async start(
+ cmd: string,
+ opts?: ProcessStartOpts
+ ): Promise<ProcessHandle> {
+ const requestTimeoutMs =
+ opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
const controller = new AbortController()
const reqTimeout = requestTimeoutMs
? setTimeout(() => {
- controller.abort()
- }, requestTimeoutMs)
+ controller.abort()
+ }, requestTimeoutMs)
: undefined
- const events = this.rpc.start({
- process: {
- cmd: '/bin/bash',
- cwd: opts?.cwd,
- envs: opts?.envs,
- args: ['-l', '-c', cmd],
- },
- }, {
- headers: {
- ...authenticationHeader(opts?.user),
- [KEEPALIVE_PING_HEADER]: KEEPALIVE_PING_INTERVAL_SEC.toString(),
+ const events = this.rpc.start(
+ {
+ process: {
+ cmd: '/bin/bash',
+ cwd: opts?.cwd,
+ envs: opts?.envs,
+ args: ['-l', '-c', cmd],
+ },
},
- signal: controller.signal,
- timeoutMs: opts?.timeoutMs ?? this.defaultProcessConnectionTimeout,
- })
+ {
+ headers: {
+ ...authenticationHeader(opts?.user),
+ [KEEPALIVE_PING_HEADER]: KEEPALIVE_PING_INTERVAL_SEC.toString(),
+ },
+ signal: controller.signal,
+ timeoutMs: opts?.timeoutMs ?? this.defaultProcessConnectionTimeout,
+ }
+ )
try {
const pid = await handleProcessStartEvent(events)
@@ -210,7 +313,7 @@ export class Process {
events,
opts?.onStdout,
opts?.onStderr,
- undefined,
+ undefined
)
} catch (err) {
throw handleRpcError(err)
diff --git a/packages/js-sdk/src/sandbox/process/processHandle.ts b/packages/js-sdk/src/sandbox/process/processHandle.ts
index 5fda6b0b4..13eba08b5 100644
--- a/packages/js-sdk/src/sandbox/process/processHandle.ts
+++ b/packages/js-sdk/src/sandbox/process/processHandle.ts
@@ -1,9 +1,6 @@
import { handleRpcError } from '../../envd/rpc'
import { SandboxError } from '../../errors'
-import {
- ConnectResponse,
- StartResponse,
-} from '../../envd/process/process_pb'
+import { ConnectResponse, StartResponse } from '../../envd/process/process_pb'
declare const __brand: unique symbol
type Brand<B> = { [__brand]: B }
@@ -13,6 +10,9 @@ export type Stdout = Branded<string, 'stdout'>
export type Stderr = Branded<string, 'stderr'>
export type PtyOutput = Branded<Uint8Array, 'pty'>
+/**
+ * Result of a process execution.
+ */
export interface ProcessResult {
exitCode: number
error?: string
@@ -20,6 +20,9 @@ export interface ProcessResult {
stderr: string
}
+/**
+ * Error thrown when a process exits with a non-zero exit code.
+ */
export class ProcessExitError extends SandboxError implements ProcessResult {
constructor(private readonly result: ProcessResult) {
super(result.error)
@@ -43,7 +46,14 @@ export class ProcessExitError extends SandboxError implements ProcessResult {
}
}
-export class ProcessHandle implements Omit<ProcessResult, 'exitCode' | 'error'>, Partial<Pick<ProcessResult, 'exitCode' | 'error'>> {
+/**
+ * Represents a process object. It provides methods for waiting for the finish and killing the process.
+ */
+export class ProcessHandle
+ implements
+ Omit<ProcessResult, 'exitCode' | 'error'>,
+ Partial<Pick<ProcessResult, 'exitCode' | 'error'>>
+{
private _stdout = ''
private _stderr = ''
@@ -57,29 +67,46 @@ export class ProcessHandle implements Omit<ProcessResult, 'exitCode' | 'error'>,
private readonly handleDisconnect: () => void,
private readonly handleKill: () => Promise<boolean>,
private readonly events: AsyncIterable<ConnectResponse | StartResponse>,
- private readonly onStdout?: (stdout: string) => (void | Promise<void>),
- private readonly onStderr?: (stderr: string) => (void | Promise<void>),
- private readonly onPty?: (pty: Uint8Array) => (void | Promise<void>),
+ private readonly onStdout?: (stdout: string) => void | Promise<void>,
+ private readonly onStderr?: (stderr: string) => void | Promise<void>,
+ private readonly onPty?: (pty: Uint8Array) => void | Promise<void>
) {
this._wait = this.handleEvents()
}
+ /**
+ * Exit code of the process. It is `undefined` if the process is still running.
+ */
get exitCode() {
return this.result?.exitCode
}
+ /**
+ * Error message of the process. It is `undefined` if the process is still running.
+ */
get error() {
return this.result?.error
}
+ /**
+ * Stderr of the process.
+ */
get stderr() {
return this._stderr
}
+ /**
+ * Stdout of the process.
+ */
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
+ */
async wait() {
await this._wait
@@ -98,15 +125,24 @@ export class ProcessHandle implements Omit<ProcessResult, 'exitCode' | 'error'>,
return this.result
}
+ /**
+ * Disconnects from the process. It does not kill the process. It only stops receiving events from the process.
+ */
async disconnect() {
this.handleDisconnect()
}
+ /**
+ * Kills the process.
+ * @returns Whether the process was killed successfully
+ */
async kill() {
await this.handleKill()
}
- private async* iterateEvents(): AsyncGenerator<[Stdout, null, null] | [null, Stderr, null] | [null, null, PtyOutput]> {
+ private async *iterateEvents(): AsyncGenerator<
+ [Stdout, null, null] | [null, Stderr, null] | [null, null, PtyOutput]
+ > {
for await (const event of this.events) {
const e = event?.event?.event
let out: string | undefined
diff --git a/packages/js-sdk/src/sandbox/process/pty.ts b/packages/js-sdk/src/sandbox/process/pty.ts
new file mode 100644
index 000000000..aaa8519df
--- /dev/null
+++ b/packages/js-sdk/src/sandbox/process/pty.ts
@@ -0,0 +1,219 @@
+import {
+ Code,
+ ConnectError,
+ createPromiseClient,
+ PromiseClient,
+ Transport,
+} from '@connectrpc/connect'
+
+import { Process as ProcessService } from '../../envd/process/process_connect'
+import { Signal } from '../../envd/process/process_pb'
+import {
+ ConnectionConfig,
+ ConnectionOpts,
+ Username,
+ KEEPALIVE_PING_HEADER,
+ KEEPALIVE_PING_INTERVAL_SEC,
+} from '../../connectionConfig'
+import { ProcessHandle } from './processHandle'
+import { authenticationHeader, handleRpcError } from '../../envd/rpc'
+import { handleProcessStartEvent } from '../../envd/api'
+
+export interface PtyCreateOpts
+ extends Pick<ConnectionOpts, 'requestTimeoutMs'> {
+ cols: number
+ rows: number
+ onData: (data: Uint8Array) => void | Promise<void>
+ timeoutMs?: number
+ user?: Username
+ envs?: Record<string, string>
+ cwd?: string
+}
+
+/**
+ * Manager for starting and interacting with PTY (pseudo-terminal) processes in the sandbox.
+ */
+export class Pty {
+ private readonly rpc: PromiseClient<typeof ProcessService>
+
+ constructor(
+ private readonly transport: Transport,
+ private readonly connectionConfig: ConnectionConfig
+ ) {
+ this.rpc = createPromiseClient(ProcessService, this.transport)
+ }
+
+ /**
+ * Starts a new process with a PTY (pseudo-terminal).
+ *
+ * @param opts Options for creating the PTY process
+ * @returns New process
+ */
+ async create(opts: PtyCreateOpts) {
+ const requestTimeoutMs =
+ opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
+ const envs = opts?.envs ?? {}
+ envs.TERM = 'xterm-256color'
+ const controller = new AbortController()
+
+ const reqTimeout = setTimeout(() => {
+ controller.abort()
+ }, requestTimeoutMs)
+
+ const events = this.rpc.start(
+ {
+ process: {
+ cmd: '/bin/bash',
+ args: ['-i', '-l'],
+ envs: envs,
+ cwd: opts?.cwd,
+ },
+ pty: {
+ size: {
+ cols: opts.cols,
+ rows: opts.rows,
+ },
+ },
+ },
+ {
+ headers: {
+ ...authenticationHeader(opts?.user),
+ [KEEPALIVE_PING_HEADER]: KEEPALIVE_PING_INTERVAL_SEC.toString(),
+ },
+ signal: controller.signal,
+ timeoutMs: opts?.timeoutMs ?? 60_000,
+ }
+ )
+
+ try {
+ const pid = await handleProcessStartEvent(events)
+
+ clearTimeout(reqTimeout)
+
+ return new ProcessHandle(
+ pid,
+ () => controller.abort(),
+ () => this.kill(pid),
+ events,
+ undefined,
+ undefined,
+ opts.onData
+ )
+ } catch (err) {
+ throw handleRpcError(err)
+ }
+ }
+
+ /**
+ * Sends 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
+ */
+ async sendInput(
+ pid: number,
+ data: Uint8Array,
+ opts?: Pick<ConnectionOpts, 'requestTimeoutMs'>
+ ): Promise<void> {
+ try {
+ await this.rpc.sendInput(
+ {
+ input: {
+ input: {
+ case: 'pty',
+ value: data,
+ },
+ },
+ process: {
+ selector: {
+ case: 'pid',
+ value: pid,
+ },
+ },
+ },
+ {
+ signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ }
+ )
+ } catch (err) {
+ throw handleRpcError(err)
+ }
+ }
+
+ /**
+ * Resizes a PTY process (changes the number of columns and rows in the terminal).
+ *
+ * @param pid Process ID of the PTY process
+ * @param size New size of the PTY
+ * @param opts Connection options for the request
+ */
+ async resize(
+ pid: number,
+ size: {
+ cols: number
+ rows: number
+ },
+ opts?: Pick<ConnectionOpts, 'requestTimeoutMs'>
+ ): Promise<void> {
+ try {
+ await this.rpc.update(
+ {
+ process: {
+ selector: {
+ case: 'pid',
+ value: pid,
+ },
+ },
+ pty: {
+ size,
+ },
+ },
+ {
+ signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ }
+ )
+ } catch (err) {
+ throw handleRpcError(err)
+ }
+ }
+
+ /**
+ * Kills a process.
+ *
+ * @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
+ */
+ async kill(
+ pid: number,
+ opts?: Pick<ConnectionOpts, 'requestTimeoutMs'>
+ ): Promise<boolean> {
+ try {
+ await this.rpc.sendSignal(
+ {
+ process: {
+ selector: {
+ case: 'pid',
+ value: pid,
+ },
+ },
+ signal: Signal.SIGKILL,
+ },
+ {
+ signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ }
+ )
+
+ return true
+ } catch (err) {
+ if (err instanceof ConnectError) {
+ if (err.code === Code.NotFound) {
+ return false
+ }
+ }
+
+ throw handleRpcError(err)
+ }
+ }
+}
diff --git a/packages/js-sdk/src/sandbox/pty.ts b/packages/js-sdk/src/sandbox/pty.ts
deleted file mode 100644
index d7fcd2f18..000000000
--- a/packages/js-sdk/src/sandbox/pty.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-import {
- Code,
- ConnectError,
- createPromiseClient,
- PromiseClient,
- Transport,
-} from '@connectrpc/connect'
-
-import { Process as ProcessService } from '../envd/process/process_connect'
-import { Signal } from '../envd/process/process_pb'
-import { ConnectionConfig, ConnectionOpts, Username, KEEPALIVE_PING_HEADER, KEEPALIVE_PING_INTERVAL_SEC } from '../connectionConfig'
-import { ProcessHandle } from './process/processHandle'
-import { authenticationHeader, handleRpcError } from '../envd/rpc'
-import { handleProcessStartEvent } from '../envd/api'
-
-export interface PtyCreateOpts extends Pick<ConnectionOpts, 'requestTimeoutMs'> {
- cols: number
- rows: number
- onData: (data: Uint8Array) => (void | Promise<void>)
- timeoutMs?: number
- user?: Username
- envs?: Record<string, string>
- cwd?: string
-}
-
-export class Pty {
- private readonly rpc: PromiseClient<typeof ProcessService>
-
- constructor(private readonly transport: Transport, private readonly connectionConfig: ConnectionConfig) {
- this.rpc = createPromiseClient(ProcessService, this.transport)
- }
-
- async create(opts: PtyCreateOpts) {
- const requestTimeoutMs = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
- const envs = opts?.envs ?? {}
- envs.TERM = 'xterm-256color'
- const controller = new AbortController()
-
- const reqTimeout = setTimeout(() => {
- controller.abort()
- }, requestTimeoutMs)
-
- const events = this.rpc.start({
- process: {
- cmd: '/bin/bash',
- args: ['-i', '-l'],
- envs: envs,
- cwd: opts?.cwd,
- },
- pty: {
- size: {
- cols: opts.cols,
- rows: opts.rows,
- },
- },
- }, {
- headers: {
- ...authenticationHeader(opts?.user),
- [KEEPALIVE_PING_HEADER]: KEEPALIVE_PING_INTERVAL_SEC.toString(),
- },
- signal: controller.signal,
- timeoutMs: opts?.timeoutMs ?? 60_000,
- })
-
- try {
- const pid = await handleProcessStartEvent(events)
-
- clearTimeout(reqTimeout)
-
- return new ProcessHandle(
- pid,
- () => controller.abort(),
- () => this.kill(pid),
- events,
- undefined,
- undefined,
- opts.onData,
- )
- } catch (err) {
- throw handleRpcError(err)
- }
- }
-
- async sendInput(pid: number, data: Uint8Array, opts?: Pick<ConnectionOpts, 'requestTimeoutMs'>): Promise<void> {
- try {
- await this.rpc.sendInput({
- input: {
- input: {
- case: 'pty',
- value: data,
- },
- },
- process: {
- selector: {
- case: 'pid',
- value: pid,
- },
- },
- }, {
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
- })
- } catch (err) {
- throw handleRpcError(err)
- }
- }
-
- async resize(
- pid: number,
- size: {
- cols: number,
- rows: number,
- },
- opts?: Pick<ConnectionOpts, 'requestTimeoutMs'>,
- ): Promise<void> {
- try {
- await this.rpc.update({
- process: {
- selector: {
- case: 'pid',
- value: pid,
- }
- },
- pty: {
- size,
- },
- }, {
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
- })
- } catch (err) {
- throw handleRpcError(err)
- }
- }
-
- private async kill(pid: number, opts?: Pick<ConnectionOpts, 'requestTimeoutMs'>): Promise<boolean> {
- try {
- await this.rpc.sendSignal({
- process: {
- selector: {
- case: 'pid',
- value: pid,
- }
- },
- signal: Signal.SIGKILL,
- }, {
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
- })
-
- return true
- } catch (err) {
- if (err instanceof ConnectError) {
- if (err.code === Code.NotFound) {
- return false
- }
- }
-
- throw handleRpcError(err)
- }
- }
-}
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index aab5aed7c..684eb98ea 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -3,7 +3,13 @@ import { ConnectionConfig, ConnectionOpts } from '../connectionConfig'
import { compareVersions } from 'compare-versions'
import { TemplateError } from '../errors'
-export interface SandboxApiOpts extends Partial<Pick<ConnectionOpts, 'apiKey' | 'debug' | 'domain' | 'requestTimeoutMs'>> { }
+/**
+ * Options for request to the sandbox orchestration API.
+ */
+export interface SandboxApiOpts
+ extends Partial<
+ Pick<ConnectionOpts, 'apiKey' | 'debug' | 'domain' | 'requestTimeoutMs'>
+ > {}
/**
* Information about a sandbox.
@@ -36,7 +42,7 @@ export interface SandboxInfo {
}
export class SandboxApi {
- protected constructor() { }
+ protected constructor() {}
/**
* Kills sandbox specified by sandbox ID.
@@ -44,7 +50,10 @@ export class SandboxApi {
* @param sandboxId - Sandbox ID.
* @param opts - Connection options.
*/
- static async kill(sandboxId: string, opts?: SandboxApiOpts): Promise<boolean> {
+ static async kill(
+ sandboxId: string,
+ opts?: SandboxApiOpts
+ ): Promise<boolean> {
const config = new ConnectionConfig(opts)
const client = new ApiClient(config)
@@ -82,16 +91,25 @@ export class SandboxApi {
throw err
}
- return res.data?.map((sandbox: components['schemas']['RunningSandbox']) => ({
- sandboxId: this.getSandboxId({ sandboxId: sandbox.sandboxID, clientId: sandbox.clientID }),
- templateId: sandbox.templateID,
- ...(sandbox.alias && { name: sandbox.alias }),
- metadata: sandbox.metadata ?? {},
- startedAt: new Date(sandbox.startedAt),
- })) ?? []
+ return (
+ res.data?.map((sandbox: components['schemas']['RunningSandbox']) => ({
+ sandboxId: this.getSandboxId({
+ sandboxId: sandbox.sandboxID,
+ clientId: sandbox.clientID,
+ }),
+ templateId: sandbox.templateID,
+ ...(sandbox.alias && { name: sandbox.alias }),
+ metadata: sandbox.metadata ?? {},
+ startedAt: new Date(sandbox.startedAt),
+ })) ?? []
+ )
}
- static async setTimeout(sandboxId: string, timeoutMs: number, opts?: SandboxApiOpts): Promise<void> {
+ static async setTimeout(
+ sandboxId: string,
+ timeoutMs: number,
+ opts?: SandboxApiOpts
+ ): Promise<void> {
const config = new ConnectionConfig(opts)
const client = new ApiClient(config)
@@ -117,9 +135,10 @@ export class SandboxApi {
template: string,
timeoutMs: number,
opts?: SandboxApiOpts & {
- metadata?: Record<string, string>,
- envs?: Record<string, string>,
- }): Promise<string> {
+ metadata?: Record<string, string>
+ envs?: Record<string, string>
+ }
+ ): Promise<string> {
const config = new ConnectionConfig(opts)
const client = new ApiClient(config)
@@ -139,20 +158,35 @@ export class SandboxApi {
}
if (compareVersions(res.data!.envdVersion, '0.1.0') < 0) {
- await this.kill(this.getSandboxId({ sandboxId: res.data!.sandboxID, clientId: res.data!.clientID }), opts)
+ await this.kill(
+ this.getSandboxId({
+ sandboxId: res.data!.sandboxID,
+ clientId: res.data!.clientID,
+ }),
+ opts
+ )
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({ sandboxId: res.data!.sandboxID, clientId: res.data!.clientID })
+ return this.getSandboxId({
+ sandboxId: res.data!.sandboxID,
+ clientId: res.data!.clientID,
+ })
}
private static timeoutToSeconds(timeout: number): number {
return Math.ceil(timeout / 1000)
}
- private static getSandboxId({ sandboxId, clientId }: { sandboxId: string, clientId: string }): string {
+ private static getSandboxId({
+ sandboxId,
+ clientId,
+ }: {
+ sandboxId: string
+ clientId: string
+ }): string {
return `${sandboxId}-${clientId}`
}
}
diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.py
index 55e8ddb42..2945e35d0 100644
--- a/packages/python-sdk/e2b/__init__.py
+++ b/packages/python-sdk/e2b/__init__.py
@@ -36,6 +36,5 @@ from .sandbox_sync.process.process_handle import ProcessHandle
from .sandbox_async.utilts import OutputHandler
from .sandbox_async.main import AsyncSandbox
-from .sandbox_async.main import AsyncSandbox
from .sandbox_async.filesystem.watch_handle import AsyncWatchHandle
from .sandbox_async.process.process_handle import AsyncProcessHandle
diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.py
index f5ac5b5af..566d15c8a 100644
--- a/packages/python-sdk/e2b/api/__init__.py
+++ b/packages/python-sdk/e2b/api/__init__.py
@@ -25,6 +25,10 @@ def handle_api_exception(e: Response):
class ApiClient(AuthenticatedClient):
+ """
+ The client for interacting with the E2B API.
+ """
+
def __init__(
self,
config: ConnectionConfig,
diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.py
index b90f41823..31a587cd6 100644
--- a/packages/python-sdk/e2b/connection_config.py
+++ b/packages/python-sdk/e2b/connection_config.py
@@ -9,6 +9,10 @@ KEEPALIVE_PING_HEADER = "Keepalive-Ping-Interval"
class ConnectionConfig:
+ """
+ Configuration for the connection to the E2B API.
+ """
+
@staticmethod
def _domain():
return os.getenv("E2B_DOMAIN", "e2b.dev")
diff --git a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
index 8188f144b..eb13d43d5 100644
--- a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
@@ -6,6 +6,10 @@ from e2b.envd.filesystem import filesystem_pb2
class FileType(Enum):
+ """
+ Enum representing the type of filesystem object.
+ """
+
FILE = "file"
DIR = "dir"
@@ -19,6 +23,10 @@ def map_file_type(ft: filesystem_pb2.FileType):
@dataclass
class EntryInfo:
+ """
+ Contains information about the filesystem object (file or directory).
+ """
+
name: str
type: Optional[FileType]
path: str
diff --git a/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py b/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py
index 1266d25e9..03d350e23 100644
--- a/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py
+++ b/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py
@@ -5,6 +5,10 @@ from e2b.envd.filesystem.filesystem_pb2 import EventType
class FilesystemEventType(Enum):
+ """
+ Enum representing the type of filesystem event.
+ """
+
CHMOD = "chmod"
CREATE = "create"
REMOVE = "remove"
@@ -27,5 +31,9 @@ def map_event_type(event: EventType):
@dataclass
class FilesystemEvent:
+ """
+ Contains information about the filesystem event - the name of the file and the type of the event.
+ """
+
name: str
type: FilesystemEventType
diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.py
index 083cdae6a..bc64807c0 100644
--- a/packages/python-sdk/e2b/sandbox/main.py
+++ b/packages/python-sdk/e2b/sandbox/main.py
@@ -22,15 +22,18 @@ class SandboxSetup(ABC):
@property
@abstractmethod
- def connection_config(self) -> ConnectionConfig: ...
+ def connection_config(self) -> ConnectionConfig:
+ ...
@property
@abstractmethod
- def envd_api_url(self) -> str: ...
+ def envd_api_url(self) -> str:
+ ...
@property
@abstractmethod
- def sandbox_id(self) -> str: ...
+ def sandbox_id(self) -> str:
+ ...
def _file_url(self, path: Optional[str] = None) -> str:
url = urllib.parse.urljoin(self.envd_api_url, ENVD_API_FILES_ROUTE)
diff --git a/packages/python-sdk/e2b/sandbox/process/main.py b/packages/python-sdk/e2b/sandbox/process/main.py
index c8f1735db..44c94c9ae 100644
--- a/packages/python-sdk/e2b/sandbox/process/main.py
+++ b/packages/python-sdk/e2b/sandbox/process/main.py
@@ -4,6 +4,10 @@ from typing import Dict, List, Optional
@dataclass
class ProcessInfo:
+ """
+ Contains information about the process.
+ """
+
pid: int
tag: Optional[str]
cmd: str
diff --git a/packages/python-sdk/e2b/sandbox/process/process_handle.py b/packages/python-sdk/e2b/sandbox/process/process_handle.py
index 16d59ad02..9f3991ee1 100644
--- a/packages/python-sdk/e2b/sandbox/process/process_handle.py
+++ b/packages/python-sdk/e2b/sandbox/process/process_handle.py
@@ -10,12 +10,20 @@ PtyOutput = bytes
@dataclass
class PtySize:
+ """
+ Contains information about the size of the pseudo-terminal
+ """
+
rows: int
cols: int
@dataclass
class ProcessResult:
+ """
+ Contains information about the process execution result.
+ """
+
stderr: str
stdout: str
exit_code: int
@@ -24,5 +32,9 @@ class ProcessResult:
@dataclass
class ProcessExitException(SandboxException, ProcessResult):
+ """
+ Exception raised when a process exits with a non-zero exit code.
+ """
+
def __str__(self):
return f"Process exited with code {self.exit_code} and error: {self.error}\n{self.stderr}"
diff --git a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
index 6f79277e3..6a47433af 100644
--- a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
@@ -21,6 +21,10 @@ from e2b.sandbox_async.utilts import OutputHandler
class Filesystem:
+ """
+ Manager for interacting with the filesystem in the sandbox.
+ """
+
def __init__(
self,
envd_api_url: str,
@@ -75,7 +79,15 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
):
- """Read from file"""
+ """
+ Reads a whole file content and returns it in requested format (text by default).
+
+ :param path: Path to the file
+ :param format: Format of the file content
+ :param user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ :return File content in requested format
+ """
r = await self._envd_api.get(
ENVD_API_FILES_ROUTE,
params={"path": path, "username": user},
@@ -100,10 +112,17 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
) -> EntryInfo:
- """Write to file
+ """
+ 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, you'll get an error.
+
+ :param path: Path to the file
+ :param data: Data to write to the file
+ :param user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ :return: Information about the written file
"""
if isinstance(data, TextIOBase):
data = data.read().encode()
@@ -133,7 +152,14 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
) -> List[EntryInfo]:
- """List directory"""
+ """
+ Lists entries in a directory.
+
+ :param path: Path to the directory
+ :param user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ :return: List of entries in the directory
+ """
try:
res = await self._rpc.alist_dir(
filesystem_pb2.ListDirRequest(path=path),
@@ -162,7 +188,13 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
) -> bool:
- """Check if file exists."""
+ """
+ Checks if a file or a directory exists.
+
+ :param path: Path to a file or a directory
+ :param user Run the operation as this user
+ :param request_timeout Timeout for the request
+ """
try:
await self._rpc.astat(
filesystem_pb2.StatRequest(path=path),
@@ -186,7 +218,12 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
) -> None:
- """Remove file"""
+ """
+ Removes a file or a directory.
+ :param path: Path to a file or a directory
+ :param user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ """
try:
await self._rpc.aremove(
filesystem_pb2.RemoveRequest(path=path),
@@ -205,7 +242,16 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
) -> EntryInfo:
- """Rename file"""
+ """
+ Renames a file or directory from one path to another.
+
+ :param old_path Path to the file or directory to move
+ :param new_path Path to move the file or directory to
+ :param user Run the operation as this user
+ :param request_timeout Timeout for the request
+
+ :return: Information about the renamed file or directory
+ """
try:
r = await self._rpc.amove(
filesystem_pb2.MoveRequest(
@@ -232,7 +278,14 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
) -> bool:
- """Create directory and all parent directories"""
+ """
+ Creates 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 user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ :return: True if the directory was created, False if the directory already exists
+ """
try:
await self._rpc.amake_dir(
filesystem_pb2.MakeDirRequest(path=path),
@@ -257,8 +310,18 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
timeout: Optional[float] = 60,
- ):
- """Watch directory for changes"""
+ ) -> AsyncWatchHandle:
+ """
+ Watches directory for filesystem events.
+
+ :param path: Path to a directory that will be watched
+ :param on_event: Callback that will be called on each event
+ :param on_exit: Callback that will be called when the watch is closed
+ :param user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ :param timeout: Timeout for the watch, after which the watch will be closed
+ :return: Watcher handle
+ """
events = self._rpc.awatch_dir(
filesystem_pb2.WatchDirRequest(path=path),
request_timeout=self._connection_config.get_request_timeout(
diff --git a/packages/python-sdk/e2b/sandbox_async/filesystem/watch_handle.py b/packages/python-sdk/e2b/sandbox_async/filesystem/watch_handle.py
index aa420cd71..6a2400d6c 100644
--- a/packages/python-sdk/e2b/sandbox_async/filesystem/watch_handle.py
+++ b/packages/python-sdk/e2b/sandbox_async/filesystem/watch_handle.py
@@ -10,6 +10,10 @@ from e2b.sandbox_async.utilts import OutputHandler
class AsyncWatchHandle:
+ """
+ Class representing the watch operation. It provides method to stop the watch operation.
+ """
+
def __init__(
self,
events: AsyncGenerator[WatchDirResponse, Any],
@@ -23,6 +27,9 @@ class AsyncWatchHandle:
self._wait = asyncio.create_task(self._handle_events())
async def close(self):
+ """
+ Stop watching the directory.
+ """
self._wait.cancel()
# BUG: In Python 3.8 closing async generator can throw RuntimeError.
# await self._events.aclose()
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
index e3c3d4cc3..5a588ac8a 100644
--- a/packages/python-sdk/e2b/sandbox_async/main.py
+++ b/packages/python-sdk/e2b/sandbox_async/main.py
@@ -9,7 +9,7 @@ from e2b.sandbox.main import SandboxSetup
from e2b.sandbox.utils import class_method_variant
from e2b.sandbox_async.filesystem.filesystem import Filesystem
from e2b.sandbox_async.process.process import Process
-from e2b.sandbox_async.pty.main import Pty
+from e2b.sandbox_async.process.pty import Pty
from e2b.sandbox_async.sandbox_api import SandboxApi
from typing_extensions import Unpack
@@ -34,37 +34,74 @@ class AsyncSandboxOpts(TypedDict):
class AsyncSandbox(SandboxSetup, SandboxApi):
+ """
+ E2B cloud sandbox gives your agent a full cloud development environment that's sandboxed.
+
+ That means:
+ - Access to Linux OS
+ - Using filesystem (create, list, and delete files and dirs)
+ - Run commands
+ - Sandboxed - you can run any code
+ - Access to the internet
+
+ Check usage docs - https://e2b.dev/docs/sandbox/overview
+
+ These cloud sandboxes are meant to be used for agents. Like a sandboxed playgrounds, where the agent can do whatever it wants.
+
+ Use the `AsyncSandbox.create()` to create a new sandbox.
+
+ Example:
+ ```python
+ sandbox = await AsyncSandbox.create()
+ ```
+ """
+
@property
def files(self) -> Filesystem:
- """Get a Filesystem Object"""
+ """
+ Filesystem module for interacting with the sandbox's filesystem
+ """
return self._filesystem
@property
def commands(self) -> Process:
- """Get a Process Object"""
+ """
+ Commands module for interacting with the sandbox's processes
+ """
return self._process
@property
def pty(self) -> Pty:
+ """
+ PTY module for interacting with the sandbox's pseudo-terminal.
+ """
return self._pty
@property
def sandbox_id(self) -> str:
- """Get the sandbox ID"""
+ """
+ Get the sandbox ID
+ """
return self._sandbox_id
@property
def envd_api_url(self) -> str:
- """Get the sanbox API URL"""
+ """
+ Get the sandbox API URL
+ """
return self._envd_api_url
@property
def connection_config(self) -> ConnectionConfig:
- """Get the ConnectionConfig Object"""
+ """
+ Get the ConnectionConfig object
+ """
return self._connection_config
def __init__(self, **opts: Unpack[AsyncSandboxOpts]):
- """Instantiate sandbox"""
+ """
+ Use `Sandbox.create()` instead.
+ """
super().__init__()
self._sandbox_id = opts["sandbox_id"]
@@ -96,7 +133,20 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
)
async def is_running(self, request_timeout: Optional[float] = None) -> bool:
- """Check if sandbox is running"""
+ """
+ Check if the sandbox is running.
+
+ :return: `True` if the sandbox is running, `False` otherwise
+
+ Example
+ ```python
+ sandbox = await AsyncSandbox.create()
+ await sandbox.is_running() # Returns True
+
+ await sandbox.kill()
+ await sandbox.is_running() # Returns False
+ ```
+ """
try:
r = await self._envd_api.get(
ENVD_API_HEALTH_ROUTE,
@@ -128,6 +178,12 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
debug: Optional[bool] = None,
request_timeout: Optional[float] = None,
):
+ """
+ Creates a new sandbox.
+
+ This method creates a new sandbox in the async version,
+ you have to use this method instead of using the constructor.
+ """
connection_config = ConnectionConfig(
api_key=api_key,
domain=domain,
@@ -163,7 +219,22 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
domain: Optional[str] = None,
debug: Optional[bool] = None,
):
- """Connect to a running sandbox"""
+ """
+ Connects to an existing Sandbox.
+ :param sandbox_id: Sandbox ID
+ :param api_key: E2B API Key
+ :param domain: E2B Domain (use only if you self-host E2B)
+ :param debug: For developing purposes, uses a local sandbox
+ :return: Sandbox object
+
+ @example
+ ```python
+ sandbox = await AsyncSandbox.create()
+ sandbox_id = sandbox.sandbox_id
+
+ # Another code block
+ same_sandbox = await AsyncSandbox.connect(sandbox_id)
+ """
connection_config = ConnectionConfig(
api_key=api_key,
domain=domain,
@@ -196,7 +267,12 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
@class_method_variant("_cls_kill")
async def kill(self, request_timeout: Optional[float] = None) -> bool: # type: ignore
- """Kill sandbox"""
+ """
+ Kill the sandbox.
+
+ :param request_timeout: Timeout for the request
+ :return: `True` if the sandbox was killed, `False` if the sandbox was not found
+ """
config_dict = self.connection_config.__dict__
config_dict.pop("access_token", None)
config_dict.pop("api_url", None)
@@ -233,7 +309,14 @@ class AsyncSandbox(SandboxSetup, SandboxApi):
timeout: int,
request_timeout: Optional[float] = None,
) -> None:
- """Configure request timeout"""
+ """
+ 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.
+
+ :param timeout: Duration in milliseconds. Must be between 0 and 86400000 milliseconds (24 hours).
+ :param request_timeout: Timeout for the request
+ """
config_dict = self.connection_config.__dict__
config_dict.pop("access_token", None)
config_dict.pop("api_url", None)
diff --git a/packages/python-sdk/e2b/sandbox_async/process/process.py b/packages/python-sdk/e2b/sandbox_async/process/process.py
index 6a3733549..b7c3fa741 100644
--- a/packages/python-sdk/e2b/sandbox_async/process/process.py
+++ b/packages/python-sdk/e2b/sandbox_async/process/process.py
@@ -18,6 +18,10 @@ from e2b.sandbox_async.utilts import OutputHandler
class Process:
+ """
+ Manager for starting and interacting with processes in the sandbox.
+ """
+
def __init__(
self,
envd_api_url: str,
@@ -37,7 +41,12 @@ class Process:
self,
request_timeout: Optional[float] = None,
) -> List[ProcessInfo]:
- """List processes"""
+ """
+ Lists all running processes.
+
+ :param request_timeout: Request timeout
+ :return: List of running processes
+ """
try:
res = await self._rpc.alist(
process_pb2.ListRequest(),
@@ -64,7 +73,13 @@ class Process:
pid: int,
request_timeout: Optional[float] = None,
) -> bool:
- """Kill process"""
+ """
+ Kills a process.
+
+ :param pid: Process ID to connect to. You can get the list of processes using `sandbox.commands.list()`.
+ :param request_timeout: Request timeout
+ :return: `True` if the process was killed, `False` if the process was not found
+ """
try:
await self._rpc.asend_signal(
process_pb2.SendSignalRequest(
@@ -87,8 +102,14 @@ class Process:
pid: int,
data: str,
request_timeout: Optional[float] = None,
- ):
- """Send stdin"""
+ ) -> None:
+ """
+ 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 request_timeout: Request timeout
+ """
try:
await self._rpc.asend_input(
process_pb2.SendInputRequest(
@@ -144,7 +165,21 @@ class Process:
timeout: Optional[float] = 60,
request_timeout: Optional[float] = None,
):
- """Run command"""
+ """
+ Starts a new process and depending on the `background` parameter, waits for the process to finish or not.
+ :param cmd Command to execute
+ :param background:
+ If `True`, the function will return a `ProcessHandle` object that can be used to interact with the process.
+ If `False`, the function will wait for the process to finish and return a `ProcessResult` object.
+ :param envs: Environment variables
+ :param user: User to run the process as
+ :param cwd: Working directory
+ :param on_stdout: Callback for stdout
+ :param on_stderr: Callback for stderr
+ :param timeout: Timeout for the maximum time the process is allowed to run
+ :param request_timeout: Timeout for the request
+ :return: `ProcessHandle` if `background` is `True`, `ProcessResult` if `background` is `False`
+ """
proc = await self._start(
cmd,
envs,
@@ -168,7 +203,7 @@ class Process:
request_timeout: Optional[float] = None,
on_stdout: Optional[OutputHandler[Stdout]] = None,
on_stderr: Optional[OutputHandler[Stderr]] = None,
- ):
+ ) -> AsyncProcessHandle:
events = self._rpc.astart(
process_pb2.StartRequest(
process=process_pb2.ProcessConfig(
@@ -213,7 +248,16 @@ class Process:
request_timeout: Optional[float] = None,
on_stdout: Optional[OutputHandler[Stdout]] = None,
on_stderr: Optional[OutputHandler[Stderr]] = None,
- ):
+ ) -> AsyncProcessHandle:
+ """
+ Connects to an existing process.
+
+ :param pid: Process ID to connect to. You can get the list of processes using `sandbox.commands.list()`.
+ :param timeout: Timeout for the connection
+ :param request_timeout: Request timeout
+ :param on_stdout: Callback for stdout
+ :param on_stderr: Callback for stderr
+ """
events = self._rpc.aconnect(
process_pb2.ConnectRequest(
process=process_pb2.ProcessSelector(pid=pid),
@@ -226,7 +270,7 @@ class Process:
KEEPALIVE_PING_HEADER: str(KEEPALIVE_PING_INTERVAL_SEC),
},
)
- """Connect to process"""
+
try:
start_event = await events.__anext__()
diff --git a/packages/python-sdk/e2b/sandbox_async/process/process_handle.py b/packages/python-sdk/e2b/sandbox_async/process/process_handle.py
index 8e4f165be..45c4bb5f2 100644
--- a/packages/python-sdk/e2b/sandbox_async/process/process_handle.py
+++ b/packages/python-sdk/e2b/sandbox_async/process/process_handle.py
@@ -23,26 +23,45 @@ from e2b.sandbox_async.utilts import OutputHandler
class AsyncProcessHandle:
+ """
+ Class representing a process. It provides methods for waiting and killing the process.
+ """
+
@property
def pid(self):
+ """
+ Get the process ID.
+ """
return self._pid
@property
def stdout(self):
+ """
+ Stdout of the process.
+ """
return self._stdout
@property
def stderr(self):
+ """
+ Stderr of the process.
+ """
return self._stderr
@property
def error(self):
+ """
+ Error message of the process. It is `None` if the process is still running.
+ """
if self._result is None:
return None
return self._result.error
@property
def exit_code(self):
+ """
+ Exit code of the process. It is `None` if the process is still running.
+ """
if self._result is None:
return None
return self._result.exit_code
@@ -105,6 +124,9 @@ class AsyncProcessHandle:
)
async def disconnect(self) -> None:
+ """
+ Disconnects from the process. It does not kill the process. It only stops receiving events from the process.
+ """
self._wait.cancel()
# BUG: In Python 3.8 closing async generator can throw RuntimeError.
# await self._events.aclose()
@@ -130,6 +152,12 @@ class AsyncProcessHandle:
self._iteration_exception = handle_rpc_exception(e)
async def wait(self) -> ProcessResult:
+ """
+ Waits for the process to finish and returns the result.
+ If the process exits with a non-zero exit code, it throws a `ProcessExitException`.
+
+ :return: Process result
+ """
await self._wait
if self._iteration_exception:
raise self._iteration_exception
@@ -147,5 +175,9 @@ class AsyncProcessHandle:
return self._result
- async def kill(self):
+ async def kill(self) -> bool:
+ """
+ Kills the process.
+ :return: Whether the process was killed successfully
+ """
await self._handle_kill()
diff --git a/packages/python-sdk/e2b/sandbox_async/pty/main.py b/packages/python-sdk/e2b/sandbox_async/process/pty.py
similarity index 77%
rename from packages/python-sdk/e2b/sandbox_async/pty/main.py
rename to packages/python-sdk/e2b/sandbox_async/process/pty.py
index 2c66849c8..30fc0c658 100644
--- a/packages/python-sdk/e2b/sandbox_async/pty/main.py
+++ b/packages/python-sdk/e2b/sandbox_async/process/pty.py
@@ -21,6 +21,10 @@ from e2b.sandbox_async.process.process_handle import (
class Pty:
+ """
+ Manager for starting and interacting with PTY (pseudo-terminal) processes in the sandbox.
+ """
+
def __init__(
self,
envd_api_url: str,
@@ -41,6 +45,13 @@ class Pty:
pid: int,
request_timeout: Optional[float] = None,
) -> bool:
+ """
+ Kills a process.
+
+ :param pid: Process ID to kill. You can get the list of processes using `sandbox.commands.list()`.
+ :param request_timeout: Timeout for the request
+ :return: `true` if the process was killed, `false` if the process was not found
+ """
try:
await self._rpc.asend_signal(
process_pb2.SendSignalRequest(
@@ -63,7 +74,14 @@ class Pty:
pid: int,
data: bytes,
request_timeout: Optional[float] = None,
- ):
+ ) -> None:
+ """
+ Sends input to a PTY process.
+
+ :param pid: Process ID of the PTY process
+ :param data: Input data to send
+ :param request_timeout: Timeout for the request
+ """
try:
await self._rpc.asend_input(
process_pb2.SendInputRequest(
@@ -89,6 +107,18 @@ class Pty:
timeout: Optional[float] = 60,
request_timeout: Optional[float] = None,
) -> AsyncProcessHandle:
+ """
+ Starts a new process with a PTY (pseudo-terminal).
+
+ :param size: Size of the PTY
+ :param on_data: Callback for handling PTY output
+ :param user: User to start the process as
+ :param cwd: Current working directory
+ :param envs: Environment variables
+ :param timeout: Timeout for the request
+ :param request_timeout: Timeout for the request
+ :return: New process
+ """
envs = envs or {}
envs["TERM"] = "xterm-256color"
events = self._rpc.astart(
@@ -136,6 +166,13 @@ class Pty:
size: PtySize,
request_timeout: Optional[float] = None,
):
+ """
+ Resizes a PTY process (changes the number of columns and rows in the terminal).
+
+ :param pid: Process ID of the PTY process
+ :param size: New size of the PTY
+ :param request_timeout: Timeout for the request
+ """
await self._rpc.aupdate(
process_pb2.UpdateRequest(
process=process_pb2.ProcessSelector(pid=pid),
diff --git a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
index eea910554..0813176e2 100644
--- a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
@@ -19,6 +19,10 @@ from e2b.sandbox_sync.filesystem.watch_handle import WatchHandle
class Filesystem:
+ """
+ Manager for interacting with the filesystem in the sandbox.
+ """
+
def __init__(
self,
envd_api_url: str,
@@ -73,7 +77,15 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
):
- """Read from file"""
+ """
+ Reads a whole file content and returns it in requested format (text by default).
+
+ :param path: Path to the file
+ :param format: Format of the file content
+ :param user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ :return File content in requested format
+ """
r = self._envd_api.get(
ENVD_API_FILES_ROUTE,
params={"path": path, "username": user},
@@ -98,10 +110,17 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
) -> EntryInfo:
- """Write to file
+ """
+ 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, you'll get an error.
+
+ :param path: Path to the file
+ :param data: Data to write to the file
+ :param user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ :return: Information about the written file
"""
if isinstance(data, TextIOBase):
data = data.read().encode()
@@ -131,7 +150,14 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
) -> List[EntryInfo]:
- """List directory"""
+ """
+ Lists entries in a directory.
+
+ :param path: Path to the directory
+ :param user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ :return: List of entries in the directory
+ """
try:
res = self._rpc.list_dir(
filesystem_pb2.ListDirRequest(path=path),
@@ -160,7 +186,13 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
) -> bool:
- """Check if file exists."""
+ """
+ Checks if a file or a directory exists.
+
+ :param path: Path to a file or a directory
+ :param user Run the operation as this user
+ :param request_timeout Timeout for the request
+ """
try:
self._rpc.stat(
filesystem_pb2.StatRequest(path=path),
@@ -183,7 +215,12 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
) -> None:
- """Remove file"""
+ """
+ Removes a file or a directory.
+ :param path: Path to a file or a directory
+ :param user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ """
try:
self._rpc.remove(
filesystem_pb2.RemoveRequest(path=path),
@@ -202,7 +239,16 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
) -> EntryInfo:
- """Rename file"""
+ """
+ Renames a file or directory from one path to another.
+
+ :param old_path Path to the file or directory to move
+ :param new_path Path to move the file or directory to
+ :param user Run the operation as this user
+ :param request_timeout Timeout for the request
+
+ :return: Information about the renamed file or directory
+ """
try:
r = self._rpc.move(
filesystem_pb2.MoveRequest(
@@ -229,7 +275,14 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
) -> bool:
- """Create directory and all parent directories"""
+ """
+ Creates 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 user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ :return: True if the directory was created, False if the directory already exists
+ """
try:
self._rpc.make_dir(
filesystem_pb2.MakeDirRequest(path=path),
@@ -252,8 +305,17 @@ class Filesystem:
user: Username = "user",
request_timeout: Optional[float] = None,
timeout: Optional[float] = 60,
- ):
- """Watch directory for changes."""
+ ) -> WatchHandle:
+ """
+ Watches directory for filesystem events. The watch will be closed after the timeout.
+ To get the events, you need to iterate over the returned WatchHandle.
+
+ :param path: Path to a directory that will be watched
+ :param user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ :param timeout: Timeout for the watch, after which the watch will be closed
+ :return: Watcher handle
+ """
events = self._rpc.watch_dir(
filesystem_pb2.WatchDirRequest(path=path),
request_timeout=self._connection_config.get_request_timeout(
diff --git a/packages/python-sdk/e2b/sandbox_sync/filesystem/watch_handle.py b/packages/python-sdk/e2b/sandbox_sync/filesystem/watch_handle.py
index 3849d726f..b88f10b31 100644
--- a/packages/python-sdk/e2b/sandbox_sync/filesystem/watch_handle.py
+++ b/packages/python-sdk/e2b/sandbox_sync/filesystem/watch_handle.py
@@ -6,6 +6,10 @@ from e2b.sandbox.filesystem.watch_handle import FilesystemEvent, map_event_type
class WatchHandle:
+ """
+ Handle for watching filesystem events. It is used to iterate over the events in the watched directory.
+ """
+
def __init__(
self,
events: Generator[WatchDirResponse, Any, None],
@@ -16,6 +20,12 @@ class WatchHandle:
return self._handle_events()
def close(self):
+ """
+ Stop watching the directory.
+
+ Warning:
+ You won't get any event if you don't iterate over the handle before closing it.
+ """
self._events.close()
def _handle_events(self):
diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.py
index 4b88f4de2..9c6a231fb 100644
--- a/packages/python-sdk/e2b/sandbox_sync/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/main.py
@@ -8,8 +8,8 @@ from e2b.exceptions import SandboxException, format_request_timeout_error
from e2b.sandbox.main import SandboxSetup
from e2b.sandbox.utils import class_method_variant
from e2b.sandbox_sync.filesystem.filesystem import Filesystem
-from e2b.sandbox_sync.process.main import Process
-from e2b.sandbox_sync.pty.main import Pty
+from e2b.sandbox_sync.process.process import Process
+from e2b.sandbox_sync.process.pty import Pty
from e2b.sandbox_sync.sandbox_api import SandboxApi
logger = logging.getLogger(__name__)
@@ -28,33 +28,68 @@ class TransportWithLogger(httpx.HTTPTransport):
class Sandbox(SandboxSetup, SandboxApi):
+ """
+ E2B cloud sandbox gives your agent a full cloud development environment that's sandboxed.
+
+ That means:
+ - Access to Linux OS
+ - Using filesystem (create, list, and delete files and dirs)
+ - Run commands
+ - Sandboxed - you can run any code
+ - Access to the internet
+
+ Check usage docs - https://e2b.dev/docs/sandbox/overview
+
+ These cloud sandboxes are meant to be used for agents. Like a sandboxed playgrounds, where the agent can do whatever it wants.
+
+ Use the `Sandbox()` to create a new sandbox.
+
+ Example:
+ ```python
+ sandbox = Sandbox()
+ ```
+ """
+
@property
def files(self) -> Filesystem:
- """Get a Filesystem Object"""
+ """
+ Filesystem module for interacting with the sandbox's filesystem
+ """
return self._filesystem
@property
def commands(self) -> Process:
- """Get a Process Object"""
+ """
+ Commands module for interacting with the sandbox's processes
+ """
return self._process
@property
def pty(self) -> Pty:
+ """
+ PTY module for interacting with the sandbox's pseudo-terminal
+ """
return self._pty
@property
def sandbox_id(self) -> str:
- """Get the sandbox ID"""
+ """
+ Unique identifier of the sandbox
+ """
return self._sandbox_id
@property
def envd_api_url(self) -> str:
- """Get the sanbox API URL"""
+ """
+ Get the sandbox API URL
+ """
return self._envd_api_url
@property
def connection_config(self) -> ConnectionConfig:
- """Get the ConnectionConfig Object"""
+ """
+ Get the ConnectionConfig object
+ """
return self._connection_config
def __init__(
@@ -129,7 +164,20 @@ class Sandbox(SandboxSetup, SandboxApi):
)
def is_running(self, request_timeout: Optional[float] = None) -> bool:
- """Check if sandbox is running"""
+ """
+ Check if the sandbox is running.
+
+ :return: `True` if the sandbox is running, `False` otherwise
+
+ Example
+ ```python
+ sandbox = Sandbox()
+ sandbox.is_running() # Returns True
+
+ sandbox.kill()
+ sandbox.is_running() # Returns False
+ ```
+ """
try:
r = self._envd_api.get(
ENVD_API_HEALTH_ROUTE,
@@ -157,7 +205,22 @@ class Sandbox(SandboxSetup, SandboxApi):
domain: Optional[str] = None,
debug: Optional[bool] = None,
):
- """Connect to a running sandbox"""
+ """
+ Connects to an existing Sandbox.
+ :param sandbox_id: Sandbox ID
+ :param api_key: E2B API Key
+ :param domain: E2B Domain (use only if you self-host E2B)
+ :param debug: For developing purposes, uses a local sandbox
+ :return: Sandbox object
+
+ @example
+ ```python
+ sandbox = Sandbox()
+ sandbox_id = sandbox.sandbox_id
+
+ # Another code block
+ same_sandbox = Sandbox.connect(sandbox_id)
+ """
return cls(
sandbox_id=sandbox_id,
api_key=api_key,
@@ -186,7 +249,12 @@ class Sandbox(SandboxSetup, SandboxApi):
@class_method_variant("_cls_kill")
def kill(self, request_timeout: Optional[float] = None) -> bool: # type: ignore
- """Kill sandbox"""
+ """
+ Kill the sandbox.
+
+ :param request_timeout: Timeout for the request
+ :return: `True` if the sandbox was killed, `False` if the sandbox was not found
+ """
config_dict = self.connection_config.__dict__
config_dict.pop("access_token", None)
config_dict.pop("api_url", None)
@@ -205,7 +273,6 @@ class Sandbox(SandboxSetup, SandboxApi):
timeout: int,
request_timeout: Optional[float] = None,
) -> None: ...
-
@overload
@staticmethod
def set_timeout(
@@ -216,14 +283,20 @@ class Sandbox(SandboxSetup, SandboxApi):
debug: Optional[bool] = None,
request_timeout: Optional[float] = None,
) -> None: ...
-
@class_method_variant("_cls_set_timeout")
def set_timeout( # type: ignore
self,
timeout: int,
request_timeout: Optional[float] = None,
) -> None:
- """Configure sandbox timeout"""
+ """
+ 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.
+
+ :param timeout: Duration in milliseconds. Must be between 0 and 86400000 milliseconds (24 hours).
+ :param request_timeout: Timeout for the request
+ """
config_dict = self.connection_config.__dict__
config_dict.pop("access_token", None)
config_dict.pop("api_url", None)
diff --git a/packages/python-sdk/e2b/sandbox_sync/process/main.py b/packages/python-sdk/e2b/sandbox_sync/process/process.py
similarity index 79%
rename from packages/python-sdk/e2b/sandbox_sync/process/main.py
rename to packages/python-sdk/e2b/sandbox_sync/process/process.py
index 99e50ab0f..41d591660 100644
--- a/packages/python-sdk/e2b/sandbox_sync/process/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/process/process.py
@@ -36,7 +36,12 @@ class Process:
self,
request_timeout: Optional[float] = None,
) -> List[ProcessInfo]:
- """List processes"""
+ """
+ Lists all running processes.
+
+ :param request_timeout: Request timeout
+ :return: List of running processes
+ """
try:
res = self._rpc.list(
process_pb2.ListRequest(),
@@ -63,7 +68,13 @@ class Process:
pid: int,
request_timeout: Optional[float] = None,
) -> bool:
- """Kill process"""
+ """
+ Kills a process.
+
+ :param pid: Process ID to connect to. You can get the list of processes using `sandbox.commands.list()`.
+ :param request_timeout: Request timeout
+ :return: `True` if the process was killed, `False` if the process was not found
+ """
try:
self._rpc.send_signal(
process_pb2.SendSignalRequest(
@@ -87,7 +98,13 @@ class Process:
data: str,
request_timeout: Optional[float] = None,
):
- """Send stdin"""
+ """
+ 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 request_timeout: Request timeout
+ """
try:
self._rpc.send_input(
process_pb2.SendInputRequest(
@@ -143,7 +160,21 @@ class Process:
timeout: Optional[float] = 60,
request_timeout: Optional[float] = None,
):
- """Run command"""
+ """
+ Starts a new process and depending on the `background` parameter, waits for the process to finish or not.
+ :param cmd Command to execute
+ :param background:
+ If `True`, the function will return a `ProcessHandle` object that can be used to interact with the process.
+ If `False`, the function will wait for the process to finish and return a `ProcessResult` object.
+ :param envs: Environment variables
+ :param user: User to run the process as
+ :param cwd: Working directory
+ :param on_stdout: Callback for stdout
+ :param on_stderr: Callback for stderr
+ :param timeout: Timeout for the maximum time the process is allowed to run
+ :param request_timeout: Timeout for the request
+ :return: `ProcessHandle` if `background` is `True`, `ProcessResult` if `background` is `False`
+ """
proc = self._start(
cmd,
envs,
@@ -212,7 +243,13 @@ class Process:
timeout: Optional[float] = 60,
request_timeout: Optional[float] = None,
):
- """Connect to process"""
+ """
+ Connects to an existing process.
+
+ :param pid: Process ID to connect to. You can get the list of processes using `sandbox.commands.list()`.
+ :param timeout: Timeout for the connection
+ :param request_timeout: Request timeout
+ """
events = self._rpc.connect(
process_pb2.ConnectRequest(
process=process_pb2.ProcessSelector(pid=pid),
diff --git a/packages/python-sdk/e2b/sandbox_sync/process/process_handle.py b/packages/python-sdk/e2b/sandbox_sync/process/process_handle.py
index dda49b612..5de9af4bd 100644
--- a/packages/python-sdk/e2b/sandbox_sync/process/process_handle.py
+++ b/packages/python-sdk/e2b/sandbox_sync/process/process_handle.py
@@ -12,8 +12,16 @@ from e2b.sandbox.process.process_handle import (
class ProcessHandle:
+ """
+ Class representing a process. It provides methods for waiting and killing the process.
+ It is also used to iterate over the process output.
+ """
+
@property
def pid(self):
+ """
+ Get the process ID.
+ """
return self._pid
def __init__(
@@ -69,6 +77,9 @@ class ProcessHandle:
)
def disconnect(self) -> None:
+ """
+ Disconnect from the process. It does not kill the process. It only stops receiving events from the process.
+ """
self._events.close()
def wait(
@@ -77,6 +88,15 @@ class ProcessHandle:
on_stdout: Optional[Callable[[str], None]] = None,
on_stderr: Optional[Callable[[str], None]] = None,
) -> ProcessResult:
+ """
+ Waits for the process to finish and returns the result.
+ If the process exits with a non-zero exit code, it throws a `ProcessExitException`.
+
+ :param on_pty: Callback for pty output
+ :param on_stdout: Callback for stdout output
+ :param on_stderr: Callback for stderr output
+ :return: Process result
+ """
try:
for stdout, stderr, pty in self:
if stdout is not None and on_stdout:
@@ -106,5 +126,9 @@ class ProcessHandle:
return self._result
- def kill(self):
- self._handle_kill()
+ def kill(self) -> bool:
+ """
+ Kills the process.
+ :return: Whether the process was killed successfully
+ """
+ return self._handle_kill()
diff --git a/packages/python-sdk/e2b/sandbox_sync/pty/main.py b/packages/python-sdk/e2b/sandbox_sync/process/pty.py
similarity index 78%
rename from packages/python-sdk/e2b/sandbox_sync/pty/main.py
rename to packages/python-sdk/e2b/sandbox_sync/process/pty.py
index b170aa2d8..92099f5d3 100644
--- a/packages/python-sdk/e2b/sandbox_sync/pty/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/process/pty.py
@@ -17,6 +17,10 @@ from e2b.sandbox_sync.process.process_handle import ProcessHandle
class Pty:
+ """
+ Manager for starting and interacting with PTY (pseudo-terminal) processes in the sandbox.
+ """
+
def __init__(
self,
envd_api_url: str,
@@ -37,6 +41,13 @@ class Pty:
pid: int,
request_timeout: Optional[float] = None,
) -> bool:
+ """
+ Kills a process.
+
+ :param pid: Process ID to kill. You can get the list of processes using `sandbox.commands.list()`.
+ :param request_timeout: Timeout for the request
+ :return: `true` if the process was killed, `false` if the process was not found
+ """
try:
self._rpc.send_signal(
process_pb2.SendSignalRequest(
@@ -60,6 +71,13 @@ class Pty:
data: bytes,
request_timeout: Optional[float] = None,
) -> None:
+ """
+ Sends input to a PTY process.
+
+ :param pid: Process ID of the PTY process
+ :param data: Input data to send
+ :param request_timeout: Timeout for the request
+ """
try:
self._rpc.send_input(
process_pb2.SendInputRequest(
@@ -84,6 +102,17 @@ class Pty:
timeout: Optional[float] = 60,
request_timeout: Optional[float] = None,
) -> ProcessHandle:
+ """
+ Starts a new process with a PTY (pseudo-terminal).
+
+ :param size: Size of the PTY
+ :param user: User to start the process as
+ :param cwd: Current working directory
+ :param envs: Environment variables
+ :param timeout: Timeout for the request
+ :param request_timeout: Timeout for the request
+ :return: New process
+ """
envs = envs or {}
envs["TERM"] = "xterm-256color"
events = self._rpc.start(
@@ -130,6 +159,13 @@ class Pty:
size: PtySize,
request_timeout: Optional[float] = None,
) -> None:
+ """
+ Resizes a PTY process (changes the number of columns and rows in the terminal).
+
+ :param pid: Process ID of the PTY process
+ :param size: New size of the PTY
+ :param request_timeout: Timeout for the request
+ """
self._rpc.update(
process_pb2.UpdateRequest(
process=process_pb2.ProcessSelector(pid=pid),
diff --git a/packages/python-sdk/tests/async/sandbox_async/pty/test_pty_create.py b/packages/python-sdk/tests/async/sandbox_async/pty/test_pty_create.py
index a2009da55..12eb76f58 100644
--- a/packages/python-sdk/tests/async/sandbox_async/pty/test_pty_create.py
+++ b/packages/python-sdk/tests/async/sandbox_async/pty/test_pty_create.py
@@ -5,7 +5,7 @@ from e2b.sandbox.process.process_handle import PtySize
async def test_pty_create(async_sandbox: AsyncSandbox):
output = []
- def append_data(data:list, x: bytes):
+ def append_data(data: list, x: bytes):
data.append(x.decode("utf-8"))
terminal = await async_sandbox.pty.create(
@@ -18,4 +18,4 @@ async def test_pty_create(async_sandbox: AsyncSandbox):
await terminal.wait()
assert terminal.exit_code == 0
- assert "123" in ''.join(output)
+ assert "123" in "".join(output)
diff --git a/packages/python-sdk/tests/async/sandbox_async/pty/test_resize.py b/packages/python-sdk/tests/async/sandbox_async/pty/test_resize.py
index d49db52dd..3e91805de 100644
--- a/packages/python-sdk/tests/async/sandbox_async/pty/test_resize.py
+++ b/packages/python-sdk/tests/async/sandbox_async/pty/test_resize.py
@@ -8,18 +8,22 @@ async def test_resize(async_sandbox: AsyncSandbox):
def append_data(data: list, x: bytes):
data.append(x.decode("utf-8"))
- terminal = await async_sandbox.pty.create(PtySize(cols=80, rows=24), on_data=lambda x: append_data(output, x))
+ terminal = await async_sandbox.pty.create(
+ PtySize(cols=80, rows=24), on_data=lambda x: append_data(output, x)
+ )
await async_sandbox.pty.send_stdin(terminal.pid, b"tput cols\n")
await async_sandbox.pty.send_stdin(terminal.pid, b"exit\n")
await terminal.wait()
assert terminal.exit_code == 0
- assert "80" in ''.join(output)
+ assert "80" in "".join(output)
output = []
- terminal = await async_sandbox.pty.create(PtySize(cols=80, rows=24), on_data=lambda x: append_data(output, x))
+ terminal = await async_sandbox.pty.create(
+ PtySize(cols=80, rows=24), on_data=lambda x: append_data(output, x)
+ )
await async_sandbox.pty.resize(terminal.pid, PtySize(cols=100, rows=24))
await async_sandbox.pty.send_stdin(terminal.pid, b"tput cols\n")
@@ -27,5 +31,4 @@ async def test_resize(async_sandbox: AsyncSandbox):
await terminal.wait()
assert terminal.exit_code == 0
- assert "100" in ''.join(output)
-
+ assert "100" in "".join(output)
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/pty/test_pty.py b/packages/python-sdk/tests/sync/sandbox_sync/pty/test_pty.py
index 6ed9219f2..9f815e02c 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/pty/test_pty.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/pty/test_pty.py
@@ -3,12 +3,10 @@ from e2b.sandbox.process.process_handle import PtySize
def test_pty(sandbox: Sandbox):
- def append_data(data:list, x: bytes):
+ def append_data(data: list, x: bytes):
data.append(x.decode("utf-8"))
- terminal = sandbox.pty.create(
- PtySize(80, 24), envs={"ABC": "123"}, cwd="/"
- )
+ terminal = sandbox.pty.create(PtySize(80, 24), envs={"ABC": "123"}, cwd="/")
sandbox.pty.send_stdin(terminal.pid, b"echo $ABC\nexit\n")
@@ -16,4 +14,4 @@ def test_pty(sandbox: Sandbox):
result = terminal.wait(on_pty=lambda x: append_data(output, x))
assert result.exit_code == 0
- assert "123" in '\n'.join(output)
+ assert "123" in "\n".join(output)
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/pty/test_resize.py b/packages/python-sdk/tests/sync/sandbox_sync/pty/test_resize.py
index be7d3c806..dba9fad6c 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/pty/test_resize.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/pty/test_resize.py
@@ -3,7 +3,7 @@ from e2b.sandbox.process.process_handle import PtySize
def test_resize(sandbox: Sandbox):
- def append_data(data:list, x: bytes):
+ def append_data(data: list, x: bytes):
data.append(x.decode("utf-8"))
terminal = sandbox.pty.create(PtySize(cols=80, rows=24))
@@ -14,7 +14,7 @@ def test_resize(sandbox: Sandbox):
result = terminal.wait(on_pty=lambda x: append_data(output, x))
assert result.exit_code == 0
- assert "80" in ''.join(output)
+ assert "80" in "".join(output)
terminal = sandbox.pty.create(PtySize(cols=80, rows=24))
@@ -25,5 +25,4 @@ def test_resize(sandbox: Sandbox):
result = terminal.wait(on_pty=lambda x: append_data(output, x))
assert result.exit_code == 0
- assert "100" in ''.join(output)
-
+ assert "100" in "".join(output)