Sandboxed code execution
createSandbox() gives an agent an isolated temp directory to run real JavaScript/Python/bash in and read/write files against — the primitive behind long-horizon coding-agent behavior.
createCodeExecutionTool() wraps it as a single execute_code tool; createSandboxTools() bundles that with write_file/read_file/list_files against the same sandbox, so a model can write a file with one tool and run it with another across turns.
import { createClient, anthropic, defineAgent, runAgent, createSandbox, createSandboxTools } from "samai-sdk";
const sandbox = createSandbox();
const client = createClient({ provider: anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }) });
const agent = defineAgent({
name: "coder",
instructions: "Write and test code using write_file and execute_code. JavaScript runs as an ES module.",
model: "claude-sonnet-4-6",
tools: createSandboxTools(sandbox),
});
const result = await runAgent(client, agent, "Write fibonacci.py, run it, and tell me the output.");
await sandbox.close(); // deletes the temp directoryFor a single one-shot execution tool without file persistence, use createCodeExecutionTool() directly:
tools: [createCodeExecutionTool({ languages: ["javascript", "python"] })]What “sandboxed” means here
Read this before using it against untrusted input.
- Every execution gets its own cwd — file I/O is confined to it, and path traversal via
../is rejected. - A minimal environment (only
PATH/HOME/TMPDIR) — your process's other env vars, including API keys, are not inherited by executed code. - A wall-clock timeout that actually kills the process (
SIGKILL, verified against a realsleepin the test suite), and a byte-accurate output-truncation cap.
Process isolation, not container isolation
dir at a path inside that boundary.Supported languages: "javascript" (ES module via node — import, not require), "python" (via python3, must be on PATH), "bash" (via /bin/bash -c).