Skip to content

armgit / E2B

Public Imported from GitHub
0

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

merge main

0div97d0cc1ef5fc
diff --cc packages/js-sdk/src/errors.ts
index 9e26f74c6,c4d472f5b..810888b9e
--- a/packages/js-sdk/src/errors.ts
+++ b/packages/js-sdk/src/errors.ts
@@@ -6,9 -6,9 +6,11 @@@ export function formatSandboxTimeoutErr
}
/**
+ * Thrown when a sandbox error occurs.
+ *
* Base class for all sandbox errors.
+ *
+ * Thrown when general sandbox errors occur.
*/
export class SandboxError extends Error {
constructor(message: any) {
diff --cc packages/js-sdk/src/index.ts
index bfd1b6cca,61541c133..05f304c0e
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@@ -1,34 -1,48 +1,47 @@@
export { ApiClient } from './api'
export type { components, paths } from './api'
+export { ConnectionConfig } from './connectionConfig'
+export type { ConnectionOpts, Username } from './connectionConfig'
export {
AuthenticationError,
- SandboxError,
- TimeoutError,
- NotFoundError,
- NotEnoughSpaceError,
InvalidArgumentError,
+ NotEnoughSpaceError,
+ NotFoundError,
+ SandboxError,
TemplateError,
+ TimeoutError,
} from './errors'
-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, WatchOpts } from './sandbox/filesystem'
export { FileType } from './sandbox/filesystem'
+export type { EntryInfo, Filesystem, WriteData } from './sandbox/filesystem'
+export { FilesystemEventType } from './sandbox/filesystem/watchHandle'
+export type { FilesystemEvent, WatchHandle } from './sandbox/filesystem/watchHandle'
- export { ProcessExitError } from './sandbox/process/processHandle'
- export type { ProcessHandle, ProcessResult, PtyOutput, Stderr, Stdout } from './sandbox/process/processHandle'
+ export { CommandExitError } from './sandbox/commands/commandHandle'
+ export type {
+ CommandResult,
+ Stdout,
+ Stderr,
+ PtyOutput,
+ CommandHandle,
+ } from './sandbox/commands/commandHandle'
export type { SandboxApiOpts } from './sandbox/sandboxApi'
- export type { Process, ProcessConnectOpts, ProcessInfo, ProcessRequestOpts, ProcessStartOpts } from './sandbox/process'
+ export type {
+ ProcessInfo,
+ CommandRequestOpts,
+ CommandConnectOpts,
+ CommandStartOpts,
+ Commands,
+ Pty,
+ } from './sandbox/commands'
-export type { SandboxInfo } from './sandbox/sandboxApi'
+export type { Pty } from './sandbox/pty'
+
export type { SandboxOpts } from './sandbox'
-import { Sandbox } from './sandbox'
+export type { SandboxInfo } from './sandbox/sandboxApi'
export { Sandbox }
+import { Sandbox } from './sandbox'
export default Sandbox
diff --cc packages/js-sdk/src/sandbox/filesystem/index.ts
index 770d850ae,f65003ae8..c330b88cc
--- a/packages/js-sdk/src/sandbox/filesystem/index.ts
+++ b/packages/js-sdk/src/sandbox/filesystem/index.ts
@@@ -1,28 -1,42 +1,42 @@@
- import { Code, ConnectError, createPromiseClient, PromiseClient, Transport } from '@connectrpc/connect'
+ import {
+ createClient,
+ Transport,
+ Client,
+ ConnectError,
+ Code,
+ } from '@connectrpc/connect'
import {
ConnectionConfig,
- defaultUsername,
- Username,
ConnectionOpts,
- KEEPALIVE_PING_INTERVAL_SEC,
+ defaultUsername,
KEEPALIVE_PING_HEADER,
+ KEEPALIVE_PING_INTERVAL_SEC,
+ Username,
} from '../../connectionConfig'
import { handleEnvdApiError, handleWatchDirStartEvent } from '../../envd/api'
import { authenticationHeader, handleRpcError } from '../../envd/rpc'
import { EnvdApiClient } from '../../envd/api'
- import { Filesystem as FilesystemService } from '../../envd/filesystem/filesystem_connect'
- import { FileType as FsFileType } from '../../envd/filesystem/filesystem_pb'
+ import { FileType as FsFileType, Filesystem as FilesystemService } from '../../envd/filesystem/filesystem_pb'
-import { WatchHandle, FilesystemEvent } from './watchHandle'
+import { FilesystemEvent, WatchHandle } from './watchHandle'
/**
- * Information about a filesystem object.
+ * Sandbox filesystem object information.
*/
export interface EntryInfo {
+ /**
+ * Name of the filesystem object.
+ */
name: string
+ /**
+ * Type of the filesystem object.
+ */
type?: FileType
+ /**
+ * Path to the filesystem object.
+ */
path: string
}
@@@ -130,45 -205,27 +212,50 @@@ export class Filesystem
}
/**
- * Writes content to a file on the path.
- * When writing to a file that doesn't exist, the file will get created.
- * When writing to a file that already exists, the file will get overwritten.
- * When writing to a file that's in a directory that doesn't exist, the directory will get created.
+ * Write content to a file.
+ *
+ *
+ * Writing to a file that doesn't exist creates the file.
+ *
+ * Writing to a file that already exists overwrites the file.
*
- * @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
+ * Writing to a file at path that doesn't exist creates the necessary directories.
+ *
+ * @param path path to file.
+ * @param data data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`.
+ * @param opts connection options.
+ *
+ * @returns information about the written file
*/
+ async write(path: string, data: WriteData, opts?: FilesystemRequestOpts): Promise<EntryInfo>
+ async write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise<EntryInfo[]>
async write(
- path: string,
- data: string | ArrayBuffer | Blob | ReadableStream,
+ pathOrFiles: string | WriteEntry[],
+ dataOrOpts?: WriteData | FilesystemRequestOpts,
opts?: FilesystemRequestOpts
- ): Promise<EntryInfo> {
- const blob = await new Response(data).blob()
+ ): Promise<EntryInfo | EntryInfo[]> {
+ if (typeof pathOrFiles !== 'string' && !Array.isArray(pathOrFiles)) {
+ throw new Error('Path or files are required')
+ }
+
+ if (typeof pathOrFiles === 'string' && Array.isArray(dataOrOpts)) {
+ throw new Error(
+ 'Cannot specify both path and array of files. You have to specify either path and data for a single file or an array for multiple files.'
+ )
+ }
+
+ const { path, writeOpts, writeFiles } =
+ typeof pathOrFiles === 'string'
+ ? {
+ path: pathOrFiles,
+ writeOpts: opts as FilesystemRequestOpts,
+ writeFiles: [{ data: dataOrOpts as WriteData }],
+ }
+ : { path: undefined, writeOpts: dataOrOpts as FilesystemRequestOpts, writeFiles: pathOrFiles as WriteEntry[] }
+
+ if (writeFiles.length === 0) return [] as EntryInfo[]
+
+ const blobs = await Promise.all(writeFiles.map((f) => new Response(f.data).blob()))
const res = await this.envdApi.api.POST('/files', {
params: {
@@@ -178,18 -235,17 +265,21 @@@
},
},
bodySerializer() {
- const fd = new FormData()
-
- fd.append('file', blob)
-
- return fd
+ return blobs.reduce((fd, blob, i) => {
+ // Important: RFC 7578, Section 4.2 requires that if a filename is provided,
+ // the directory path information must not be used.
+ // BUT in our case we need to use the directory path information with a custom
+ // muktipart part name getter in envd.
+ fd.append('file', blob, writeFiles[i].path)
+
+ return fd
+ }, new FormData())
},
body: {},
- signal: this.connectionConfig.getSignal(writeOpts?.requestTimeoutMs),
+ headers: {
+ 'Content-Type': 'multipart/form-data',
+ 'Bun-Content-Type': 'temporary-fix', // https://github.com/oven-sh/bun/issues/14988
+ },
})
const err = await handleEnvdApiError(res)
@@@ -272,14 -330,19 +364,15 @@@
}
/**
- * Renames a file or directory from one path to another.
+ * Rename a file or directory.
+ *
+ * @param oldPath path to the file or directory to rename.
+ * @param newPath new path for the file or directory.
+ * @param opts connection options.
*
- * @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
+ * @returns information about renamed file or directory.
*/
- async rename(
- oldPath: string,
- newPath: string,
- opts?: FilesystemRequestOpts
- ): Promise<EntryInfo> {
+ async rename(oldPath: string, newPath: string, opts?: FilesystemRequestOpts): Promise<EntryInfo> {
try {
const res = await this.rpc.move(
{
@@@ -356,19 -421,21 +451,20 @@@
}
/**
- * Watches directory for filesystem events.
+ * Start watching a directory for filesystem events.
+ *
+ * @param path path to directory to watch.
+ * @param onEvent callback to call when an event in the directory occurs.
+ * @param opts connection options.
*
- * @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
+ * @returns `WatchHandle` object for stopping watching directory.
*/
- async watch(
+ async watchDir(
path: string,
onEvent: (event: FilesystemEvent) => void | Promise<void>,
- opts?: FilesystemRequestOpts & { timeout?: number; onExit?: (err?: Error) => void | Promise<void> }
+ opts?: WatchOpts
): Promise<WatchHandle> {
- const requestTimeoutMs =
- opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
+ const requestTimeoutMs = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
const controller = new AbortController()
diff --cc packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
index 3eb575791,9e04a3975..9ccc017f9
--- a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
@@@ -28,18 -34,14 +34,27 @@@ class EntryInfo
"""
name: str
+ """
+ Name of the filesystem object.
+ """
type: Optional[FileType]
+ """
+ Type of the filesystem object.
+ """
path: str
+ """
+ Path to the filesystem object.
+ """
+
+
+WriteData = Union[str, bytes, IO]
+
+
+@dataclass
+class WriteEntry:
+ """
+ Contains path and data of the file to be written to the filesystem.
+ """
+
+ path: str
+ data: WriteData
diff --cc packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
index 720b7c74d,216147c78..b55849781
--- a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
@@@ -115,75 -137,23 +139,79 @@@ class Filesystem
request_timeout: Optional[float] = None,
) -> 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, the directory will get created.
+ Write content to a file on the path.
+
+ Writing to a file that doesn't exist creates the file.
+
+ Writing to a file that already exists overwrites the file.
+
+ Writing to a file at path that doesn't exist creates the necessary directories.
:param path: Path to the file
- :param data: Data to write to the file
+ :param data: Data to write to the file, can be a `str`, `bytes`, or `IO`.
:param user: Run the operation as this user
- :param request_timeout: Timeout for the request
+ :param request_timeout: Timeout for the request in **seconds**
+
:return: Information about the written file
"""
- if isinstance(data, TextIOBase):
- data = data.read().encode()
+
+ @overload
+ async def write(
+ self,
+ files: List[WriteEntry],
+ user: Optional[Username] = "user",
+ request_timeout: Optional[float] = None,
+ ) -> List[EntryInfo]:
+ """
+ Writes multiple files.
+
+ :param files: list of files to write
+ :param user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ :return: Information about the written files
+ """
+
+ async def write(
+ self,
+ path_or_files: str | List[WriteEntry],
+ data_or_user: WriteData | Username = "user",
+ user_or_request_timeout: Optional[float | Username] = None,
+ request_timeout_or_none: Optional[float] = None
+ ) -> EntryInfo | List[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.
+ """
+ path, write_files, user, request_timeout = None, [], "user", None
+ if isinstance(path_or_files, str):
+ if isinstance(data_or_user, list):
+ raise Exception("Cannot specify both path and array of files. You have to specify either path and data for a single file or an array for multiple files.")
+ path, write_files, user, request_timeout = \
+ path_or_files, [{"path": path_or_files, "data": data_or_user}], user_or_request_timeout or "user", request_timeout_or_none
+ else:
+ if path_or_files is None:
+ raise Exception("Path or files are required")
+ path, write_files, user, request_timeout = \
+ None, path_or_files, data_or_user, user_or_request_timeout
+
+ # Prepare the files for the multipart/form-data request
+ httpx_files = []
+ for file in write_files:
+ file_path, file_data = file['path'], file['data']
+ if isinstance(file_data, str) or isinstance(file_data, bytes):
+ httpx_files.append(('file', (file_path, file_data)))
+ elif isinstance(file_data, TextIOBase):
+ httpx_files.append(('file', (file_path, file_data.read())))
+ else:
+ raise ValueError(f"Unsupported data type for file {file_path}")
+
+ # Allow passing empty list of files
+ if len(httpx_files) == 0: return []
+
+ params = {"username": user}
+ if path is not None: params["path"] = path
r = await self._envd_api.post(
ENVD_API_FILES_ROUTE,
diff --cc packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
index 015d9e8c2,094d82a71..915e3f4d3
--- a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
@@@ -113,72 -134,23 +136,76 @@@ class Filesystem
request_timeout: Optional[float] = None,
) -> 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, the directory will get created.
+ Write content to a file on the path.
+
+ Writing to a file that doesn't exist creates the file.
+
+ Writing to a file that already exists overwrites the file.
+
+ Writing to a file at path that doesn't exist creates the necessary directories.
:param path: Path to the file
- :param data: Data to write to the file
+ :param data: Data to write to the file, can be a `str`, `bytes`, or `IO`.
:param user: Run the operation as this user
- :param request_timeout: Timeout for the request
+ :param request_timeout: Timeout for the request in **seconds**
+
:return: Information about the written file
"""
- if isinstance(data, TextIOBase):
- data = data.read().encode()
+
+ @overload
+ def write(
+ self,
+ files: List[WriteEntry],
+ user: Optional[Username] = "user",
+ request_timeout: Optional[float] = None,
+ ) -> List[EntryInfo]:
+ """
+ Writes a list of files to the filesystem.
+ 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 files: list of files to write
+ :param user: Run the operation as this user
+ :param request_timeout: Timeout for the request
+ :return: Information about the written files
+ """
+
+ def write(
+ self,
+ path_or_files: str | List[WriteEntry],
+ data_or_user: WriteData | Username = "user",
+ user_or_request_timeout: Optional[float | Username] = None,
+ request_timeout_or_none: Optional[float] = None
+ ) -> EntryInfo | List[EntryInfo]:
+ path, write_files, user, request_timeout = None, [], "user", None
+ if isinstance(path_or_files, str):
+ if isinstance(data_or_user, list):
+ raise Exception("Cannot specify both path and array of files. You have to specify either path and data for a single file or an array for multiple files.")
+ path, write_files, user, request_timeout = \
+ path_or_files, [{"path": path_or_files, "data": data_or_user}], user_or_request_timeout or "user", request_timeout_or_none
+ else:
+ if path_or_files is None:
+ raise Exception("Path or files are required")
+ path, write_files, user, request_timeout = \
+ None, path_or_files, data_or_user, user_or_request_timeout
+
+ # Prepare the files for the multipart/form-data request
+ httpx_files = []
+ for file in write_files:
+ file_path, file_data = file['path'], file['data']
+ if isinstance(file_data, str) or isinstance(file_data, bytes):
+ httpx_files.append(('file', (file_path, file_data)))
+ elif isinstance(file_data, TextIOBase):
+ httpx_files.append(('file', (file_path, file_data.read())))
+ else:
+ raise ValueError(f"Unsupported data type for file {file_path}")
+
+ # Allow passing empty list of files
+ if len(httpx_files) == 0: return []
+
+ params = {"username": user}
+ if path is not None: params["path"] = path
r = self._envd_api.post(
ENVD_API_FILES_ROUTE,