Instance (interface)
Overview
Methods available for interacting with a compute sandbox instance. Exported as the InstanceInterface type (Instance internally).
Deprecated alias: the
Sandbox/SandboxInterfacetype names still work as aliases forInstanceInterface.
runCommand(command, options?)
Execute shell commands in the sandbox with full control over execution environment.
Parameters:
command(string, required): The shell command to execute as a single stringoptions(RunCommandOptions, optional): Execution optionscwd(string, optional): Working directory for command executionenv(Record<string, string>, optional): Environment variables to settimeout(number, optional): Command timeout in millisecondsbackground(boolean, optional): Run command in background without waiting for completiononStdout((data: string) => void, optional): Callback invoked with stdout chunks as the command runsonStderr((data: string) => void, optional): Callback invoked with stderr chunks as the command runs
Returns: Promise<CommandResult> - Command execution result with output streams, exit code, and duration
CommandResult interface:
stdout(string): Standard output from the commandstderr(string): Standard error output from the commandexitCode(number): Exit code (0 for success, non-zero for errors)durationMs(number): Command execution duration in milliseconds
Examples:
Notes:
Commands are executed as a single string, not as separate command + arguments arrays
Use shell operators (
&&,||,|, etc.) within the command string for complex operationsNon-zero exit codes indicate command failure but do not throw errors - check
exitCodein the resultBackground commands return immediately with
exitCode: 0without waiting for completionThe command runs in a shell context, so all shell features (pipes, redirects, etc.) are available
Passing
onStdout/onStderrenables incremental streaming of command output. The returnedCommandResultstill contains the completestdoutandstderronce the command finishesStreaming callbacks cannot be combined with
background: true— doing so throwsAvailable on all sandbox instances regardless of provider
Streaming output with onStdout / onStderr
By default runCommand buffers all output and only resolves once the command finishes. Pass onStdout and/or onStderr to receive output incrementally as the command runs — useful for long-running commands (installs, builds, dev servers) where you want to surface progress instead of waiting for completion.
Both are optional callbacks with the signature (data: string) => void. Each fires once per output chunk delivered as the command streams, in order, while the command executes.
Accumulate streamed chunks yourself, e.g. to push progress to a UI:
Behavior:
The callbacks are additive, not a replacement. The returned
CommandResultstill contains the fullstdoutandstderronce the command finishes, regardless of whether you passed callbacks.Chunk boundaries are not guaranteed. A chunk may contain a partial line, multiple lines, or a mix — do not assume one callback invocation equals one line. Buffer and split on
\nyourself if you need line-by-line handling.Runtime selection is capability-specific: provider-native streaming first, then the POSIX shell fallback. The in-sandbox daemon is used only with provider config
processRuntime: 'daemond', and native hooks still take precedence. Shell streaming on instances whose execs share no state falls back to one plain execution, delivering output at completion rather than incrementally.Cannot be combined with
background: true. Passing streaming callbacks together withbackground: truethrows, since a backgrounded command returns immediately and has no output to stream.
startProcess(command, options?)
Start an interactive long-running process. Unlike runCommand, this returns immediately with a handle while the process keeps running — the handle lets you write to its stdin, poll its status, and wait for or kill it.
Parameters:
command(string): Shell command to run; native providers may use their own shell invocationoptions(StartProcessOptions, optional):cwd(string): Working directoryenv(Record<string, string>): Environment variablesstdin(boolean): Open a writable stdin pipe (defaultfalse)onStdout/onStderr((chunk: string) => void): Streamed output callbacksonExit((result: { exitCode: number | null; signal: string | null }) => void): Fires once when the process exitspollIntervalMs(number): Daemond status-polling fallback interval (default 500 ms); the shell tier uses in-instance long-polls instead
Returns: Promise<ProcessHandle>
Behavior:
Provider-native
startProcesswins. Otherwise the default shell tier uses plain provider execs,nohup setsid, process groups, stdin FIFOs, and durable framed logs under${TMPDIR:-/tmp}/.computesdk/jobs/<jobId>/. No Node installation, daemon download, or routable port is needed.Inspect
sandbox.processRuntime, e.g.{ streaming: 'native', processes: 'shell' }.sandbox.attachProcess(jobId, options?)reattaches to a shell-tier job from a new client; output is replayed from the start of its log. Usestdin: trueto write to a job originally started with stdin enabled. Native/daemon reattachment is not implemented by this method.Shell callbacks come from incremental log reads, not necessarily the command's write boundaries. Each handle keeps up to 4 Mi characters per stream, retaining the tail with
truncated: truewhen exceeded; the on-instance log remains available until cleanup. Job directories are removed 10 minutes after exit (60 seconds after kill).Shell
kill()signals the whole process group. A streamingrunCommandtimeout uses an in-instance watchdog (exit code 124), even if the client disconnects.handle.wait({ timeout })only bounds waiting; it does not kill the process.The shell tier requires POSIX tools including
sh,setsid,mkfifo,kill,cat,dd,wc,tail,head,base64,mkdir,rm,mv, andsleep. Missing tools raiseShellProcessUnsupportedError. Instances without shared filesystem/process state between execs raiseShellStateNotPersistentErroronstartProcessbefore executing the user's command.To opt into daemond, configure the provider, e.g.
e2b({ processRuntime: 'daemond' }). This tier needs Node or an image it can bootstrap Node into. Its callbacks use buffered status snapshots, with SSE when reachable and polling otherwise; each stream retains a 4-MiB tail and exited processes remain retrievable for 10 minutes. These are daemon-specific requirements, not the default process contract.
Lifecycle
pause() / resume()
Optional native operations. Check typeof sandbox.pause === 'function' and read provider.instances.pause on the direct provider before creation:
memory: whether running processes and memory survive pause/resume.falsemeans a filesystem-preserving stop/start, not process suspension.createOptions: options the instance needs to be pausable (for example{ persistent: true }on Vercel or{ ephemeral: false }on Archil/Upstash).
Do not use destroy() as pause: destruction is cleanup, not a reversible operation. Some providers expose the methods on all handles but reject an incompatible backend or execution mode; apply the declared requirements and check the provider page.
extendLifetime(ms) and timeouts
extendLifetime is optional and keeps the instance alive for ms more from now, within the provider's limit; it is not an increment added to the previous deadline. The direct provider's instances.lifetime, when declared, contains defaultMs (when create sets no timeout), maxMs (absent means no declared bound), and extendable (whether the instance method exists). Providers need not publish this descriptor; its absence is not a promise of unlimited lifetime or extension support.
instances.create({ timeout }) configures the provider's lifetime/idle policy; runCommand(command, { timeout }) bounds a command; process.wait({ timeout }) only bounds the caller's wait. All SDK values here are milliseconds. Native options may use other units. Auto-delete, auto-stop, and auto-pause are not interchangeable: see the provider page, and always destroy resources when finished.
Snapshots and forks
Snapshots belong to the provider, not the instance: use provider.snapshot.create(sandbox.instanceId) and restore with provider.instances.create({ snapshotId }). Read the source's required create options and the snapshot's scope/memory/source semantics before capture. There is no universal sandbox.fork() method: independent forks are new instances restored from the same snapshot only where the provider supports that behavior. See snapshot capabilities and safe cleanup.
getInfo()
Get information about the sandbox including status, provider, and metadata.
Parameters: None
Returns: Promise<InstanceInfo> - Sandbox information including status and configuration
InstanceInfo interface:
id(string): Unique identifier for the sandboxprovider(string): Provider hosting the sandbox (e.g., 'e2b', 'modal', 'docker')status(string): Current sandbox status ('running' | 'stopped' | 'error')createdAt(Date): Timestamp when the sandbox was createdtimeout(number): Execution timeout in millisecondsmetadata(Record<string, any>, optional): Additional provider-specific metadata
Examples:
Notes:
Returns information about the sandbox's current state and configuration
May return locally cached information depending on provider implementation
The
metadatafield contains any custom metadata set during sandbox creationAvailable on all sandbox instances regardless of provider
getUrl(options)
Get a publicly accessible URL for accessing services running on a specific port in the sandbox.
Parameters:
options(object, required): URL configuration optionsport(number, required): Port number where the service is running in the sandboxprotocol(string, optional): Protocol to use ('http' | 'https'). Defaults to 'https'
Returns: Promise<string> - Publicly accessible URL for the specified port
Examples:
Notes:
Returns a publicly accessible URL that routes to the specified port in your sandbox
Whether a network call is needed depends on the provider — some construct the URL synchronously from the sandbox host (e.g. E2B), while others resolve it via an API call (e.g. Modal tunnels, Daytona preview links). Always
awaitthe resultThe service must be running on the specified port for the URL to be accessible
sandbox.filesystem
ComputeSDK provides filesystem operations for managing files and directories within sandboxes. All filesystem operations are accessed through the sandbox.filesystem object.
filesystem.readFile(path)
Read the contents of a file from the sandbox filesystem.
Parameters:
path(string, required): Absolute path to the file to read within the sandbox
Returns: Promise<string> - File contents as UTF-8 encoded string
Examples:
Notes:
Always returns UTF-8 encoded strings
Throws an error if the file does not exist
Requires absolute paths (paths should start with
/)No encoding options available - always returns UTF-8
filesystem.writeFile(path, content)
Write content to a file in the sandbox filesystem, creating the file if it doesn't exist.
Parameters:
path(string, required): Absolute path where the file should be writtencontent(string, required): Content to write to the file as UTF-8 text
Returns: Promise<void> - Resolves when the file is successfully written
Examples:
Notes:
Always writes UTF-8 encoded text
Creates the file if it doesn't exist
Overwrites existing files completely (previous content is lost)
Requires absolute paths (paths should start with
/)No encoding options available - always UTF-8
filesystem.mkdir(path)
Create a directory in the sandbox filesystem, automatically creating parent directories as needed.
Parameters:
path(string, required): Absolute path of the directory to create
Returns: Promise<void> - Resolves when the directory is successfully created
Examples:
Notes:
Automatically creates parent directories as needed
Does not throw an error if the directory already exists
Requires absolute paths (paths should start with
/)Throws errors only on actual failures (permissions, invalid paths, disk space issues)
filesystem.readdir(path)
List the contents of a directory in the sandbox filesystem.
Parameters:
path(string, required): Absolute path to the directory to list
Returns: Promise<FileEntry[]> - Array of entries in the directory
FileEntry interface:
name(string): Name of the file or directorytype('file' | 'directory'): Type of the entrysize(number, optional): Size in bytes (for files)modified(Date, optional): Last modification timestamp
Examples:
Notes:
Returns an array of FileEntry objects with file/directory metadata
Requires absolute paths (paths should start with
/)Only lists direct children - does not recursively list subdirectories
Throws an error if the directory does not exist
The
sizeandmodifiedfields may not be available on all providersEmpty directories return an empty array (not an error)
filesystem.exists(path)
Check if a file or directory exists at the specified path in the sandbox filesystem.
Parameters:
path(string, required): Absolute path to the file or directory to check
Returns: Promise<boolean> - Returns true if the path exists (file or directory), false otherwise
Examples:
Notes:
Returns a boolean value - never throws errors (unlike
readFileorreaddir)Works for both files and directories - no distinction in the return value
Requires absolute paths (paths should start with
/)Returns
falsefor non-existent paths, not an errorCannot distinguish between a file and directory from the return value alone
Useful for defensive programming to prevent errors before operations
filesystem.remove(path)
Remove a file or directory from the sandbox filesystem. For directories, this recursively removes all contents.
Parameters:
path(string, required): Absolute path to the file or directory to remove
Returns: Promise<void> - Resolves when the file or directory is successfully removed
Examples:
Notes:
Works for both files and directories - no distinction needed
Recursive deletion for directories - removes all contents and subdirectories (like
rm -rf)Requires absolute paths (paths should start with
/)Throws an error if the path does not exist
Deletion is permanent - no recycle bin, trash, or undo capability
Use with caution - destructive operation that cannot be reversed
For directories, all nested files and subdirectories are removed automatically
No confirmation prompt - removal happens immediately
Last updated
Was this helpful?