Executes a shell command in the sandbox and waits for it to complete. Returns the full output and exit code.
Method Signature
await sandbox.exec(
command: string,
options?: ExecOptions
): Promise<ExecResult>
Parameters
Shell command to execute. The command runs in a bash shell with full shell features (pipes, redirects, etc.).
Execution options
Maximum execution time in milliseconds. Command is terminated if it exceeds this limit.
Environment variables to set for this command only (merged with session environment)
Working directory for the command. Defaults to the session’s current working directory.
Session ID to execute in. Uses the default session if not specified.
Returns
Standard output captured from the command
Standard error output captured from the command
Exit code from the command (0 typically indicates success)
True if exitCode is 0, false otherwise
Examples
Basic command execution
const result = await sandbox.exec('echo "Hello, World!"');
console.log(result.stdout); // "Hello, World!\n"
console.log(result.success); // true
Command with timeout
try {
const result = await sandbox.exec('sleep 10', { timeout: 3000 });
} catch (error) {
console.error('Command timed out after 3 seconds');
}
Command with environment variables
const result = await sandbox.exec('echo $MY_VAR', {
env: { MY_VAR: 'custom value' }
});
console.log(result.stdout); // "custom value\n"
Command with custom working directory
await sandbox.exec('mkdir -p /workspace/project');
const result = await sandbox.exec('pwd', {
cwd: '/workspace/project'
});
console.log(result.stdout); // "/workspace/project\n"
Running Python code
const result = await sandbox.exec('python3 -c "print(2 + 2)"');
console.log(result.stdout); // "4\n"
Error handling
const result = await sandbox.exec('ls /nonexistent');
if (!result.success) {
console.error('Command failed with exit code:', result.exitCode);
console.error('Error output:', result.stderr);
}