Concepts
Execution
Running commands and managing files in sandboxes
Executing Commands
Use sandbox.exec.run() to run shell commands:
const result = await sandbox.exec.run('echo "Hello, World!"')
console.log(result.stdout) // "Hello, World!\n"
console.log(result.stderr) // ""
console.log(result.exit_code) // 0
console.log(result.ok) // true (exit_code == 0)
console.log(result.duration_ms) // time the command tookresult = sandbox.exec.run(["echo", "Hello, World!"])
print(result.stdout) # "Hello, World!\n"
print(result.stderr) # ""
print(result.exit_code) # 0
print(result.ok) # True (exit_code == 0)
print(result.duration_ms) # time the command tookPython's exec.run() requires a list[str] — passing a bare string raises a ValidationError. Use ["bash", "-c", "..."] when you need shell features like pipes or globs.
Execution Options
Pass keyword arguments for fine-grained control:
const result = await sandbox.exec.run({
cmd: ['python3', 'train.py'],
dir: '/app', // working directory (field name is dir, not cwd)
env: {
DEBUG: 'true',
API_KEY: 'secret'
},
timeout_ms: 60000, // 60 second timeout
stdin: 'input data'
})result = sandbox.exec.run(
["python3", "train.py"],
dir="/app",
env={"DEBUG": "true", "API_KEY": "secret"},
timeout_ms=60000,
stdin="input data",
)| Parameter | Type | Description |
|---|---|---|
cmd (required) | string[] / list[str] | Command and arguments as an array, e.g. ["python3", "-c", "print('hello')"] |
dir | string | Working directory for the command. Defaults to $HOME |
env | object / dict | Additional environment variables to set |
timeout_ms | number / int | Timeout in milliseconds. If exceeded, the process is killed and timed_out is set to true |
stdin | string | Optional stdin to pass to the process |
Handling Timeouts
const result = await sandbox.exec.run({
cmd: ['python3', 'long_job.py'],
timeout_ms: 30000,
})
if (result.timed_out) {
console.log('Command timed out after 30s')
} else if (!result.ok) {
console.error('Failed with exit code:', result.exit_code)
console.error(result.stderr)
}result = sandbox.exec.run(["python3", "long_job.py"], timeout_ms=30000)
if result.timed_out:
print("Command timed out after 30s")
elif not result.ok:
print("Failed with exit code:", result.exit_code)
print(result.stderr)File Operations
Reading Files
const text = await sandbox.files.readText('/app/output.txt')
const bytes = await sandbox.files.read('/app/model.bin')# As string (most common)
text = sandbox.files.read_text("/app/output.txt")
# As raw bytes
data = sandbox.files.read("/app/model.bin")Writing Files
await sandbox.files.write('/app/config.json', JSON.stringify({
model: 'gpt-4',
temperature: 0.7
}))
// With explicit permissions
await sandbox.files.write('/app/run.sh', '#!/bin/sh\necho hello', '0755')import json
sandbox.files.write("/app/config.json", json.dumps({"model": "gpt-4", "temperature": 0.7}))
# With explicit permissions
sandbox.files.write("/app/run.sh", "#!/bin/sh\necho hello", mode="0755")Listing Directories
const listing = await sandbox.files.list('/app')
for (const entry of listing.entries) {
console.log(entry.name, entry.is_dir ? '(dir)' : entry.size)
}listing = sandbox.files.list("/app")
for entry in listing.entries:
print(entry.name, "(dir)" if entry.is_dir else entry.size)Other Operations
// Check existence
const { exists } = await sandbox.files.exists('/app/data.csv')
// Stat a path
const info = await sandbox.files.stat('/app/output.txt')
console.log(info.size, info.modified_at)
// Move/rename
await sandbox.files.move({ source: '/tmp/result.txt', destination: '/app/result.txt' })
// Remove
await sandbox.files.remove('/tmp/scratch', { recursive: true })
// Create directory
await sandbox.files.mkdir({ path: '/app/data', parents: true })# Check existence
result = sandbox.files.exists("/app/data.csv")
# Stat a path
info = sandbox.files.stat("/app/output.txt")
print(info.size, info.modified_at)
# Move/rename
sandbox.files.move("/tmp/result.txt", "/app/result.txt")
# Remove
sandbox.files.remove("/tmp/scratch", recursive=True)
# Create directory
sandbox.files.mkdir("/app/data", parents=True)Installing Packages
// Python
await sandbox.exec.run('pip install numpy pandas scikit-learn')
// Node.js
await sandbox.exec.run('npm install lodash axios')
// System packages
await sandbox.exec.run('apt-get update && apt-get install -y ffmpeg')# Python packages
sandbox.exec.run(["bash", "-c", "pip install numpy pandas scikit-learn"])
# Node.js packages
sandbox.exec.run(["bash", "-c", "npm install lodash axios"])
# System packages
sandbox.exec.run(["bash", "-c", "apt-get update && apt-get install -y ffmpeg"])Install dependencies once, create a checkpoint, then use fork() to spin up fresh copies with those deps already in place.