Skip to content

Execution

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 took

Execution Options

Pass a full ExecRequest 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'
})
ParameterTypeDescription
cmd (required)string[]Command and arguments as an array, e.g. ["python3", "-c", "print('hello')"]
dirstringWorking directory for the command. Defaults to $HOME
envobjectAdditional environment variables to set
timeout_msnumberTimeout in milliseconds. If exceeded, the process is killed and timed_out is set to true
stdinstringOptional 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)
}

File Operations

Reading Files

// As string (most common)
const text = await sandbox.files.readText('/app/output.txt')
// As raw bytes
const bytes = await 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')

Listing Directories

const listing = await sandbox.files.list('/app')
for (const entry of listing.entries) {
console.log(entry.name, entry.type === 'directory' ? '(dir)' : 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 })

Installing Packages

Node.js
// Python
await sandbox.exec.run('pip install numpy pandas scikit-learn')
await sandbox.exec.run('npm install lodash axios')
// System packages
await sandbox.exec.run('apt-get update && apt-get install -y ffmpeg')