Execute Commands
Learn how to run commands in sandboxes with synchronous and streaming execution.
Basic Execution
Execute a command and wait for the result:
import SandboxSDK from '@akiralabs/sandbox-sdk';
const client = new SandboxSDK({
apiKey: process.env['AKIRA_API_KEY'],
});
const result = await client.sandboxes.execute(sandbox.id, {
command: 'ls -la /app',
});
console.log(result.stdout);
console.log(`Exit code: ${result.exit_code}`);Response Structure
The execute method returns:
interface ExecuteResponse {
id: string; // Unique execution ID
status: string; // 'running' | 'completed' | 'timeout' | 'error'
exit_code: number; // Command exit code (0 = success)
stdout: string; // Standard output
stderr: string; // Standard error
execution_time_ms: number;
created_at: string;
completed_at: string;
}Configuration Options
Timeout
Set a maximum execution time (1-300 seconds, default 30):
const result = await client.sandboxes.execute(sandbox.id, {
command: 'npm install',
timeout: 120, // 2 minutes
});Working Directory
Set the directory where the command runs:
const result = await client.sandboxes.execute(sandbox.id, {
command: 'npm test',
working_dir: '/app/project',
});Environment Variables
Pass additional environment variables:
const result = await client.sandboxes.execute(sandbox.id, {
command: 'node server.js',
env: {
PORT: '3000',
DEBUG: 'true',
},
});Command Patterns
Shell Features
Use pipes, redirects, and chaining:
// Pipe output
await client.sandboxes.execute(sandbox.id, {
command: 'cat data.json | jq ".items"',
});
// Redirect output
await client.sandboxes.execute(sandbox.id, {
command: 'npm install > /dev/null 2>&1',
});
// Chain commands
await client.sandboxes.execute(sandbox.id, {
command: 'cd /app && npm install && npm test',
});Python Execution
// Inline script
const result = await client.sandboxes.execute(sandbox.id, {
command: 'python3 -c "import json; print(json.dumps({\'result\': 42}))"',
});
// Run a file
const result = await client.sandboxes.execute(sandbox.id, {
command: 'python3 /app/script.py',
timeout: 60,
});Node.js Execution
// Inline script
const result = await client.sandboxes.execute(sandbox.id, {
command: 'node -e "console.log(JSON.stringify({ result: 42 }))"',
});
// Run a file
const result = await client.sandboxes.execute(sandbox.id, {
command: 'node /app/index.js',
});Streaming Execution
For long-running commands, use streaming to get real-time output:
const stream = await client.sandboxes.executeAsync(sandbox.id, {
command: 'npm install',
});
for await (const chunk of stream) {
if (chunk.stdout) {
process.stdout.write(chunk.stdout);
}
if (chunk.stderr) {
process.stderr.write(chunk.stderr);
}
if (chunk.exit_code !== undefined) {
console.log(`\nProcess exited with code: ${chunk.exit_code}`);
}
}Error Handling
⚠️
Always Check Exit Code
A completed execution doesn't mean success. Always check exit_code - zero means success, non-zero means failure.
const result = await client.sandboxes.execute(sandbox.id, {
command: 'npm test',
});
if (result.exit_code !== 0) {
console.error('Tests failed:');
console.error(result.stderr);
throw new Error(`Command failed with exit code ${result.exit_code}`);
}
console.log('Tests passed!');Status Values
| Status | Description |
|---|---|
running | Command is still executing |
completed | Command finished (check exit_code for success) |
timeout | Command exceeded timeout limit |
error | Execution failed (sandbox error, not command error) |
Timeout Handling
const result = await client.sandboxes.execute(sandbox.id, {
command: 'sleep 60',
timeout: 5,
});
if (result.status === 'timeout') {
console.log('Command timed out');
}REST API
Synchronous Execution
curl -X POST https://api.akiralabs.ai/v1/sandboxes/{sandbox_id}/execute \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"command": "python3 -c \"print(2+2)\"",
"timeout": 30,
"working_dir": "/app"
}'Streaming Execution
curl -X POST https://api.akiralabs.ai/v1/sandboxes/{sandbox_id}/execute_async \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"command": "npm install"
}'Returns NDJSON (newline-delimited JSON) stream:
{"stdout": "Installing packages...\n"}
{"stdout": "Done!\n"}
{"exit_code": 0}Best Practices
- Set appropriate timeouts - Long operations need longer timeouts
- Check exit codes - Don't assume completion means success
- Use streaming for long commands - Get real-time feedback
- Handle both stdout and stderr - Errors may be in either stream
- Quote shell arguments - Prevent injection vulnerabilities
// Good: Use array for arguments when possible
const filename = userInput;
const result = await client.sandboxes.execute(sandbox.id, {
command: `cat "${filename.replace(/"/g, '\\"')}"`,
});Next Steps
- Learn about sandbox configuration
- Explore use cases for AI agents