Home Features Architecture Docs SDKs Get Started
TypeScript Python Go

TypeScript & JavaScript

Async/await client for Isolon with typed errors, streaming I/O, WebSocket terminals, and file transfer helpers.

Add to your project

bash
npm install isolon-sdk

# or from source within the isolon repo
cd sdk/ts
npm install
npm run build

Environment variables

VariableDescriptionDefault
ISOLON_API_URLIsolon server URLhttp://localhost:8080
ISOLON_API_KEYAPI key for authentication(none)

Your first sandbox

sandbox.ts
import { Sandbox } from "isolon-sdk";

// Create a sandbox
const sandbox = await Sandbox.create({
  image: "python:3.12-alpine",
  cpus: 2,
  memory_mb: 1024,
  envs: { OPENAI_API_KEY: process.env.OPENAI_API_KEY },
  on_start: ["pip install openai langchain"]
});

// Run commands
const result = await sandbox.commands.run("python --version");
console.log(result.stdout);  // Python 3.12.3

// Write and read files
await sandbox.files.write("/app/main.py", "print('Hello')");
const content = await sandbox.files.read("/app/main.py");

// Commit for instant reuse
const img = await sandbox.commit("my-image");

// Cleanup
await sandbox.close();

TypeScript SDK

Static methods

MethodReturnsDescription
Sandbox.create(opts?)Promise<Sandbox>Create a new sandbox. Waits for agent healthy before resolving.
Sandbox.connect(id, opts?)Promise<Sandbox>Connect to an existing sandbox by ID.
Sandbox.list(opts?)Promise<Sandbox[]>List sandboxes. Optional label filtering via opts.labels.
Sandbox.listProfiles()Promise<Profile[]>List available pre-defined profiles from the server.
Sandbox.getSystemStats()Promise<SystemStats>Get server-level CPU/memory stats.

Instance properties & methods

MemberType / ReturnsDescription
idstringWorkspace ID
commandsCommandManagerExecute commands in the sandbox
filesFileManagerRead, write, list, watch files
gitGitManagerClone, commit, push, pull, branch operations
terminalTerminalManagerWebSocket PTY sessions
processProcessManagerList, kill, attach to processes
portsPortManagerList ports, wait for services, preview URLs
close()Promise<void>Destroy the sandbox
pause()Promise<void>Pause the VM (freeze state in memory)
resume()Promise<void>Resume a paused VM
isRunning()Promise<boolean>Check if the sandbox is healthy
getInfo()Promise<SandboxInfo>Get metadata: ID, template, status, createdAt
setTimeout(ms)Promise<void>Update the auto-destroy timeout
runCode(code, opts?)Promise<ExecResult>Run code in a persistent REPL context (python, js, bash)
commit(ref?)Promise<CommitResult>Save filesystem as a reusable image
fork()Promise<Sandbox>Create a copy of this sandbox
snapshot()Promise<SnapshotResult>Capture full VM state (memory + disk)
getStats()Promise<VMStats>Current CPU, memory, disk, network usage
streamStats(cb)() => voidSubscribe to real-time stats via SSE. Returns unsubscribe function.
getMetrics()Promise<Metrics[]>Legacy E2B-compatible metrics format
updateMemory(mb)Promise<void>Adjust VM memory via balloon device
applySandboxFile(yaml)Promise<void>Apply a declarative Sandboxfile configuration
getPreviewUrl(port)Promise<string>Get a shareable URL for a sandbox port
setInternet(enabled)Promise<void>Toggle outbound internet access
execInTerminal(cmd)Promise<void>Execute a command through the active PTY
onEvent(cb)() => voidSubscribe to lifecycle events (starting, running, stopped, etc.)
streamLogs(cb)() => voidSubscribe to serial console logs via WebSocket

CommandManager

MethodDescription
run(cmd, opts?)Execute a command. Options: envs, background, onStdout, onStderr, context.

FileManager

MethodDescription
read(path)Read a text file
write(path, content)Write a text or binary (Uint8Array) file
list(path)List directory contents with FileInfo entries
makeDir(path)Create a directory
exists(path)Check if a path exists
remove(path)Delete a file or directory
rename(oldPath, newPath)Rename/move a file
watch(path, cb)Watch a directory for changes. Returns unsubscribe function.
watchMultiplex(paths, cb)Watch multiple directories over a single WebSocket
readStream(path)Read a file as a ReadableStream
writeStream(path, stream)Write from a ReadableStream, Blob, ArrayBuffer, or string
uploadArchive(tarData, remotePath)Upload a tar archive and extract it
downloadArchive(remotePath)Download a directory as a tar archive (ReadableStream)
uploadDir(files, remotePath)Upload multiple files at once from a Record<string, string|Uint8Array>
downloadDir(remotePath)Download a directory as Record<string, Uint8Array>

GitManager

