Documentation Index
Fetch the complete documentation index at: https://docs.ag-kit.dev/llms.txt
Use this file to discover all available pages before exploring further.
Code Executor
Execute code snippets using either secure sandboxed execution or high-performance local execution.
Executor Types
Built-In Code Executor (Sandboxed)
Secure execution in isolated E2B containers with full feature support.
import { BuiltInCodeExecutor } from '@ag-kit/tools';
const executor = new BuiltInCodeExecutor(
{ sandbox }, // Optional: provide existing sandbox
{
timeoutMs: 60000,
envs: { CUSTOM_VAR: 'value' },
onStdout: (data) => console.log('OUT:', data.line),
onStderr: (data) => console.error('ERR:', data.line),
}
);
Unsafe Local Code Executor
Direct execution on local system with identical feature set.
import { UnsafeLocalCodeExecutor } from '@ag-kit/tools';
const executor = new UnsafeLocalCodeExecutor({
timeoutMs: 30000,
envs: { CUSTOM_VAR: 'value' },
onStdout: (data) => console.log('OUT:', data.line),
onStderr: (data) => console.error('ERR:', data.line),
});
Common Features
Both executors support the same feature set:
| Feature | Built-In (Sandboxed) | Unsafe Local |
|---|
| Security | ✅ Isolated | ⚠️ Full access |
| Performance | Network overhead | ✅ Maximum speed |
| Context Persistence | ✅ Yes | ✅ Yes |
| Real-time Output | ✅ onStdout/onStderr | ✅ onStdout/onStderr |
| Environment Variables | ✅ envs | ✅ envs |
| Timeout Control | ✅ timeoutMs | ✅ timeoutMs |
| Multi-language | ✅ Python/JS/TS/Java/R/Bash | ✅ Python/JS/TS/Bash |
Basic Usage
const result = await executor.invoke({
code: 'x = "Hello World!"\nx',
language: 'python'
});
console.log(result.data.results[0].text); // "Hello World!"
Advanced Features
Persistent Context
Variables persist between executions in both executors:
// First execution
await executor.invoke({
code: 'x = 10',
language: 'python'
});
// Second execution - x is still available
const result = await executor.invoke({
code: 'print(x)', // Outputs: 10
language: 'python'
});
Real-time Output Streaming
const executor = new UnsafeLocalCodeExecutor({
onStdout: (data) => console.log('OUT:', data.line),
onStderr: (data) => console.error('ERR:', data.line)
});
await executor.invoke({
code: `
import time
for i in range(3):
print(f"Step {i}")
time.sleep(1)
`,
language: 'python'
});
// Real-time output: OUT: Step 0, OUT: Step 1, OUT: Step 2
Environment Variables
// Built-In Executor
const sandboxExecutor = new BuiltInCodeExecutor({}, {
envs: {
API_KEY: 'secret-key',
DEBUG: 'true'
}
});
// Local Executor
const localExecutor = new UnsafeLocalCodeExecutor({
envs: {
API_KEY: 'secret-key',
DEBUG: 'true'
}
});
const result = await executor.invoke({
code: 'import os; print(os.environ.get("API_KEY"))',
language: 'python'
});
Timeout Configuration
const executor = new UnsafeLocalCodeExecutor({
timeoutMs: 60000 // 60 seconds
});
// For Built-In Executor
const sandboxExecutor = new BuiltInCodeExecutor({}, {
timeoutMs: 60000
});
Setup Instructions
Built-In Executor Setup
export AG_KIT_SANDBOX_API_KEY=your_sandbox_api_key
export AG_KIT_SANDBOX_DOMAIN=your_sandbox_domain # Optional
// Custom sandbox configuration
const sandbox = await Sandbox.create('code-interpreter-v1', {
apiKey: process.env.AG_KIT_SANDBOX_API_KEY,
domain: process.env.AG_KIT_SANDBOX_DOMAIN,
timeoutMs: 60000
});
const executor = new BuiltInCodeExecutor({ sandbox });
Local Executor Setup
Ensure interpreters are installed:
python3 --version # Python
node --version # Node.js
bash --version # Bash
API Reference
Common Interface
interface ICodeExecutorInput {
code: string;
language?: "python" | "js" | "ts" | "java" | "r" | "bash";
}
interface CodeExecutorOptions {
timeoutMs?: number; // Execution timeout (default: 30000)
envs?: Record<string, string>; // Environment variables
onStdout?: (data: OutputMessage) => void; // Real-time stdout callback
onStderr?: (data: OutputMessage) => void; // Real-time stderr callback
onResult?: (result: Result) => void; // Result callback
onError?: (error: ExecutionError) => void; // Error callback
}
Constructor Signatures
// Built-In Executor
new BuiltInCodeExecutor(
fields?: { sandbox?: Sandbox },
options?: CodeExecutorOptions
)
// Local Executor
new UnsafeLocalCodeExecutor(options: CodeExecutorOptions)
Execution Result
interface Execution {
results: Result[]; // Execution outputs
logs: { // Captured logs
stdout: string[];
stderr: string[];
};
error?: ExecutionError; // Error if execution failed
executionCount?: number; // Execution counter
}
Language Support
| Language | Built-In | Local | Notes |
|---|
| Python | ✅ | ✅ | Full support |
| JavaScript | ✅ | ✅ | Full support |
| TypeScript | ✅ | ✅ | Full support |
| Bash | ✅ | ✅ | Full support |
| Java | ✅ | ❌ | Sandbox only |
| R | ✅ | ❌ | Sandbox only |
Environment-Based Selection
function createExecutor() {
const useLocal = process.env.USE_LOCAL_EXECUTOR === 'true';
const options = {
timeoutMs: 60000,
onStdout: (data) => console.log(data.line),
envs: { NODE_ENV: 'development' }
};
return useLocal
? new UnsafeLocalCodeExecutor(options)
: new BuiltInCodeExecutor({}, options);
}
Error Handling
try {
const result = await executor.invoke({
code: userCode,
language: 'python'
});
if (result.data.error) {
console.error('Execution failed:', result.data.error.value);
console.error('Traceback:', result.data.error.traceback);
}
} catch (error) {
console.error('System error:', error);
}
Security Considerations
Built-In Executor
- ✅ Safe for untrusted code
- ✅ Network isolation
- ✅ Filesystem restrictions
- ✅ Resource limits
Local Executor
- ⚠️ Full system access
- ⚠️ Can modify files
- ⚠️ Can make network requests
- ⚠️ Can execute system commands
Security Guidelines:
- Use Built-In for untrusted code
- Validate input before local execution
- Run in restricted environments when possible
- Monitor resource usage
Built-In Executor
- Reuse sandbox instances
- Batch multiple executions
- Use connection pooling
Local Executor
- Leverage persistent context
- Use real-time callbacks for long operations
- Optimize interpreter startup time
Cleanup
// Clean up persistent sessions
executor.cleanup?.();
Troubleshooting
Built-In Executor
- Sandbox creation failed: Check AG_KIT_SANDBOX_API_KEY
- Network timeout: Increase timeout or check connectivity
Local Executor
- Interpreter not found: Install required interpreters
- Permission denied: Check file/directory permissions
- Context lost: Session may have terminated, restart executor