sandbox.commands.run and sandbox.files so every command the model runs, and every file it writes, stays in an isolated VM instead of on your server. The model API key stays in your app; the sandbox never sees it.
Setup
@ai-sdk/openai, set OPENAI_API_KEY, and pass openai("gpt-5.5") as the model. See API keys to create a Superserve API key.
Wire the sandbox into the agent
The highlighted block defines abash tool backed by the sandbox. Everything else is standard AI SDK usage. generateText stops after one step by default, so set stopWhen to let the model run commands, read the results, and answer.
stdout, stderr, and exitCode as an object, so the model sees failed commands as well as their output.
Run code with file tools
Add file tools next tobash to let the model write a script, run it, and read the result. ToolLoopAgent keeps the agent definition reusable and loops for up to 20 steps by default.
claude-haiku-4-5 (trimmed; the model’s wording varies):
sandbox.files paths must be absolute. See Read & write files for binary content and directory downloads.
Stream tool calls
streamText takes the same tools. Read fullStream to show each command and its output while the agent works.
Stream to a browser
In a route handler, returnresult.toUIMessageStreamResponse() instead of reading fullStream. The handler returns before the agent finishes, so a try/finally would kill the sandbox mid-run. Kill the sandbox from the onEnd, onAbort, and onError callbacks instead, and call result.consumeStream() so that one of them runs even if the client disconnects.
consumeStream(), a client disconnect can cancel the stream before any callback fires, and the sandbox keeps running. As a backstop for crashes, set timeoutSeconds and autoDeleteSeconds when you create the sandbox. See Auto-delete.
On Vercel, work that must finish after the response is sent belongs in waitUntil. Register a promise that settles after kill():
vercel.json
Reuse a sandbox across turns
A sandbox outlives the request that created it. Storesandbox.id with the conversation, reconnect on each turn, and pause between turns so files and installed packages stay available without paying for an idle VM.
Sandbox.connect() resumes a paused sandbox, or one that is still pausing, before it returns. See Lifecycle and Connect.
Good to know
- The model can call only the tools you define. Keep
kill(),pause(), andupdate()in your application code, not in a tool. - To limit what model-written code can reach, create the sandbox with network rules.
- Pass
timeoutMstocommands.run. Without it, the SDK request times out after 30 seconds, so the tool call fails on longer commands such as package installs. - The default sandbox has
python3but nopython. Tell the model ininstructions, or use a template with the tools you need.
Resources
AI SDK docs
Tools, agents, and streaming in the AI SDK.
Run commands
Options for
commands.run, including environment variables and working directory.