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) // 0console.log(result.ok) // true (exit_code == 0)console.log(result.duration_ms) // time the command tookExecution 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'})| Parameter | Type | Description |
|---|---|---|
cmd (required) | string[] | Command and arguments as an array, e.g. ["python3", "-c", "print('hello')"] |
dir | string | Working directory for the command. Defaults to $HOME |
env | object | Additional environment variables to set |
timeout_ms | number | 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)}File Operations
Reading Files
// As string (most common)const text = await sandbox.files.readText('/app/output.txt')
// As raw bytesconst 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 permissionsawait 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 existenceconst { exists } = await sandbox.files.exists('/app/data.csv')
// Stat a pathconst info = await sandbox.files.stat('/app/output.txt')console.log(info.size, info.modified_at)
// Move/renameawait sandbox.files.move({ source: '/tmp/result.txt', destination: '/app/result.txt' })
// Removeawait sandbox.files.remove('/tmp/scratch', { recursive: true })
// Create directoryawait sandbox.files.mkdir({ path: '/app/data', parents: true })Installing Packages
// Pythonawait sandbox.exec.run('pip install numpy pandas scikit-learn')
await sandbox.exec.run('npm install lodash axios')
// System packagesawait sandbox.exec.run('apt-get update && apt-get install -y ffmpeg')