MethodDescription
clone(url, opts?)Clone a repository. Options: path, branch, depth, username, password.
status(path)Get git status output
add(path, files?)Stage files (all if files omitted)
commit(path, message, opts?)Commit changes. Options: authorName, authorEmail, allowEmpty, files.
push(path, opts?)Push to remote. Options: remote, branch, username, password, setUpstream.
pull(path, opts?)Pull from remote. Options: remote, branch, username, password.
remoteAdd(path, name, url, opts?)Add a remote. Options: fetch, overwrite.
branches(path)List branches
createBranch(path, name)Create a new branch
checkoutBranch(path, name, opts?)Checkout a branch. Options: force.
deleteBranch(path, name)Delete a branch
getConfig(key, opts?)Get a git config value. Options: scope, path.
setConfig(key, value, opts?)Set a git config value. Options: scope, path.

TerminalManager & TerminalHandle

MethodDescription
terminal.connect()Open a WebSocket PTY session. Returns TerminalHandle.
terminal.resize(cols, rows)Resize the active PTY
terminal.execInTerminal(cmd)Execute a command through the active PTY
terminal.getSessionId()Get the current session ID
handle.write(data)Write data to terminal stdin
handle.onData(cb)Register callback for terminal output
handle.resize({cols, rows})Resize the PTY
handle.wait(timeout?)Wait for session to end
handle.close()Close the terminal session

ProcessManager

MethodDescription
process.list()List running processes with PID, PPID, CPU%, MEM%, command
process.kill(pid, signal?)Kill a process. Signal defaults to SIGKILL.
process.attach(pid, cb)Attach to a background process output stream. Returns unsubscribe.

PortManager

MethodDescription
ports.list()List open ports with protocol, state, and address
ports.waitForPort(port, timeoutMs?)Wait for a port to be listening
ports.getPreviewUrl(port)Get a shareable preview URL for a port

ImageManager

MethodDescription
ImageManager.convert(imageRef)Convert a Docker/OCI image to MicroVM rootfs
ImageManager.build(context, tag, dockerfile?)Build from a tarball context
ImageManager.list()List images
ImageManager.get(id)Get image status
ImageManager.warm(id)Pre-create VM snapshot for faster boot
ImageManager.delete(id)Delete an image
ImageManager.listTemplates()List cached templates
ImageManager.uploadTemplate(buffer, name)Upload a template tarball
ImageManager.deleteTemplate(name)Delete a template

Common patterns

Streaming command output

streaming.ts
const result = await sandbox.commands.run(
  "for i in 1 2 3 4 5; do echo $i; sleep 1; done",
  {
    onStdout: (data) => process.stdout.write(`OUT: ${data}`),
    onStderr: (data) => process.stderr.write(`ERR: ${data}`)
  }
);
console.log(`Exit code: ${result.exitCode}`);

Background process with attach

background.ts
const bg = await sandbox.commands.run("python server.py", { background: true });
console.log(`Started process with PID: ${bg.pid}`);

// Attach to stream its output
const stop = sandbox.process.attach(bg.pid!, (data) => console.log(data));

// Later, stop streaming and kill
stop();
await sandbox.process.kill(bg.pid!);

File watching

watch.ts
const stop = await sandbox.files.watch("/app/src", (event) => {
  console.log(`${event.type}: ${event.name}`);
});

// ... do some work ...

stop();

Git workflow

git.ts
await sandbox.git.clone(
  "https://github.com/user/repo.git",
  { path: "/workspace/repo", branch: "main", depth: 1 }
);

await sandbox.git.add("/workspace/repo");
await sandbox.git.commit("/workspace/repo", "Update", {
  authorName: "Dev",
  authorEmail: "dev@example.com"
});
await sandbox.git.push("/workspace/repo", {
  remote: "origin",
  branch: "main",
  username: "user",
  password: "token"
});

Persistent REPL context

repl.ts
await sandbox.runCode("x = 1", { language: "python", context: "my-session" });
await sandbox.runCode("x += 1", { language: "python", context: "my-session" });

const result = await sandbox.runCode(
  "print(x)",
  { language: "python", context: "my-session" }
);
console.log(result.stdout);  // 2

Typed errors

errors.ts
import {
  Sandbox,
  IsolonError,
  SandboxNotFoundError,
  SandboxNotRunningError,
  QuotaExceededError,
  AuthenticationError
} from "isolon-sdk";

try {
  const sandbox = await Sandbox.create({ image: "python:3.12-alpine" });
} catch (e) {
  if (e instanceof AuthenticationError) {
    console.error(`Auth failed: ${e.message}`);
  } else if (e instanceof QuotaExceededError) {
    console.error(`Rate limited: ${e.message}`);
  } else if (e instanceof SandboxNotFoundError) {
    console.error(`Not found: ${e.message}`);
  } else if (e instanceof IsolonError) {
    console.error(`Error: ${e.message} (status: ${e.statusCode})`);
  } else {
    throw e;
  }
}