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 public-facing template methods (#943)

Mish Ushakov73114272e086
diff --git a/.changeset/fresh-dolphins-listen.md b/.changeset/fresh-dolphins-listen.md
new file mode 100644
index 000000000..059a46de7
--- /dev/null
+++ b/.changeset/fresh-dolphins-listen.md
@@ -0,0 +1,6 @@
+---
+'@e2b/python-sdk': patch
+'e2b': patch
+---
+
+added docstrings
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index bb0612215..393c04c1b 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -64,7 +64,12 @@ export default Sandbox
export { BuildError, FileUploadError } from './template/errors'
-export type { CopyItem } from './template/types'
+export type {
+ BuildOptions,
+ CopyItem,
+ TemplateBuilder,
+ TemplateClass,
+} from './template/types'
export {
waitForPort,
@@ -82,9 +87,4 @@ export {
defaultBuildLogger,
} from './template/logger'
-export {
- Template,
- type TemplateClass,
- type TemplateBuilder,
- type TemplateBase,
-} from './template'
+export { Template, type TemplateBase } from './template'
diff --git a/packages/js-sdk/src/template/consts.ts b/packages/js-sdk/src/template/consts.ts
index c4ba56511..007a63c6a 100644
--- a/packages/js-sdk/src/template/consts.ts
+++ b/packages/js-sdk/src/template/consts.ts
@@ -1,12 +1,34 @@
+/**
+ * Special step name for the finalization phase of template building.
+ * This is the last step that runs after all user-defined instructions.
+ * @internal
+ */
export const FINALIZE_STEP_NAME = 'finalize'
+
+/**
+ * Special step name for the base image phase of template building.
+ * This is the first step that sets up the base image.
+ * @internal
+ */
export const BASE_STEP_NAME = 'base'
/**
- * Depths explained:
- * 1. Template
- * 2. TemplateBase
- * 3. Caller method (eg. copy(), fromImage(), etc.)
+ * Stack trace depth for capturing caller information.
+ *
+ * Depth levels:
+ * 1. Template function
+ * 2. TemplateBase class
+ * 3. Caller method (e.g., copy(), fromImage(), etc.)
+ *
+ * This depth is used to determine the original caller's location
+ * for stack traces.
+ * @internal
*/
export const STACK_TRACE_DEPTH = 3
+/**
+ * Default setting for whether to resolve symbolic links when copying files.
+ * When false, symlinks are copied as symlinks rather than following them.
+ * @internal
+ */
export const RESOLVE_SYMLINKS = false
diff --git a/packages/js-sdk/src/template/errors.ts b/packages/js-sdk/src/template/errors.ts
index f61e5c2d9..ef221997c 100644
--- a/packages/js-sdk/src/template/errors.ts
+++ b/packages/js-sdk/src/template/errors.ts
@@ -1,3 +1,6 @@
+/**
+ * Thrown when the build fails.
+ */
export class BuildError extends Error {
constructor(message: string, stackTrace?: string) {
super(message)
@@ -8,6 +11,9 @@ export class BuildError extends Error {
}
}
+/**
+ * Thrown when the file upload fails.
+ */
export class FileUploadError extends BuildError {
constructor(message: string, stackTrace?: string) {
super(message, stackTrace)
diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.ts
index a249ef572..5573ed954 100644
--- a/packages/js-sdk/src/template/index.ts
+++ b/packages/js-sdk/src/template/index.ts
@@ -15,13 +15,16 @@ import { parseDockerfile } from './dockerfileParser'
import { LogEntry, LogEntryEnd, LogEntryStart } from './logger'
import { ReadyCmd } from './readycmd'
import {
+ BuildOptions,
CopyItem,
Instruction,
InstructionType,
RegistryConfig,
TemplateBuilder,
+ TemplateClass,
TemplateFinal,
TemplateFromImage,
+ TemplateOptions,
} from './types'
import {
calculateFilesHash,
@@ -32,26 +35,9 @@ import {
readGCPServiceAccountJSON,
} from './utils'
-export { type TemplateBuilder } from './types'
-
-type TemplateOptions = {
- fileContextPath?: PathLike
- fileIgnorePatterns?: string[]
-}
-
-type BasicBuildOptions = {
- alias: string
- cpuCount?: number
- memoryMB?: number
- skipCache?: boolean
- onBuildLogs?: (logEntry: LogEntry) => void
-}
-
-export type BuildOptions = BasicBuildOptions & {
- apiKey?: string
- domain?: string
-}
-
+/**
+ * Base class for building E2B sandbox templates.
+ */
export class TemplateBase
implements TemplateFromImage, TemplateBuilder, TemplateFinal
{
@@ -79,6 +65,13 @@ export class TemplateBase
options?.fileIgnorePatterns ?? this.fileIgnorePatterns
}
+ /**
+ * Convert a template to JSON representation.
+ *
+ * @param template The template to convert
+ * @param computeHashes Whether to compute file hashes for cache invalidation
+ * @returns JSON string representation of the template
+ */
static toJSON(
template: TemplateClass,
computeHashes: boolean = true
@@ -86,10 +79,34 @@ export class TemplateBase
return (template as TemplateBase).toJSON(computeHashes)
}
+ /**
+ * Convert a template to Dockerfile format.
+ * Note: Templates based on other E2B templates cannot be converted to Dockerfile.
+ *
+ * @param template The template to convert
+ * @returns Dockerfile string representation
+ * @throws Error if the template is based on another E2B template
+ */
static toDockerfile(template: TemplateClass): string {
return (template as TemplateBase).toDockerfile()
}
+ /**
+ * Build and deploy a template to E2B infrastructure.
+ *
+ * @param template The template to build
+ * @param options Build configuration options
+ *
+ * @example
+ * ```ts
+ * const template = Template().fromPythonImage('3')
+ * await Template.build(template, {
+ * alias: 'my-python-env',
+ * cpuCount: 2,
+ * memoryMB: 1024
+ * })
+ * ```
+ */
static async build(
template: TemplateClass,
options: BuildOptions
@@ -102,8 +119,7 @@ export class TemplateBase
}
}
- // Built-in image mixins
- fromDebianImage(variant: string = 'slim'): TemplateBuilder {
+ fromDebianImage(variant: string = 'stable'): TemplateBuilder {
return this.fromImage(`debian:${variant}`)
}
@@ -111,7 +127,7 @@ export class TemplateBase
return this.fromImage(`ubuntu:${variant}`)
}
- fromPythonImage(version: string = '3.13'): TemplateBuilder {
+ fromPythonImage(version: string = '3'): TemplateBuilder {
return this.fromImage(`python:${version}`)
}
@@ -161,13 +177,6 @@ export class TemplateBase
return this
}
- /**
- * Parse a Dockerfile and convert it to Template SDK format
- *
- * @param dockerfileContentOrPath Either the Dockerfile content as a string,
- * or a path to a Dockerfile file
- * @returns TemplateBuilder instance for method chaining
- */
fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder {
const { baseImage } = parseDockerfile(dockerfileContentOrPath, this)
this.baseImage = baseImage
@@ -503,6 +512,12 @@ export class TemplateBase
return this
}
+ /**
+ * Collect the current stack trace for debugging purposes.
+ *
+ * @param stackTracesDepth Depth to traverse in the call stack
+ * @returns this for method chaining
+ */
private collectStackTrace(stackTracesDepth: number = STACK_TRACE_DEPTH) {
if (!this.stackTracesEnabled) {
return this
@@ -512,16 +527,32 @@ export class TemplateBase
return this
}
+ /**
+ * Temporarily disable stack trace collection.
+ *
+ * @returns this for method chaining
+ */
private disableStackTrace() {
this.stackTracesEnabled = false
return this
}
+ /**
+ * Re-enable stack trace collection.
+ *
+ * @returns this for method chaining
+ */
private enableStackTrace() {
this.stackTracesEnabled = true
return this
}
+ /**
+ * Execute a function in a clean stack trace context.
+ *
+ * @param fn Function to execute
+ * @returns The result of the function
+ */
private runInNewStackTraceContext<T>(fn: () => T): T {
this.disableStackTrace()
const result = fn()
@@ -530,6 +561,12 @@ export class TemplateBase
return result
}
+ /**
+ * Convert the template to JSON representation.
+ *
+ * @param computeHashes Whether to compute file hashes for COPY instructions
+ * @returns JSON string representation of the template
+ */
private async toJSON(computeHashes: boolean): Promise<string> {
let instructions = this.instructions
if (computeHashes) {
@@ -539,6 +576,16 @@ export class TemplateBase
return JSON.stringify(this.serialize(instructions), undefined, 2)
}
+ /**
+ * Convert the template to Dockerfile format.
+ *
+ * Note: Only templates based on Docker images can be converted to Dockerfile.
+ * Templates based on other E2B templates cannot be converted because they
+ * may use features not available in standard Dockerfiles.
+ *
+ * @returns Dockerfile string representation
+ * @throws Error if template is based on another E2B template or has no base image
+ */
private toDockerfile(): string {
if (this.baseTemplate !== undefined) {
throw new Error(
@@ -561,6 +608,12 @@ export class TemplateBase
return dockerfile
}
+ /**
+ * Internal implementation of the template build process.
+ *
+ * @param options Build configuration options
+ * @throws BuildError if the build fails
+ */
private async build(options: BuildOptions): Promise<void> {
const config = new ConnectionConfig({
domain: options.domain,
@@ -683,7 +736,11 @@ export class TemplateBase
})
}
- // We might no longer need this as we move the logic server-side
+ /**
+ * Add file hashes to COPY instructions for cache invalidation.
+ *
+ * @returns Copy of instructions array with filesHash added to COPY instructions
+ */
private async instructionsWithHashes(): Promise<Instruction[]> {
return Promise.all(
this.instructions.map(async (instruction, index) => {
@@ -722,6 +779,12 @@ export class TemplateBase
)
}
+ /**
+ * Serialize the template to the API request format.
+ *
+ * @param steps Array of build instructions with file hashes
+ * @returns Template data formatted for the API
+ */
private serialize(steps: Instruction[]): TriggerBuildTemplate {
const templateData: TriggerBuildTemplate = {
startCmd: this.startCmd,
@@ -746,7 +809,24 @@ export class TemplateBase
}
}
-// Factory function to create Template instances without 'new'
+/**
+ * Create a new E2B template builder instance.
+ *
+ * @param options Optional configuration for the template builder
+ * @returns A new template builder instance
+ *
+ * @example
+ * ```ts
+ * import { Template } from 'e2b'
+ *
+ * const template = Template()
+ * .fromPythonImage('3')
+ * .copy('requirements.txt', '/app/')
+ * .pipInstall()
+ *
+ * await Template.build(template, { alias: 'my-python-app' })
+ * ```
+ */
export function Template(options?: TemplateOptions): TemplateFromImage {
return new TemplateBase(options)
}
@@ -754,5 +834,3 @@ export function Template(options?: TemplateOptions): TemplateFromImage {
Template.build = TemplateBase.build
Template.toJSON = TemplateBase.toJSON
Template.toDockerfile = TemplateBase.toDockerfile
-
-export type TemplateClass = TemplateBuilder | TemplateFinal
diff --git a/packages/js-sdk/src/template/logger.ts b/packages/js-sdk/src/template/logger.ts
index f384adc3b..13fdcaa39 100644
--- a/packages/js-sdk/src/template/logger.ts
+++ b/packages/js-sdk/src/template/logger.ts
@@ -1,8 +1,14 @@
import chalk from 'chalk'
import { stripAnsi } from '../utils'
+/**
+ * Log entry severity levels.
+ */
export type LogEntryLevel = 'debug' | 'info' | 'warn' | 'error'
+/**
+ * Represents a single log entry from the template build process.
+ */
export class LogEntry {
constructor(
public readonly timestamp: Date,
@@ -17,22 +23,40 @@ export class LogEntry {
}
}
+/**
+ * Special log entry indicating the start of a build process.
+ */
export class LogEntryStart extends LogEntry {
constructor(timestamp: Date, message: string) {
super(timestamp, 'debug', message)
}
}
+/**
+ * Special log entry indicating the end of a build process.
+ */
export class LogEntryEnd extends LogEntry {
constructor(timestamp: Date, message: string) {
super(timestamp, 'debug', message)
}
}
+/**
+ * Interval in milliseconds for updating the build timer display.
+ * @internal
+ */
const TIMER_UPDATE_INTERVAL_MS = 150
+/**
+ * Default minimum log level to display.
+ * @internal
+ */
const DEFAULT_LEVEL: LogEntryLevel = 'info'
+/**
+ * Colored labels for each log level.
+ * @internal
+ */
const levels: Record<LogEntryLevel, string> = {
error: chalk.red('ERROR'),
warn: chalk.hex('#FF4400')('WARN '),
@@ -40,7 +64,10 @@ const levels: Record<LogEntryLevel, string> = {
debug: chalk.gray('DEBUG'),
}
-// Level ordering for comparison (assuming lower = less severe)
+/**
+ * Numeric ordering of log levels for comparison (lower = less severe).
+ * @internal
+ */
const level_order: Record<LogEntryLevel, number> = {
debug: 0,
info: 1,
@@ -48,15 +75,15 @@ const level_order: Record<LogEntryLevel, number> = {
error: 3,
}
-interface BuildLoggerState {
+interface DefaultBuildLoggerState {
startTime: number
animationFrame: number
timerInterval: NodeJS.Timeout | undefined
}
-class BuildLogger {
+class DefaultBuildLogger {
private minLevel: LogEntryLevel
- private state: BuildLoggerState
+ private state: DefaultBuildLoggerState
constructor(minLevel?: LogEntryLevel) {
this.minLevel = minLevel ?? DEFAULT_LEVEL
@@ -86,7 +113,9 @@ class BuildLogger {
this.updateTimer()
}
- private getInitialState(timerInterval?: NodeJS.Timeout): BuildLoggerState {
+ private getInitialState(
+ timerInterval?: NodeJS.Timeout
+ ): DefaultBuildLoggerState {
return {
startTime: Date.now(),
animationFrame: 0,
@@ -155,10 +184,29 @@ class BuildLogger {
}
}
+/**
+ * Create a default build logger with animated timer display.
+ *
+ * @param options Logger configuration options
+ * @param options.minLevel Minimum log level to display (default: 'info')
+ * @returns Logger function that accepts LogEntry instances
+ *
+ * @example
+ * ```ts
+ * import { Template, defaultBuildLogger } from 'e2b'
+ *
+ * const template = Template().fromPythonImage()
+ *
+ * await Template.build(template, {
+ * alias: 'my-template',
+ * onBuildLogs: defaultBuildLogger({ minLevel: 'debug' })
+ * })
+ * ```
+ */
export function defaultBuildLogger(options?: {
minLevel?: LogEntryLevel
}): (logEntry: LogEntry) => void {
- const buildLogger = new BuildLogger(options?.minLevel)
+ const buildLogger = new DefaultBuildLogger(options?.minLevel)
return buildLogger.logger.bind(buildLogger)
}
diff --git a/packages/js-sdk/src/template/readycmd.ts b/packages/js-sdk/src/template/readycmd.ts
index 5e7906c14..c08ea4788 100644
--- a/packages/js-sdk/src/template/readycmd.ts
+++ b/packages/js-sdk/src/template/readycmd.ts
@@ -1,3 +1,6 @@
+/**
+ * Class for ready check commands.
+ */
export class ReadyCmd {
private cmd: string
@@ -10,26 +13,107 @@ export class ReadyCmd {
}
}
+/**
+ * Wait for a port to be listening.
+ * Uses `ss` command to check if a port is open and listening.
+ *
+ * @param port Port number to wait for
+ * @returns ReadyCmd that checks for the port
+ *
+ * @example
+ * ```ts
+ * import { Template, waitForPort } from 'e2b'
+ *
+ * const template = Template()
+ * .fromPythonImage()
+ * .setStartCmd('python -m http.server 8000', waitForPort(8000))
+ * ```
+ */
export function waitForPort(port: number): ReadyCmd {
const cmd = `ss -tuln | grep :${port}`
return new ReadyCmd(cmd)
}
+/**
+ * Wait for a URL to return a specific HTTP status code.
+ * Uses `curl` to make HTTP requests and check the response status.
+ *
+ * @param url URL to check (e.g., 'http://localhost:3000/health')
+ * @param statusCode Expected HTTP status code (default: 200)
+ * @returns ReadyCmd that checks the URL
+ *
+ * @example
+ * ```ts
+ * import { Template, waitForURL } from 'e2b'
+ *
+ * const template = Template()
+ * .fromNodeImage()
+ * .setStartCmd('npm start', waitForURL('http://localhost:3000/health'))
+ * ```
+ */
export function waitForURL(url: string, statusCode: number = 200): ReadyCmd {
const cmd = `curl -s -o /dev/null -w "%{http_code}" ${url} | grep -q "${statusCode}"`
return new ReadyCmd(cmd)
}
+/**
+ * Wait for a process with a specific name to be running.
+ * Uses `pgrep` to check if a process exists.
+ *
+ * @param processName Name of the process to wait for
+ * @returns ReadyCmd that checks for the process
+ *
+ * @example
+ * ```ts
+ * import { Template, waitForProcess } from 'e2b'
+ *
+ * const template = Template()
+ * .fromBaseImage()
+ * .setStartCmd('./my-daemon', waitForProcess('my-daemon'))
+ * ```
+ */
export function waitForProcess(processName: string): ReadyCmd {
const cmd = `pgrep ${processName} > /dev/null`
return new ReadyCmd(cmd)
}
+/**
+ * Wait for a file to exist.
+ * Uses shell test command to check file existence.
+ *
+ * @param filename Path to the file to wait for
+ * @returns ReadyCmd that checks for the file
+ *
+ * @example
+ * ```ts
+ * import { Template, waitForFile } from 'e2b'
+ *
+ * const template = Template()
+ * .fromBaseImage()
+ * .setStartCmd('./init.sh', waitForFile('/tmp/ready'))
+ * ```
+ */
export function waitForFile(filename: string): ReadyCmd {
const cmd = `[ -f ${filename} ]`
return new ReadyCmd(cmd)
}
+/**
+ * Wait for a specified timeout before considering the sandbox ready.
+ * Uses `sleep` command to wait for a fixed duration.
+ *
+ * @param timeout Time to wait in milliseconds (minimum: 1000ms / 1 second)
+ * @returns ReadyCmd that waits for the specified duration
+ *
+ * @example
+ * ```ts
+ * import { Template, waitForTimeout } from 'e2b'
+ *
+ * const template = Template()
+ * .fromNodeImage()
+ * .setStartCmd('npm start', waitForTimeout(5000)) // Wait 5 seconds
+ * ```
+ */
export function waitForTimeout(timeout: number): ReadyCmd {
// convert to seconds, but ensure minimum of 1 second
const seconds = Math.max(1, Math.floor(timeout / 1000))
diff --git a/packages/js-sdk/src/template/types.ts b/packages/js-sdk/src/template/types.ts
index a7f4472ad..269df88cc 100644
--- a/packages/js-sdk/src/template/types.ts
+++ b/packages/js-sdk/src/template/types.ts
@@ -1,6 +1,68 @@
import { ReadyCmd } from './readycmd'
import type { PathLike } from 'node:fs'
+import type { LogEntry } from './logger'
+
+/**
+ * Options for creating a new template.
+ */
+export type TemplateOptions = {
+ /**
+ * Path to the directory containing files to be copied into the template.
+ * @default Current directory from template location
+ */
+ fileContextPath?: PathLike
+ /**
+ * Array of glob patterns to ignore when copying files.
+ */
+ fileIgnorePatterns?: string[]
+}
+
+/**
+ * Basic options for building a template.
+ */
+export type BasicBuildOptions = {
+ /**
+ * Alias name for the template.
+ */
+ alias: string
+ /**
+ * Number of CPUs allocated to the sandbox.
+ * @default 2
+ */
+ cpuCount?: number
+ /**
+ * Amount of memory in MB allocated to the sandbox.
+ * @default 1024
+ */
+ memoryMB?: number
+ /**
+ * If true, skips cache and forces a complete rebuild.
+ * @default false
+ */
+ skipCache?: boolean
+ /**
+ * Callback function to receive build logs during the build process.
+ */
+ onBuildLogs?: (logEntry: LogEntry) => void
+}
+/**
+ * Options for building a template with authentication.
+ */
+export type BuildOptions = BasicBuildOptions & {
+ /**
+ * E2B API key for authentication.
+ */
+ apiKey?: string
+ /**
+ * Domain of the E2B API.
+ */
+ domain?: string
+}
+
+/**
+ * Types of instructions that can be used in a template.
+ */
export enum InstructionType {
COPY = 'COPY',
ENV = 'ENV',
@@ -9,6 +71,9 @@ export enum InstructionType {
USER = 'USER',
}
+/**
+ * Represents a single instruction in the template build process.
+ */
export type Instruction = {
type: InstructionType
args: string[]
@@ -18,6 +83,9 @@ export type Instruction = {
resolveSymlinks?: boolean
}
+/**
+ * Configuration for a single file/directory copy operation.
+ */
export type CopyItem = {
src: PathLike | PathLike[]
dest: PathLike
@@ -27,27 +95,126 @@ export type CopyItem = {
resolveSymlinks?: boolean
}
-// Interface for the initial state
+/**
+ * Initial state of a template builder.
+ * Use one of these methods to specify the base image or template to start from.
+ */
export interface TemplateFromImage {
+ /**
+ * Start from a Debian-based Docker image.
+ * @param variant Debian variant (default: 'stable')
+ *
+ * @example
+ * ```ts
+ * Template().fromDebianImage('bookworm')
+ * ```
+ */
fromDebianImage(variant?: string): TemplateBuilder
+ /**
+ * Start from an Ubuntu-based Docker image.
+ * @param variant Ubuntu variant (default: 'lts')
+ *
+ * @example
+ * ```ts
+ * Template().fromUbuntuImage('24.04')
+ * ```
+ */
fromUbuntuImage(variant?: string): TemplateBuilder
+ /**
+ * Start from a Python-based Docker image.
+ * @param version Python version (default: '3')
+ *
+ * @example
+ * ```ts
+ * Template().fromPythonImage('3')
+ * ```
+ */
fromPythonImage(version?: string): TemplateBuilder
+ /**
+ * Start from a Node.js-based Docker image.
+ * @param variant Node.js variant (default: 'lts')
+ *
+ * @example
+ * ```ts
+ * Template().fromNodeImage('24')
+ * ```
+ */
fromNodeImage(variant?: string): TemplateBuilder
+ /**
+ * Start from E2B's default base image (e2bdev/base:latest).
+ *
+ * @example
+ * ```ts
+ * Template().fromBaseImage()
+ * ```
+ */
fromBaseImage(): TemplateBuilder
+ /**
+ * Start from a custom Docker image.
+ * @param baseImage Docker image name
+ * @param credentials Optional credentials for private registries
+ *
+ * @example
+ * ```ts
+ * Template().fromImage('python:3')
+ *
+ * // With credentials (optional)
+ * Template().fromImage('myregistry.com/myimage:latest', {
+ * username: 'user',
+ * password: 'pass'
+ * })
+ * ```
+ */
fromImage(
baseImage: string,
credentials?: { username: string; password: string }
): TemplateBuilder
+ /**
+ * Start from an existing E2B template.
+ * @param template E2B template ID or alias
+ *
+ * @example
+ * ```ts
+ * Template().fromTemplate('my-base-template')
+ * ```
+ */
fromTemplate(template: string): TemplateBuilder
+ /**
+ * Parse a Dockerfile and convert it to Template SDK format.
+ * @param dockerfileContentOrPath Dockerfile content or path
+ *
+ * @example
+ * ```ts
+ * Template().fromDockerfile('Dockerfile')
+ * Template().fromDockerfile('FROM python:3\nRUN pip install numpy')
+ * ```
+ */
fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder
+ /**
+ * Start from a Docker image in AWS ECR.
+ * @param image Full ECR image path
+ * @param credentials AWS credentials
+ *
+ * @example
+ * ```ts
+ * Template().fromAWSRegistry(
+ * '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest',
+ * {
+ * accessKeyId: 'AKIA...',
+ * secretAccessKey: '...',
+ * region: 'us-west-2'
+ * }
+ * )
+ * ```
+ */
fromAWSRegistry(
image: string,
credentials: {
@@ -57,6 +224,19 @@ export interface TemplateFromImage {
}
): TemplateBuilder
+ /**
+ * Start from a Docker image in Google Container Registry.
+ * @param image Full GCR/GAR image path
+ * @param credentials GCP service account credentials
+ *
+ * @example
+ * ```ts
+ * Template().fromGCPRegistry(
+ * 'gcr.io/myproject/myimage:latest',
+ * { serviceAccountJSON: 'path/to/service-account.json' }
+ * )
+ * ```
+ */
fromGCPRegistry(
image: string,
credentials: {
@@ -64,11 +244,34 @@ export interface TemplateFromImage {
}
): TemplateBuilder
+ /**
+ * Skip cache for all subsequent build instructions from this point.
+ *
+ * @example
+ * ```ts
+ * Template().skipCache().fromPythonImage('3')
+ * ```
+ */
skipCache(): this
}
-// Interface for the main builder state
+/**
+ * Main builder state for constructing templates.
+ * Provides methods for customizing the template environment.
+ */
export interface TemplateBuilder {
+ /**
+ * Copy files or directories into the template.
+ * @param src Source path(s)
+ * @param dest Destination path
+ * @param options Copy options
+ *
+ * @example
+ * ```ts
+ * template.copy('requirements.txt', '/home/user/')
+ * template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 })
+ * ```
+ */
copy(
src: PathLike | PathLike[],
dest: PathLike,
@@ -80,86 +283,321 @@ export interface TemplateBuilder {
}
): TemplateBuilder
+ /**
+ * Copy multiple items with individual options.
+ * @param items Array of copy items
+ *
+ * @example
+ * ```ts
+ * template.copyItems([
+ * { src: 'app.ts', dest: '/app/' },
+ * { src: 'config.ts', dest: '/app/', mode: 0o644 }
+ * ])
+ * ```
+ */
copyItems(items: CopyItem[]): TemplateBuilder
+ /**
+ * Remove files or directories.
+ * @param path Path(s) to remove
+ * @param options Remove options
+ *
+ * @example
+ * ```ts
+ * template.remove('/tmp/cache', { recursive: true, force: true })
+ * ```
+ */
remove(
path: PathLike | PathLike[],
options?: { force?: boolean; recursive?: boolean }
): TemplateBuilder
+ /**
+ * Rename or move a file or directory.
+ * @param src Source path
+ * @param dest Destination path
+ * @param options Rename options
+ *
+ * @example
+ * ```ts
+ * template.rename('/tmp/old.txt', '/tmp/new.txt')
+ * ```
+ */
rename(
src: PathLike,
dest: PathLike,
options?: { force?: boolean }
): TemplateBuilder
+ /**
+ * Create directories.
+ * @param path Directory path(s)
+ * @param options Directory options
+ *
+ * @example
+ * ```ts
+ * template.makeDir('/app/data', { mode: 0o755 })
+ * template.makeDir(['/app/logs', '/app/cache'])
+ * ```
+ */
makeDir(
path: PathLike | PathLike[],
options?: { mode?: number }
): TemplateBuilder
+ /**
+ * Create a symbolic link.
+ * @param src Source path (target)
+ * @param dest Destination path (symlink location)
+ *
+ * @example
+ * ```ts
+ * template.makeSymlink('/usr/bin/python3', '/usr/bin/python')
+ * ```
+ */
makeSymlink(src: PathLike, dest: PathLike): TemplateBuilder
+ /**
+ * Run a shell command.
+ * @param command Command string
+ * @param options Command options
+ *
+ * @example
+ * ```ts
+ * template.runCmd('apt-get update')
+ * template.runCmd(['pip install numpy', 'pip install pandas'])
+ * template.runCmd('apt-get install vim', { user: 'root' })
+ * ```
+ */
runCmd(command: string, options?: { user?: string }): TemplateBuilder
+ /**
+ * Run multiple shell commands.
+ * @param commands Array of command strings
+ * @param options Command options
+ */
runCmd(commands: string[], options?: { user?: string }): TemplateBuilder
+ /**
+ * Run command(s).
+ * @param commandOrCommands Command or commands
+ * @param options Command options
+ */
runCmd(
commandOrCommands: string | string[],
options?: { user?: string }
): TemplateBuilder
+ /**
+ * Set the working directory.
+ * @param workdir Working directory path
+ *
+ * @example
+ * ```ts
+ * template.setWorkdir('/app')
+ * ```
+ */
setWorkdir(workdir: PathLike): TemplateBuilder
+ /**
+ * Set the user for subsequent commands.
+ * @param user Username
+ *
+ * @example
+ * ```ts
+ * template.setUser('root')
+ * ```
+ */
setUser(user: string): TemplateBuilder
+ /**
+ * Install Python packages using pip.
+ * @param packages Package name(s) or undefined for current directory
+ *
+ * @example
+ * ```ts
+ * template.pipInstall('numpy')
+ * template.pipInstall(['pandas', 'scikit-learn'])
+ * template.pipInstall() // Installs from current directory
+ * ```
+ */
pipInstall(packages?: string | string[]): TemplateBuilder
+ /**
+ * Install Node.js packages using npm.
+ * @param packages Package name(s) or undefined for package.json
+ * @param options Install options
+ *
+ * @example
+ * ```ts
+ * template.npmInstall('express')
+ * template.npmInstall(['lodash', 'axios'])
+ * template.npmInstall('typescript', { g: true })
+ * template.npmInstall() // Installs from package.json
+ * ```
+ */
npmInstall(
packages?: string | string[],
options?: { g?: boolean }
): TemplateBuilder
+ /**
+ * Install Debian/Ubuntu packages using apt-get.
+ * @param packages Package name(s)
+ *
+ * @example
+ * ```ts
+ * template.aptInstall('vim')
+ * template.aptInstall(['git', 'curl', 'wget'])
+ * ```
+ */
aptInstall(packages: string | string[]): TemplateBuilder
+ /**
+ * Clone a Git repository.
+ * @param url Repository URL
+ * @param path Optional destination path
+ * @param options Clone options
+ *
+ * @example
+ * ```ts
+ * template.gitClone('https://github.com/user/repo.git', '/app/repo')
+ * template.gitClone('https://github.com/user/repo.git', undefined, {
+ * branch: 'main',
+ * depth: 1
+ * })
+ * ```
+ */
gitClone(
url: string,
path?: PathLike,
options?: { branch?: string; depth?: number }
): TemplateBuilder
+ /**
+ * Set environment variables.
+ * @param envs Environment variables
+ *
+ * @example
+ * ```ts
+ * template.setEnvs({ NODE_ENV: 'production', PORT: '8080' })
+ * ```
+ */
setEnvs(envs: Record<string, string>): TemplateBuilder
+ /**
+ * Skip cache for all subsequent build instructions from this point.
+ *
+ * @example
+ * ```ts
+ * template.skipCache().runCmd('apt-get update')
+ * ```
+ */
skipCache(): this
+ /**
+ * Set the start command and ready check.
+ * @param startCommand Command to run on startup
+ * @param readyCommand Command to check readiness
+ *
+ * @example
+ * ```ts
+ * // Using a string command
+ * template.setStartCmd(
+ * 'node app.js',
+ * 'curl http://localhost:8000/health'
+ * )
+ *
+ * // Using ReadyCmd helpers
+ * import { waitForPort, waitForURL } from 'e2b'
+ *
+ * template.setStartCmd(
+ * 'python -m http.server 8000',
+ * waitForPort(8000)
+ * )
+ *
+ * template.setStartCmd(
+ * 'npm start',
+ * waitForURL('http://localhost:3000/health', 200)
+ * )
+ * ```
+ */
setStartCmd(
startCommand: string,
readyCommand: string | ReadyCmd
): TemplateFinal
+ /**
+ * Set or update the ready check command.
+ * @param readyCommand Command to check readiness
+ *
+ * @example
+ * ```ts
+ * // Using a string command
+ * template.setReadyCmd('curl http://localhost:8000/health')
+ *
+ * // Using ReadyCmd helpers
+ * import { waitForPort, waitForFile, waitForProcess } from 'e2b'
+ *
+ * template.setReadyCmd(waitForPort(3000))
+ *
+ * template.setReadyCmd(waitForFile('/tmp/ready'))
+ *
+ * template.setReadyCmd(waitForProcess('nginx'))
+ * ```
+ */
setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal
}
-// Interface for the final state
+/**
+ * Final state of a template after start/ready commands are set.
+ * The template can only be built in this state.
+ */
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface TemplateFinal {}
+/**
+ * Configuration for a generic Docker registry with basic authentication.
+ */
export type GenericDockerRegistry = {
+ /** Registry type identifier */
type: 'registry'
+ /** Registry username */
username: string
+ /** Registry password */
password: string
}
+/**
+ * Configuration for AWS Elastic Container Registry (ECR).
+ */
export type AWSRegistry = {
+ /** Registry type identifier */
type: 'aws'
+ /** AWS access key ID */
awsAccessKeyId: string
+ /** AWS secret access key */
awsSecretAccessKey: string
+ /** AWS region */
awsRegion: string
}
+/**
+ * Configuration for Google Container Registry (GCR) or Artifact Registry.
+ */
export type GCPRegistry = {
+ /** Registry type identifier */
type: 'gcp'
+ /** Service account JSON as string */
serviceAccountJson: string
}
+/**
+ * Union type for all supported container registry configurations.
+ */
export type RegistryConfig = GenericDockerRegistry | AWSRegistry | GCPRegistry
+
+/**
+ * Type representing a template in any state (builder or final).
+ */
+export type TemplateClass = TemplateBuilder | TemplateFinal
diff --git a/packages/js-sdk/src/template/utils.ts b/packages/js-sdk/src/template/utils.ts
index 7c7d7a316..4ee8b27e3 100644
--- a/packages/js-sdk/src/template/utils.ts
+++ b/packages/js-sdk/src/template/utils.ts
@@ -4,6 +4,12 @@ import path from 'node:path'
import { dynamicGlob, dynamicTar } from '../utils'
import { BASE_STEP_NAME, FINALIZE_STEP_NAME } from './consts'
+/**
+ * Read and parse a .dockerignore file.
+ *
+ * @param contextPath Directory path containing the .dockerignore file
+ * @returns Array of ignore patterns (empty lines and comments are filtered out)
+ */
export function readDockerignore(contextPath: string): string[] {
const dockerignorePath = path.join(contextPath, '.dockerignore')
if (!fs.existsSync(dockerignorePath)) {
@@ -17,6 +23,19 @@ export function readDockerignore(contextPath: string): string[] {
.filter((line) => line && !line.startsWith('#'))
}
+/**
+ * Calculate a hash of files being copied to detect changes for cache invalidation.
+ * The hash includes file content, metadata (mode, uid, gid, size, mtime), and relative paths.
+ *
+ * @param src Source path pattern for files to copy
+ * @param dest Destination path where files will be copied
+ * @param contextPath Base directory for resolving relative paths
+ * @param ignorePatterns Glob patterns to ignore
+ * @param resolveSymlinks Whether to resolve symbolic links when hashing
+ * @param stackTrace Optional stack trace for error reporting
+ * @returns Hex string hash of all files
+ * @throws Error if no files match the source pattern
+ */
export async function calculateFilesHash(
src: string,
dest: string,
@@ -92,10 +111,11 @@ export async function calculateFilesHash(
}
/**
- * Get the caller frame
- * @param depth - The depth of the stack trace
- * Levels explained: caller (eg. from class TemplateBase.fromImage) > original caller (eg. template file)
- * @returns The caller frame
+ * Get the caller's stack trace frame at a specific depth.
+ *
+ * @param depth The depth of the stack trace to retrieve
+ * - Levels: caller (e.g., TemplateBase.fromImage) > original caller (e.g., user's template file)
+ * @returns The caller frame as a string, or undefined if not available
*/
export function getCallerFrame(depth: number): string | undefined {
const stackTrace = new Error().stack
@@ -112,9 +132,14 @@ export function getCallerFrame(depth: number): string | undefined {
}
/**
- * Matches paths like "at <anonymous> (/path/to/file.js:1:1)" or "at /path/to/file.js:1:1"
- * @param line - The line to match
- * @returns The directory of the file
+ * Extract the directory path from a stack trace line.
+ *
+ * Matches patterns like:
+ * - "at <anonymous> (/path/to/file.js:1:1)"
+ * - "at /path/to/file.js:1:1"
+ *
+ * @param line A line from a stack trace
+ * @returns The directory of the file, or undefined if not found
*/
export function matchFileDir(line: string): string | undefined {
const match = line.match(/\/[^:]+/)
@@ -125,8 +150,10 @@ export function matchFileDir(line: string): string | undefined {
}
/**
- * Get the caller directory
- * @returns The caller directory
+ * Get the directory of the caller at a specific stack depth.
+ *
+ * @param depth The depth of the stack trace
+ * @returns The caller's directory path, or undefined if not available
*/
export function getCallerDirectory(depth: number): string | undefined {
const caller = getCallerFrame(depth + 1) // +1 depth to skip this function (getCallerDirectory)
@@ -143,10 +170,30 @@ export function getCallerDirectory(depth: number): string | undefined {
return matchFileDir(firstLine)
}
+/**
+ * Convert a numeric file mode to a zero-padded octal string.
+ *
+ * @param mode File mode as a number (e.g., 493 for 0o755)
+ * @returns Zero-padded 4-digit octal string (e.g., "0755")
+ *
+ * @example
+ * ```ts
+ * padOctal(0o755) // Returns "0755"
+ * padOctal(0o644) // Returns "0644"
+ * ```
+ */
export function padOctal(mode: number): string {
return mode.toString(8).padStart(4, '0')
}
+/**
+ * Create a compressed tar stream of files matching a pattern.
+ *
+ * @param fileName Glob pattern for files to include
+ * @param fileContextPath Base directory for resolving file paths
+ * @param resolveSymlinks Whether to follow symbolic links
+ * @returns A readable stream of the gzipped tar archive
+ */
export async function tarFileStream(
fileName: string,
fileContextPath: string,
@@ -166,12 +213,20 @@ export async function tarFileStream(
)
}
+/**
+ * Create a tar stream and calculate its compressed size for upload.
+ *
+ * @param fileName Glob pattern for files to include
+ * @param fileContextPath Base directory for resolving file paths
+ * @param resolveSymlinks Whether to follow symbolic links
+ * @returns Object containing the content length and upload stream
+ */
export async function tarFileStreamUpload(
fileName: string,
fileContextPath: string,
resolveSymlinks: boolean
) {
- // First pass: calculate the compressed size without buffering
+ // First pass: calculate the compressed size
const sizeCalculationStream = await tarFileStream(
fileName,
fileContextPath,
@@ -192,6 +247,18 @@ export async function tarFileStreamUpload(
}
}
+/**
+ * Get the array index for a build step based on its name.
+ *
+ * Special steps:
+ * - BASE_STEP_NAME: Returns 0 (first step)
+ * - FINALIZE_STEP_NAME: Returns the last index
+ * - Numeric strings: Converted to number
+ *
+ * @param step Build step name or number as string
+ * @param stackTracesLength Total number of stack traces (used for FINALIZE_STEP_NAME)
+ * @returns Index for the build step
+ */
export function getBuildStepIndex(
step: string,
stackTracesLength: number
@@ -207,6 +274,13 @@ export function getBuildStepIndex(
return Number(step)
}
+/**
+ * Read GCP service account JSON from a file or object.
+ *
+ * @param contextPath Base directory for resolving relative file paths
+ * @param pathOrContent Either a path to a JSON file or a service account object
+ * @returns Service account JSON as a string
+ */
export function readGCPServiceAccountJSON(
contextPath: string,
pathOrContent: string | object
diff --git a/packages/python-sdk/e2b/template/consts.py b/packages/python-sdk/e2b/template/consts.py
index 9d6121863..41d6cb879 100644
--- a/packages/python-sdk/e2b/template/consts.py
+++ b/packages/python-sdk/e2b/template/consts.py
@@ -1,11 +1,30 @@
+"""
+Special step name for the finalization phase of template building.
+This is the last step that runs after all user-defined instructions.
+"""
+
FINALIZE_STEP_NAME = "finalize"
+
+"""
+Special step name for the base image phase of template building.
+This is the first step that sets up the base image.
+"""
BASE_STEP_NAME = "base"
"""
-Depths explained:
+Stack trace depth for capturing caller information.
+
+Depth levels:
1. TemplateClass
-2. Caller method (eg. copy(), fromImage(), etc.)
+2. Caller method (e.g., copy(), from_image(), etc.)
+
+This depth is used to determine the original caller's location
+for stack traces.
"""
STACK_TRACE_DEPTH = 2
+"""
+Default setting for whether to resolve symbolic links when copying files.
+When False, symlinks are copied as symlinks rather than following them.
+"""
RESOLVE_SYMLINKS = False
diff --git a/packages/python-sdk/e2b/template/dockerfile_parser.py b/packages/python-sdk/e2b/template/dockerfile_parser.py
index c1d27be0d..c5932c501 100644
--- a/packages/python-sdk/e2b/template/dockerfile_parser.py
+++ b/packages/python-sdk/e2b/template/dockerfile_parser.py
@@ -54,18 +54,15 @@ class DockerfileParserInterface(Protocol):
def parse_dockerfile(
dockerfile_content_or_path: str, template_builder: DockerfileParserInterface
) -> str:
- """Parse a Dockerfile and convert it to Template SDK format.
+ """
+ Parse a Dockerfile and convert it to Template SDK format.
- Args:
- dockerfile_content_or_path: Either the Dockerfile content as a string,
- or a path to a Dockerfile file
- template_builder: Interface providing template builder methods
+ :param dockerfile_content_or_path: Either the Dockerfile content as a string, or a path to a Dockerfile file
+ :param template_builder: Interface providing template builder methods
- Returns:
- The base image from the Dockerfile
+ :return: The base image from the Dockerfile
- Raises:
- ValueError: If the Dockerfile is invalid or unsupported
+ :raises ValueError: If the Dockerfile is invalid or unsupported
"""
# Check if input is a file path that exists
if os.path.isfile(dockerfile_content_or_path):
diff --git a/packages/python-sdk/e2b/template/exceptions.py b/packages/python-sdk/e2b/template/exceptions.py
index 303e43512..ef6bcddb5 100644
--- a/packages/python-sdk/e2b/template/exceptions.py
+++ b/packages/python-sdk/e2b/template/exceptions.py
@@ -1,10 +1,10 @@
class BuildException(Exception):
"""
- Raised when a build fails.
+ Raised when the build fails.
"""
class FileUploadException(BuildException):
"""
- Raised when a file upload fails.
+ Raised when the file upload fails.
"""
diff --git a/packages/python-sdk/e2b/template/logger.py b/packages/python-sdk/e2b/template/logger.py
index d865015e8..414e04942 100644
--- a/packages/python-sdk/e2b/template/logger.py
+++ b/packages/python-sdk/e2b/template/logger.py
@@ -11,11 +11,16 @@ from rich.text import Text
from e2b.template.utils import strip_ansi_escape_codes
+"""Log entry severity levels."""
LogEntryLevel = Literal["debug", "info", "warn", "error"]
@dataclass
class LogEntry:
+ """
+ Represents a single log entry from the template build process.
+ """
+
timestamp: datetime
level: LogEntryLevel
message: str
@@ -29,19 +34,35 @@ class LogEntry:
@dataclass
class LogEntryStart(LogEntry):
+ """
+ Special log entry indicating the start of a build process.
+ """
+
level: LogEntryLevel = field(default="debug", init=False)
@dataclass
class LogEntryEnd(LogEntry):
+ """
+ Special log entry indicating the end of a build process.
+ """
+
level: LogEntryLevel = field(default="debug", init=False)
+"""
+Interval in milliseconds for updating the build timer display.
+"""
TIMER_UPDATE_INTERVAL_MS = 150
+"""
+Default minimum log level to display.
+"""
DEFAULT_LEVEL: LogEntryLevel = "info"
-# Level labels with Rich styles
+"""
+Colored labels for each log level.
+"""
levels: Dict[LogEntryLevel, tuple[str, Style]] = {
"error": ("ERROR", Style(color="red")),
"warn": ("WARN ", Style(color="#FF4400")),
@@ -49,7 +70,9 @@ levels: Dict[LogEntryLevel, tuple[str, Style]] = {
"debug": ("DEBUG", Style(color="bright_black")),
}
-# Level ordering for comparison
+"""
+Numeric ordering of log levels for comparison (lower = less severe).
+"""
level_order = {
"debug": 0,
"info": 1,
@@ -61,7 +84,13 @@ level_order = {
def set_interval(func, interval):
"""
Returns a stop function that can be called to cancel the interval.
+
Similar to JavaScript's setInterval.
+
+ :param func: Function to execute at each interval
+ :param interval: Interval duration in **seconds**
+
+ :return: Stop function that can be called to cancel the interval
"""
stopped = threading.Event()
@@ -76,17 +105,17 @@ def set_interval(func, interval):
return stopped.set # Return the stop function
-class InitialState(TypedDict):
+class DefaultBuildLoggerInitialState(TypedDict):
start_time: float
animation_frame: int
timer: Optional[Callable[[], None]]
-class BuildLogger:
+class DefaultBuildLogger:
__console = Console()
__min_level: LogEntryLevel
- __state: InitialState
+ __state: DefaultBuildLoggerInitialState
def __init__(self, min_level: Optional[LogEntryLevel] = None):
self.__min_level = min_level if min_level is not None else DEFAULT_LEVEL
@@ -178,6 +207,26 @@ class BuildLogger:
def default_build_logger(
min_level: Optional[LogEntryLevel] = None,
) -> Callable[[LogEntry], None]:
- build_logger = BuildLogger(min_level)
+ """
+ Create a default build logger with animated timer display.
+
+ :param min_level: Minimum log level to display (default: 'info')
+
+ :return: Logger function that accepts LogEntry instances
+
+ Example
+ ```python
+ from e2b import Template, default_build_logger
+
+ template = Template().from_python_image()
+
+ # Use with build - implementation would be in build_async module
+ # await Template.build(template,
+ # alias='my-template',
+ # on_build_logs=default_build_logger(min_level='debug')
+ # )
+ ```
+ """
+ build_logger = DefaultBuildLogger(min_level)
return build_logger.logger
diff --git a/packages/python-sdk/e2b/template/main.py b/packages/python-sdk/e2b/template/main.py
index 3c8d62ca6..215ab2ee8 100644
--- a/packages/python-sdk/e2b/template/main.py
+++ b/packages/python-sdk/e2b/template/main.py
@@ -26,6 +26,12 @@ from types import TracebackType
class TemplateBuilder:
+ """
+ Builder class for adding instructions to an E2B template.
+
+ All methods return self to allow method chaining.
+ """
+
def __init__(self, template: "TemplateBase"):
self._template = template
@@ -38,6 +44,24 @@ class TemplateBuilder:
mode: Optional[int] = None,
resolve_symlinks: Optional[bool] = None,
) -> "TemplateBuilder":
+ """
+ Copy files or directories from the local filesystem into the template.
+
+ :param src: Source file(s) or directory path(s) to copy
+ :param dest: Destination path in the template
+ :param force_upload: Force upload even if files are cached
+ :param user: User and optionally group (user:group) to own the files
+ :param mode: File permissions in octal format (e.g., 0o755)
+ :param resolve_symlinks: Whether to resolve symlinks
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.copy('requirements.txt', '/home/user/')
+ template.copy(['app.py', 'config.py'], '/app/', mode=0o755)
+ ```
+ """
srcs = [src] if isinstance(src, (str, Path)) else src
for src_item in srcs:
@@ -62,6 +86,21 @@ class TemplateBuilder:
return self
def copy_items(self, items: List[CopyItem]) -> "TemplateBuilder":
+ """
+ Copy multiple files or directories using a list of copy items.
+
+ :param items: List of CopyItem dictionaries with src, dest, and optional parameters
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.copy_items([
+ {'src': 'app.py', 'dest': '/app/'},
+ {'src': 'config.py', 'dest': '/app/', 'mode': 0o644}
+ ])
+ ```
+ """
self._template._run_in_new_stack_trace_context(
lambda: [
self.copy(
@@ -83,6 +122,20 @@ class TemplateBuilder:
force: bool = False,
recursive: bool = False,
) -> "TemplateBuilder":
+ """
+ Remove files or directories in the template.
+
+ :param path: File(s) or directory path(s) to remove
+ :param force: Force removal without prompting
+ :param recursive: Remove directories recursively
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.remove('/tmp/cache', recursive=True, force=True)
+ ```
+ """
paths = [path] if isinstance(path, (str, Path)) else path
args = ["rm"]
if recursive:
@@ -98,6 +151,20 @@ class TemplateBuilder:
def rename(
self, src: Union[str, Path], dest: Union[str, Path], force: bool = False
) -> "TemplateBuilder":
+ """
+ Rename or move a file or directory in the template.
+
+ :param src: Source path
+ :param dest: Destination path
+ :param force: Force rename without prompting
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.rename('/tmp/old.txt', '/tmp/new.txt')
+ ```
+ """
args = ["mv", str(src), str(dest)]
if force:
args.append("-f")
@@ -111,6 +178,20 @@ class TemplateBuilder:
path: Union[Union[str, Path], List[Union[str, Path]]],
mode: Optional[int] = None,
) -> "TemplateBuilder":
+ """
+ Create directory(ies) in the template.
+
+ :param path: Directory path(s) to create
+ :param mode: Directory permissions in octal format (e.g., 0o755)
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.make_dir('/app/data', mode=0o755)
+ template.make_dir(['/app/logs', '/app/cache'])
+ ```
+ """
path_list = [path] if isinstance(path, (str, Path)) else path
args = ["mkdir", "-p"]
if mode:
@@ -124,6 +205,19 @@ class TemplateBuilder:
def make_symlink(
self, src: Union[str, Path], dest: Union[str, Path]
) -> "TemplateBuilder":
+ """
+ Create a symbolic link in the template.
+
+ :param src: Source path (target of the symlink)
+ :param dest: Destination path (location of the symlink)
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.make_symlink('/usr/bin/python3', '/usr/bin/python')
+ ```
+ """
args = ["ln", "-s", str(src), str(dest)]
return self._template._run_in_new_stack_trace_context(
lambda: self.run_cmd(" ".join(args))
@@ -132,6 +226,21 @@ class TemplateBuilder:
def run_cmd(
self, command: Union[str, List[str]], user: Optional[str] = None
) -> "TemplateBuilder":
+ """
+ Run a shell command during template build.
+
+ :param command: Command string or list of commands to run (joined with &&)
+ :param user: User to run the command as
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.run_cmd('apt-get update')
+ template.run_cmd(['pip install numpy', 'pip install pandas'])
+ template.run_cmd('apt-get install vim', user='root')
+ ```
+ """
commands = [command] if isinstance(command, str) else command
args = [" && ".join(commands)]
@@ -149,6 +258,18 @@ class TemplateBuilder:
return self
def set_workdir(self, workdir: Union[str, Path]) -> "TemplateBuilder":
+ """
+ Set the working directory for subsequent commands in the template.
+
+ :param workdir: Path to set as the working directory
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.set_workdir('/app')
+ ```
+ """
instruction: Instruction = {
"type": InstructionType.WORKDIR,
"args": [str(workdir)],
@@ -160,6 +281,18 @@ class TemplateBuilder:
return self
def set_user(self, user: str) -> "TemplateBuilder":
+ """
+ Set the user for subsequent commands in the template.
+
+ :param user: Username to set
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.set_user('root')
+ ```
+ """
instruction: Instruction = {
"type": InstructionType.USER,
"args": [user],
@@ -173,6 +306,20 @@ class TemplateBuilder:
def pip_install(
self, packages: Optional[Union[str, List[str]]] = None
) -> "TemplateBuilder":
+ """
+ Install Python packages using pip.
+
+ :param packages: Package name(s) to install. If None, runs 'pip install .' in the current directory
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.pip_install('numpy')
+ template.pip_install(['pandas', 'scikit-learn'])
+ template.pip_install() # Installs from current directory
+ ```
+ """
if isinstance(packages, str):
packages = [packages]
@@ -191,6 +338,22 @@ class TemplateBuilder:
packages: Optional[Union[str, List[str]]] = None,
g: Optional[bool] = False,
) -> "TemplateBuilder":
+ """
+ Install Node.js packages using npm.
+
+ :param packages: Package name(s) to install. If None, installs from package.json
+ :param g: Install packages globally
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.npm_install('express')
+ template.npm_install(['lodash', 'axios'])
+ template.npm_install('typescript', g=True)
+ template.npm_install() # Installs from package.json
+ ```
+ """
if isinstance(packages, str):
packages = [packages]
@@ -205,6 +368,19 @@ class TemplateBuilder:
)
def apt_install(self, packages: Union[str, List[str]]) -> "TemplateBuilder":
+ """
+ Install system packages using apt-get.
+
+ :param packages: Package name(s) to install
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.apt_install('vim')
+ template.apt_install(['git', 'curl', 'wget'])
+ ```
+ """
if isinstance(packages, str):
packages = [packages]
@@ -225,6 +401,22 @@ class TemplateBuilder:
branch: Optional[str] = None,
depth: Optional[int] = None,
) -> "TemplateBuilder":
+ """
+ Clone a git repository into the template.
+
+ :param url: Git repository URL
+ :param path: Destination path for the clone
+ :param branch: Branch to clone
+ :param depth: Clone depth for shallow clones
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.git_clone('https://github.com/user/repo.git', '/app/repo')
+ template.git_clone('https://github.com/user/repo.git', branch='main', depth=1)
+ ```
+ """
args = ["git", "clone", url]
if branch:
args.append(f"--branch {branch}")
@@ -238,6 +430,18 @@ class TemplateBuilder:
)
def set_envs(self, envs: Dict[str, str]) -> "TemplateBuilder":
+ """
+ Set environment variables in the template.
+
+ :param envs: Dictionary of environment variable names and values
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.set_envs({'NODE_ENV': 'production', 'PORT': '8080'})
+ ```
+ """
if len(envs) == 0:
return self
@@ -252,12 +456,55 @@ class TemplateBuilder:
return self
def skip_cache(self) -> "TemplateBuilder":
+ """
+ Skip cache for all subsequent build instructions from this point.
+
+ Call this before any instruction to force it and all following layers
+ to be rebuilt, ignoring any cached layers.
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ template.skip_cache().run_cmd('apt-get update')
+ ```
+ """
self._template._force_next_layer = True
return self
def set_start_cmd(
self, start_cmd: str, ready_cmd: Union[str, ReadyCmd]
) -> "TemplateFinal":
+ """
+ Set the command to start when the sandbox launches and the ready check command.
+
+ :param start_cmd: Command to run when the sandbox starts
+ :param ready_cmd: Command or ReadyCmd to check if the sandbox is ready
+
+ :return: `TemplateFinal` class
+
+ Example
+ ```python
+ # Using a string command
+ template.set_start_cmd(
+ 'python app.py',
+ 'curl http://localhost:8000/health'
+ )
+
+ # Using ReadyCmd helpers
+ from e2b import wait_for_port, wait_for_url
+
+ template.set_start_cmd(
+ 'python -m http.server 8000',
+ wait_for_port(8000)
+ )
+
+ template.set_start_cmd(
+ 'npm start',
+ wait_for_url('http://localhost:3000/health', 200)
+ )
+ ```
+ """
self._template._start_cmd = start_cmd
if isinstance(ready_cmd, ReadyCmd):
@@ -268,6 +515,28 @@ class TemplateBuilder:
return TemplateFinal(self._template)
def set_ready_cmd(self, ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal":
+ """
+ Set the command to check if the sandbox is ready.
+
+ :param ready_cmd: Command or ReadyCmd to check if the sandbox is ready
+
+ :return: `TemplateFinal` class
+
+ Example
+ ```python
+ # Using a string command
+ template.set_ready_cmd('curl http://localhost:8000/health')
+
+ # Using ReadyCmd helpers
+ from e2b import wait_for_port, wait_for_file, wait_for_process
+
+ template.set_ready_cmd(wait_for_port(3000))
+
+ template.set_ready_cmd(wait_for_file('/tmp/ready'))
+
+ template.set_ready_cmd(wait_for_process('nginx'))
+ ```
+ """
if isinstance(ready_cmd, ReadyCmd):
ready_cmd = ready_cmd.get_cmd()
@@ -277,11 +546,19 @@ class TemplateBuilder:
class TemplateFinal:
+ """
+ Final template state after start/ready commands are set.
+ """
+
def __init__(self, template: "TemplateBase"):
self._template = template
class TemplateBase:
+ """
+ Base class for building E2B sandbox templates.
+ """
+
_limits = Limits(
max_keepalive_connections=40,
max_connections=40,
@@ -294,6 +571,12 @@ class TemplateBase:
file_context_path: Optional[Union[str, Path]] = None,
file_ignore_patterns: Optional[List[str]] = None,
):
+ """
+ Create a new template builder instance.
+
+ :param file_context_path: Base path for resolving relative file paths in copy operations
+ :param file_ignore_patterns: List of glob patterns to ignore when copying files
+ """
self._default_base_image: str = "e2bdev/base"
self._base_image: Optional[str] = self._default_base_image
self._base_template: Optional[str] = None
@@ -316,14 +599,29 @@ class TemplateBase:
self._stack_traces_enabled: bool = True
def skip_cache(self) -> "TemplateBase":
- """Skip cache for the next instruction (before from instruction)"""
+ """
+ Skip cache for all subsequent build instructions from this point.
+
+ :return: `TemplateBase` class
+
+ Example
+ ```python
+ template.skip_cache().from_python_image('3.11')
+ ```
+ """
self._force_next_layer = True
return self
def _collect_stack_trace(
self, stack_traces_depth: int = STACK_TRACE_DEPTH
) -> "TemplateBase":
- """Collect stack trace if enabled"""
+ """
+ Collect the current stack trace for debugging purposes.
+
+ :param stack_traces_depth: Depth to traverse in the call stack
+
+ :return: `TemplateBase` class
+ """
if not self._stack_traces_enabled:
return self
@@ -344,17 +642,31 @@ class TemplateBase:
return self
def _disable_stack_trace(self) -> "TemplateBase":
- """Disable stack trace collection"""
+ """
+ Temporarily disable stack trace collection.
+
+ :return: `TemplateBase` class
+ """
self._stack_traces_enabled = False
return self
def _enable_stack_trace(self) -> "TemplateBase":
- """Enable stack trace collection"""
+ """
+ Re-enable stack trace collection.
+
+ :return: `TemplateBase` class
+ """
self._stack_traces_enabled = True
return self
def _run_in_new_stack_trace_context(self, fn):
- """Run a function in a new stack trace context"""
+ """
+ Execute a function in a clean stack trace context.
+
+ :param fn: Function to execute
+
+ :return: The result of the function
+ """
self._disable_stack_trace()
result = fn()
self._enable_stack_trace()
@@ -362,27 +674,85 @@ class TemplateBase:
return result
# Built-in image mixins
- def from_debian_image(self, variant: str = "slim") -> TemplateBuilder:
+ def from_debian_image(self, variant: str = "stable") -> TemplateBuilder:
+ """
+ Start template from a Debian base image.
+
+ :param variant: Debian image variant
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ Template().from_debian_image('bookworm')
+ ```
+ """
return self._run_in_new_stack_trace_context(
lambda: self.from_image(f"debian:{variant}")
)
def from_ubuntu_image(self, variant: str = "lts") -> TemplateBuilder:
+ """
+ Start template from an Ubuntu base image.
+
+ :param variant: Ubuntu image variant (default: 'lts')
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ Template().from_ubuntu_image('24.04')
+ ```
+ """
return self._run_in_new_stack_trace_context(
lambda: self.from_image(f"ubuntu:{variant}")
)
- def from_python_image(self, version: str = "3.13") -> TemplateBuilder:
+ def from_python_image(self, version: str = "3") -> TemplateBuilder:
+ """
+ Start template from a Python base image.
+
+ :param version: Python version (default: '3')
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ Template().from_python_image('3')
+ ```
+ """
return self._run_in_new_stack_trace_context(
lambda: self.from_image(f"python:{version}")
)
def from_node_image(self, variant: str = "lts") -> TemplateBuilder:
+ """
+ Start template from a Node.js base image.
+
+ :param variant: Node.js image variant (default: 'lts')
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ Template().from_node_image('24')
+ ```
+ """
return self._run_in_new_stack_trace_context(
lambda: self.from_image(f"node:{variant}")
)
def from_base_image(self) -> TemplateBuilder:
+ """
+ Start template from the E2B base image (e2bdev/base:latest).
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ Template().from_base_image()
+ ```
+ """
return self._run_in_new_stack_trace_context(
lambda: self.from_image(self._default_base_image)
)
@@ -393,7 +763,23 @@ class TemplateBase:
username: Optional[str] = None,
password: Optional[str] = None,
) -> TemplateBuilder:
- """Private method to set base image without adding stack trace"""
+ """
+ Start template from a Docker image.
+
+ :param image: Docker image name (e.g., 'ubuntu:24.04')
+ :param username: Username for private registry authentication
+ :param password: Password for private registry authentication
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ Template().from_image('python:3')
+
+ # With credentials (optional)
+ Template().from_image('myregistry.com/myimage:latest', username='user', password='pass')
+ ```
+ """
self._base_image = image
self._base_template = None
@@ -413,6 +799,18 @@ class TemplateBase:
return TemplateBuilder(self)
def from_template(self, template: str) -> TemplateBuilder:
+ """
+ Start template from an existing E2B template.
+
+ :param template: E2B template ID or alias
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ Template().from_template('my-base-template')
+ ```
+ """
self._base_template = template
self._base_image = None
@@ -424,11 +822,18 @@ class TemplateBase:
return TemplateBuilder(self)
def from_dockerfile(self, dockerfile_content_or_path: str) -> TemplateBuilder:
- """Parse a Dockerfile and convert it to Template SDK format
+ """
+ Parse a Dockerfile and convert it to Template SDK format.
- Args:
- dockerfile_content_or_path: Either the Dockerfile content as a string,
- or a path to a Dockerfile file
+ :param dockerfile_content_or_path: Either the Dockerfile content as a string, or a path to a Dockerfile file
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ Template().from_dockerfile('Dockerfile')
+ Template().from_dockerfile('FROM python:3\\nRUN pip install numpy')
+ ```
"""
# Create a TemplateBuilder first to use its methods
builder = TemplateBuilder(self)
@@ -451,6 +856,26 @@ class TemplateBase:
secret_access_key: str,
region: str,
) -> TemplateBuilder:
+ """
+ Start template from an AWS ECR registry image.
+
+ :param image: Docker image name from AWS ECR
+ :param access_key_id: AWS access key ID
+ :param secret_access_key: AWS secret access key
+ :param region: AWS region
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ Template().from_aws_registry(
+ '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest',
+ access_key_id='AKIA...',
+ secret_access_key='...',
+ region='us-west-2'
+ )
+ ```
+ """
self._base_image = image
self._base_template = None
@@ -472,6 +897,22 @@ class TemplateBase:
def from_gcp_registry(
self, image: str, service_account_json: Union[str, dict]
) -> TemplateBuilder:
+ """
+ Start template from a GCP Artifact Registry or Container Registry image.
+
+ :param image: Docker image name from GCP registry
+ :param service_account_json: Service account JSON string, dict, or path to JSON file
+
+ :return: `TemplateBuilder` class
+
+ Example
+ ```python
+ Template().from_gcp_registry(
+ 'gcr.io/myproject/myimage:latest',
+ service_account_json='path/to/service-account.json'
+ )
+ ```
+ """
self._base_image = image
self._base_template = None
@@ -492,6 +933,19 @@ class TemplateBase:
@staticmethod
def to_json(template: "TemplateClass") -> str:
+ """
+ Convert a template to JSON representation.
+
+ :param template: The template to convert (TemplateBuilder or TemplateFinal instance)
+
+ :return: JSON string representation of the template
+
+ Example
+ ```python
+ template = Template().from_python_image('3').copy('app.py', '/app/')
+ json_str = TemplateBase.to_json(template)
+ ```
+ """
return json.dumps(
template._template._serialize(
template._template._instructions_with_hashes()
@@ -501,6 +955,23 @@ class TemplateBase:
@staticmethod
def to_dockerfile(template: "TemplateClass") -> str:
+ """
+ Convert a template to Dockerfile format.
+
+ Note: Templates based on other E2B templates cannot be converted to Dockerfile.
+
+ :param template: The template to convert (TemplateBuilder or TemplateFinal instance)
+
+ :return: Dockerfile string representation
+
+ :raises ValueError: If the template is based on another E2B template or has no base image
+
+ Example
+ ```python
+ template = Template().from_python_image('3').copy('app.py', '/app/')
+ dockerfile = TemplateBase.to_dockerfile(template)
+ ```
+ """
if template._template._base_template is not None:
raise ValueError(
"Cannot convert template built from another template to Dockerfile. "
@@ -525,6 +996,11 @@ class TemplateBase:
def _instructions_with_hashes(
self,
) -> List[Instruction]:
+ """
+ Add file hashes to COPY instructions for cache invalidation.
+
+ :return: Copy of instructions list with filesHash added to COPY instructions
+ """
steps: List[Instruction] = []
for index, instruction in enumerate(self._instructions):
@@ -547,6 +1023,7 @@ class TemplateBase:
if src is None or dest is None:
raise ValueError("Source path and destination path are required")
+ resolve_symlinks = instruction.get("resolveSymlinks")
step["filesHash"] = calculate_files_hash(
src,
dest,
@@ -555,7 +1032,9 @@ class TemplateBase:
*self._file_ignore_patterns,
*read_dockerignore(self._file_context_path),
],
- instruction.get("resolveSymlinks", RESOLVE_SYMLINKS),
+ resolve_symlinks
+ if resolve_symlinks is not None
+ else RESOLVE_SYMLINKS,
stack_trace,
)
@@ -564,6 +1043,13 @@ class TemplateBase:
return steps
def _serialize(self, steps: List[Instruction]) -> TemplateType:
+ """
+ Serialize the template to the API request format.
+
+ :param steps: List of build instructions with file hashes
+
+ :return: Template data formatted for the API
+ """
_steps: List[Instruction] = []
for _, instruction in enumerate(steps):
@@ -573,11 +1059,13 @@ class TemplateBase:
"force": instruction.get("force"),
}
- if instruction.get("filesHash") is not None:
- step["filesHash"] = instruction["filesHash"]
+ files_hash = instruction.get("filesHash")
+ if files_hash is not None:
+ step["filesHash"] = files_hash
- if instruction.get("forceUpload") is not None:
- step["forceUpload"] = instruction["forceUpload"]
+ force_upload = instruction.get("forceUpload")
+ if force_upload is not None:
+ step["forceUpload"] = force_upload
_steps.append(step)
diff --git a/packages/python-sdk/e2b/template/readycmd.py b/packages/python-sdk/e2b/template/readycmd.py
index 5cae19ba6..1ec65d822 100644
--- a/packages/python-sdk/e2b/template/readycmd.py
+++ b/packages/python-sdk/e2b/template/readycmd.py
@@ -1,4 +1,8 @@
class ReadyCmd:
+ """
+ Wrapper class for ready check commands.
+ """
+
def __init__(self, cmd: str):
self.__cmd = cmd
@@ -7,31 +11,127 @@ class ReadyCmd:
def wait_for_port(port: int):
- """Generate a command to wait for a port to be available."""
+ """
+ Wait for a port to be listening.
+
+ Uses `ss` command to check if a port is open and listening.
+
+ :param port: Port number to wait for
+
+ :return: ReadyCmd that checks for the port
+
+ Example
+ ```python
+ from e2b import Template, wait_for_port
+
+ template = (
+ Template()
+ .from_python_image()
+ .set_start_cmd('python -m http.server 8000', wait_for_port(8000))
+ )
+ ```
+ """
cmd = f"ss -tuln | grep :{port}"
return ReadyCmd(cmd)
def wait_for_url(url: str, status_code: int = 200):
- """Generate a command to wait for a URL to return a specific status code."""
+ """
+ Wait for a URL to return a specific HTTP status code.
+
+ Uses `curl` to make HTTP requests and check the response status.
+
+ :param url: URL to check (e.g., 'http://localhost:3000/health')
+ :param status_code: Expected HTTP status code (default: 200)
+
+ :return: ReadyCmd that checks the URL
+
+ Example
+ ```python
+ from e2b import Template, wait_for_url
+
+ template = (
+ Template()
+ .from_node_image()
+ .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health'))
+ )
+ ```
+ """
cmd = f'curl -s -o /dev/null -w "%{{http_code}}" {url} | grep -q "{status_code}"'
return ReadyCmd(cmd)
def wait_for_process(process_name: str):
- """Generate a command to wait for a process to be running."""
+ """
+ Wait for a process with a specific name to be running.
+
+ Uses `pgrep` to check if a process exists.
+
+ :param process_name: Name of the process to wait for
+
+ :return: ReadyCmd that checks for the process
+
+ Example
+ ```python
+ from e2b import Template, wait_for_process
+
+ template = (
+ Template()
+ .from_base_image()
+ .set_start_cmd('./my-daemon', wait_for_process('my-daemon'))
+ )
+ ```
+ """
cmd = f"pgrep {process_name} > /dev/null"
return ReadyCmd(cmd)
def wait_for_file(filename: str):
- """Generate a command to wait for a file to exist."""
+ """
+ Wait for a file to exist.
+
+ Uses shell test command to check file existence.
+
+ :param filename: Path to the file to wait for
+
+ :return: ReadyCmd that checks for the file
+
+ Example
+ ```python
+ from e2b import Template, wait_for_file
+
+ template = (
+ Template()
+ .from_base_image()
+ .set_start_cmd('./init.sh', wait_for_file('/tmp/ready'))
+ )
+ ```
+ """
cmd = f"[ -f {filename} ]"
return ReadyCmd(cmd)
def wait_for_timeout(timeout: int):
- """Generate a command to wait for a specified duration."""
+ """
+ Wait for a specified timeout before considering the sandbox ready.
+
+ Uses `sleep` command to wait for a fixed duration.
+
+ :param timeout: Time to wait in **milliseconds** (minimum: 1000ms / 1 second)
+
+ :return: ReadyCmd that waits for the specified duration
+
+ Example
+ ```python
+ from e2b import Template, wait_for_timeout
+
+ template = (
+ Template()
+ .from_node_image()
+ .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds
+ )
+ ```
+ """
# convert to seconds, but ensure minimum of 1 second
seconds = max(1, timeout // 1000)
cmd = f"sleep {seconds}"
diff --git a/packages/python-sdk/e2b/template/types.py b/packages/python-sdk/e2b/template/types.py
index 480b0a119..d6dfa8476 100644
--- a/packages/python-sdk/e2b/template/types.py
+++ b/packages/python-sdk/e2b/template/types.py
@@ -7,6 +7,10 @@ from typing_extensions import NotRequired
class InstructionType(str, Enum):
+ """
+ Types of instructions that can be used in a template.
+ """
+
COPY = "COPY"
ENV = "ENV"
RUN = "RUN"
@@ -15,6 +19,10 @@ class InstructionType(str, Enum):
class CopyItem(TypedDict):
+ """
+ Configuration for a single file/directory copy operation.
+ """
+
src: Union[Union[str, Path], List[Union[str, Path]]]
dest: Union[str, Path]
forceUpload: NotRequired[Optional[Literal[True]]]
@@ -24,6 +32,10 @@ class CopyItem(TypedDict):
class Instruction(TypedDict):
+ """
+ Represents a single instruction in the template build process.
+ """
+
type: InstructionType
args: List[str]
force: bool
@@ -33,12 +45,20 @@ class Instruction(TypedDict):
class GenericDockerRegistry(TypedDict):
+ """
+ Configuration for a generic Docker registry with basic authentication.
+ """
+
type: Literal["registry"]
username: str
password: str
class AWSRegistry(TypedDict):
+ """
+ Configuration for AWS Elastic Container Registry (ECR).
+ """
+
type: Literal["aws"]
awsAccessKeyId: str
awsSecretAccessKey: str
@@ -46,14 +66,25 @@ class AWSRegistry(TypedDict):
class GCPRegistry(TypedDict):
+ """
+ Configuration for Google Container Registry (GCR) or Artifact Registry.
+ """
+
type: Literal["gcp"]
serviceAccountJson: str
+"""
+Union type for all supported container registry configurations.
+"""
RegistryConfig = Union[GenericDockerRegistry, AWSRegistry, GCPRegistry]
class TemplateType(TypedDict):
+ """
+ Internal representation of a template for the E2B build API.
+ """
+
fromImage: NotRequired[str]
fromTemplate: NotRequired[str]
fromImageRegistry: NotRequired[RegistryConfig]
diff --git a/packages/python-sdk/e2b/template/utils.py b/packages/python-sdk/e2b/template/utils.py
index 7d330c3f7..07b672748 100644
--- a/packages/python-sdk/e2b/template/utils.py
+++ b/packages/python-sdk/e2b/template/utils.py
@@ -13,6 +13,13 @@ from e2b.template.consts import BASE_STEP_NAME, FINALIZE_STEP_NAME
def read_dockerignore(context_path: str) -> List[str]:
+ """
+ Read and parse a .dockerignore file.
+
+ :param context_path: Directory path containing the .dockerignore file
+
+ :return: Array of ignore patterns (empty lines and comments are filtered out)
+ """
dockerignore_path = os.path.join(context_path, ".dockerignore")
if not os.path.exists(dockerignore_path):
return []
@@ -35,6 +42,22 @@ def calculate_files_hash(
resolve_symlinks: bool,
stack_trace: Optional[TracebackType],
) -> str:
+ """
+ Calculate a hash of files being copied to detect changes for cache invalidation.
+
+ The hash includes file content, metadata (mode, uid, gid, size, mtime), and relative paths.
+
+ :param src: Source path pattern for files to copy
+ :param dest: Destination path where files will be copied
+ :param context_path: Base directory for resolving relative paths
+ :param ignore_patterns: Glob patterns to ignore
+ :param resolve_symlinks: Whether to resolve symbolic links when hashing
+ :param stack_trace: Optional stack trace for error reporting
+
+ :return: Hex string hash of all files
+
+ :raises ValueError: If no files match the source pattern
+ """
src_path = os.path.join(context_path, src)
hash_obj = hashlib.sha256()
content = f"COPY {src} {dest}"
@@ -91,7 +114,15 @@ def calculate_files_hash(
def strip_ansi_escape_codes(text: str) -> str:
- """Strip ANSI escape codes from a string. Source: https://github.com/chalk/ansi-regex/blob/main/index.js"""
+ """
+ Strip ANSI escape codes from a string.
+
+ Source: https://github.com/chalk/ansi-regex/blob/main/index.js
+
+ :param text: String with ANSI escape codes
+
+ :return: String without ANSI escape codes
+ """
# Valid string terminator sequences are BEL, ESC\, and 0x9c
st = r"(?:\u0007|\u001B\u005C|\u009C)"
pattern = [
@@ -103,7 +134,16 @@ def strip_ansi_escape_codes(text: str) -> str:
def get_caller_frame(depth: int) -> Optional[FrameType]:
- """Get the caller frame. Skip this function (first frame)."""
+ """
+ Get the caller's stack frame at a specific depth.
+
+ This is used to provide better error messages and debugging information
+ by tracking where template methods were called from in user code.
+
+ :param depth: The depth of the stack trace to retrieve
+
+ :return: The caller frame, or None if not available
+ """
stack = inspect.stack()[1:]
if len(stack) < depth + 1:
return None
@@ -111,7 +151,16 @@ def get_caller_frame(depth: int) -> Optional[FrameType]:
def get_caller_directory(depth: int) -> Optional[str]:
- """Get the directory of the file that called this function."""
+ """
+ Get the directory of the caller at a specific stack depth.
+
+ This is used to determine the file_context_path when creating a template,
+ so file paths are resolved relative to the user's template file location.
+
+ :param depth: The depth of the stack trace
+
+ :return: The caller's directory path, or None if not available
+ """
try:
# Get the stack trace
caller_frame = get_caller_frame(depth)
@@ -127,10 +176,36 @@ def get_caller_directory(depth: int) -> Optional[str]:
def pad_octal(mode: int) -> str:
+ """
+ Convert a numeric file mode to a zero-padded octal string.
+
+ :param mode: File mode as a number (e.g., 493 for 0o755)
+
+ :return: Zero-padded 4-digit octal string (e.g., "0755")
+
+ Example
+ ```python
+ pad_octal(0o755) # Returns "0755"
+ pad_octal(0o644) # Returns "0644"
+ ```
+ """
return f"{mode:04o}"
def get_build_step_index(step: str, stack_traces_length: int) -> int:
+ """
+ Get the array index for a build step based on its name.
+
+ Special steps:
+ - BASE_STEP_NAME: Returns 0 (first step)
+ - FINALIZE_STEP_NAME: Returns the last index
+ - Numeric strings: Converted to number
+
+ :param step: Build step name or number as string
+ :param stack_traces_length: Total number of stack traces (used for FINALIZE_STEP_NAME)
+
+ :return: Index for the build step
+ """
if step == BASE_STEP_NAME:
return 0
@@ -143,6 +218,14 @@ def get_build_step_index(step: str, stack_traces_length: int) -> int:
def read_gcp_service_account_json(
context_path: str, path_or_content: Union[str, dict]
) -> str:
+ """
+ Read GCP service account JSON from a file or object.
+
+ :param context_path: Base directory for resolving relative file paths
+ :param path_or_content: Either a path to a JSON file or a service account object
+
+ :return: Service account JSON as a string
+ """
if isinstance(path_or_content, str):
with open(
os.path.join(context_path, path_or_content), "r", encoding="utf-8"
diff --git a/packages/python-sdk/e2b/template_async/main.py b/packages/python-sdk/e2b/template_async/main.py
index 0592987b9..de47042ce 100644
--- a/packages/python-sdk/e2b/template_async/main.py
+++ b/packages/python-sdk/e2b/template_async/main.py
@@ -18,6 +18,10 @@ from .build_api import (
class AsyncTemplate(TemplateBase):
+ """
+ Asynchronous template builder for E2B sandboxes.
+ """
+
@staticmethod
async def build(
template: TemplateClass,
@@ -29,6 +33,37 @@ class AsyncTemplate(TemplateBase):
api_key: Optional[str] = None,
domain: Optional[str] = None,
) -> None:
+ """
+ Build and deploy a template to E2B infrastructure.
+
+ :param template: The template to build
+ :param alias: Alias name for the template
+ :param cpu_count: Number of CPUs allocated to the sandbox
+ :param memory_mb: Amount of memory in MB allocated to the sandbox
+ :param skip_cache: If True, forces a complete rebuild ignoring cache
+ :param on_build_logs: Callback function to receive build logs during the build process
+ :param api_key: E2B API key for authentication
+ :param domain: Domain of the E2B API
+
+ Example
+ ```python
+ from e2b import AsyncTemplate
+
+ template = (
+ AsyncTemplate()
+ .from_python_image('3')
+ .copy('requirements.txt', '/home/user/')
+ .run_cmd('pip install -r /home/user/requirements.txt')
+ )
+
+ await AsyncTemplate.build(
+ template,
+ alias='my-python-env',
+ cpu_count=2,
+ memory_mb=1024
+ )
+ ```
+ """
try:
if on_build_logs:
on_build_logs(
diff --git a/packages/python-sdk/e2b/template_sync/main.py b/packages/python-sdk/e2b/template_sync/main.py
index 20b121798..f61806cb5 100644
--- a/packages/python-sdk/e2b/template_sync/main.py
+++ b/packages/python-sdk/e2b/template_sync/main.py
@@ -18,6 +18,10 @@ from e2b.template_sync.build_api import (
class Template(TemplateBase):
+ """
+ Synchronous template builder for E2B sandboxes.
+ """
+
@staticmethod
def build(
template: TemplateClass,
@@ -29,6 +33,37 @@ class Template(TemplateBase):
api_key: Optional[str] = None,
domain: Optional[str] = None,
) -> None:
+ """
+ Build and deploy a template to E2B infrastructure.
+
+ :param template: The template to build
+ :param alias: Alias name for the template
+ :param cpu_count: Number of CPUs allocated to the sandbox
+ :param memory_mb: Amount of memory in MB allocated to the sandbox
+ :param skip_cache: If True, forces a complete rebuild ignoring cache
+ :param on_build_logs: Callback function to receive build logs during the build process
+ :param api_key: E2B API key for authentication
+ :param domain: Domain of the E2B API
+
+ Example
+ ```python
+ from e2b import Template
+
+ template = (
+ Template()
+ .from_python_image('3')
+ .copy('requirements.txt', '/home/user/')
+ .run_cmd('pip install -r /home/user/requirements.txt')
+ )
+
+ Template.build(
+ template,
+ alias='my-python-env',
+ cpu_count=2,
+ memory_mb=1024
+ )
+ ```
+ """
try:
if on_build_logs:
on_build_logs(