sandbox-agent/docs/sdk-overview.mdx
Nathan Flurry cf7e2a92c6
SDK: Add ensureServer() for automatic server recovery (#260)
* SDK sandbox provisioning: built-in providers, docs restructure, and quickstart overhaul

- Add built-in sandbox providers (local, docker, e2b, daytona, vercel, cloudflare) to the TypeScript SDK so users import directly instead of passing client instances
- Restructure docs: rename architecture to orchestration-architecture, add new architecture page for server overview, improve getting started flow
- Rewrite quickstart to be TypeScript-first with provider CodeGroup and custom provider accordion
- Update all examples to use new provider APIs
- Update persist drivers and foundry for new SDK surface

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix SDK typecheck errors and update persist drivers for insertEvent signature

- Fix insertEvent call in client.ts to pass sessionId as first argument
- Update Daytona provider create options to use Partial type (image has default)
- Update StrictUniqueSessionPersistDriver in tests to match new insertEvent signature
- Sync persist packages, openapi spec, and docs with upstream changes

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add Modal and ComputeSDK built-in providers, update examples and docs

- Add `sandbox-agent/modal` provider using Modal SDK with node:22-slim image
- Add `sandbox-agent/computesdk` provider using ComputeSDK's unified sandbox API
- Update Modal and ComputeSDK examples to use new SDK providers
- Update Modal and ComputeSDK deploy docs with provider-based examples
- Add Modal to quickstart CodeGroup and docs.json navigation
- Add provider test entries for Modal and ComputeSDK
- Remove old standalone example files (modal.ts, computesdk.ts)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix Modal provider: pre-install agents in image, fire-and-forget exec for server

- Pre-install agents in Dockerfile commands so they are cached across creates
- Use fire-and-forget exec (no wait) to keep server alive in Modal sandbox
- Add memoryMiB option (default 2GB) to avoid OOM during agent install

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Sync upstream changes: multiplayer docs, logos, openapi spec, foundry config

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* SDK: Add ensureServer() for automatic server recovery

Add ensureServer() to SandboxProvider interface to handle cases where the
sandbox-agent server stops or goes to sleep. The SDK now calls this method
after 3 consecutive health-check failures, allowing providers to restart the
server if needed. Most built-in providers (E2B, Daytona, Vercel, Modal,
ComputeSDK) implement this. Docker and Cloudflare manage server lifecycle
differently, and Local uses managed child processes.

Also update docs for quickstart, architecture, multiplayer, and session
persistence; mark persist-* packages as deprecated; and add ensureServer
implementations to all applicable providers.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* wip

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 20:29:28 -07:00

238 lines
6 KiB
Text

---
title: "SDK Overview"
description: "Use the TypeScript SDK to manage Sandbox Agent sessions and APIs."
icon: "compass"
---
The TypeScript SDK is centered on `sandbox-agent` and its `SandboxAgent` class.
## Install
<Tabs>
<Tab title="npm">
```bash
npm install sandbox-agent@0.3.x
```
</Tab>
<Tab title="bun">
```bash
bun add sandbox-agent@0.3.x
# Allow Bun to run postinstall scripts for native binaries (required for SandboxAgent.start()).
bun pm trust @sandbox-agent/cli-linux-x64 @sandbox-agent/cli-linux-arm64 @sandbox-agent/cli-darwin-arm64 @sandbox-agent/cli-darwin-x64 @sandbox-agent/cli-win32-x64
```
</Tab>
</Tabs>
## Optional React components
```bash
npm install @sandbox-agent/react@0.3.x
```
## Create a client
```ts
import { SandboxAgent } from "sandbox-agent";
const sdk = await SandboxAgent.connect({
baseUrl: "http://127.0.0.1:2468",
});
```
`SandboxAgent.connect(...)` now waits for `/v1/health` by default before other SDK requests proceed. To disable that gate, pass `waitForHealth: false`. To keep the default gate but fail after a bounded wait, pass `waitForHealth: { timeoutMs: 120_000 }`. To cancel the startup wait early, pass `signal: abortController.signal`.
With a custom fetch handler (for example, proxying requests inside Workers):
```ts
const sdk = await SandboxAgent.connect({
fetch: (input, init) => customFetch(input, init),
});
```
With an abort signal for the startup health gate:
```ts
const controller = new AbortController();
const sdk = await SandboxAgent.connect({
baseUrl: "http://127.0.0.1:2468",
signal: controller.signal,
});
controller.abort();
```
With persistence (see [Persisting Sessions](/session-persistence) for driver options):
```ts
import { SandboxAgent, InMemorySessionPersistDriver } from "sandbox-agent";
const persist = new InMemorySessionPersistDriver();
const sdk = await SandboxAgent.connect({
baseUrl: "http://127.0.0.1:2468",
persist,
});
```
Local spawn with a sandbox provider:
```ts
import { SandboxAgent } from "sandbox-agent";
import { local } from "sandbox-agent/local";
const sdk = await SandboxAgent.start({
sandbox: local(),
});
// sdk.sandboxId — prefixed provider ID (e.g. "local/127.0.0.1:2468")
await sdk.destroySandbox(); // tears down sandbox + disposes client
```
`SandboxAgent.start(...)` requires a `sandbox` provider. Built-in providers:
| Import | Provider |
|--------|----------|
| `sandbox-agent/local` | Local subprocess |
| `sandbox-agent/docker` | Docker container |
| `sandbox-agent/e2b` | E2B sandbox |
| `sandbox-agent/daytona` | Daytona workspace |
| `sandbox-agent/vercel` | Vercel Sandbox |
| `sandbox-agent/cloudflare` | Cloudflare Sandbox |
Use `sdk.dispose()` to disconnect without destroying the sandbox, or `sdk.destroySandbox()` to tear down both.
## Session flow
```ts
const session = await sdk.createSession({
agent: "mock",
cwd: "/",
});
const prompt = await session.prompt([
{ type: "text", text: "Summarize this repository." },
]);
console.log(prompt.stopReason);
```
Load and destroy:
```ts
const restored = await sdk.resumeSession(session.id);
await restored.prompt([{ type: "text", text: "Continue from previous context." }]);
await sdk.destroySession(restored.id);
```
## Session configuration
Set model, mode, or thought level at creation or on an existing session:
```ts
const session = await sdk.createSession({
agent: "codex",
model: "gpt-5.3-codex",
});
await session.setModel("gpt-5.2-codex");
await session.setMode("auto");
const options = await session.getConfigOptions();
const modes = await session.getModes();
```
Handle permission requests from agents that ask before executing tools:
```ts
const claude = await sdk.createSession({
agent: "claude",
mode: "default",
});
claude.onPermissionRequest((request) => {
void claude.respondPermission(request.id, "once");
});
```
See [Agent Sessions](/agent-sessions) for full details on config options and error handling.
## Events
Subscribe to live events:
```ts
const unsubscribe = session.onEvent((event) => {
console.log(event.eventIndex, event.sender, event.payload);
});
await session.prompt([{ type: "text", text: "Give me a short summary." }]);
unsubscribe();
```
Fetch persisted events:
```ts
const page = await sdk.getEvents({
sessionId: session.id,
limit: 100,
});
console.log(page.items.length);
```
## Control-plane and HTTP helpers
```ts
const health = await sdk.getHealth();
const agents = await sdk.listAgents();
await sdk.installAgent("codex", { reinstall: true });
const entries = await sdk.listFsEntries({ path: "." });
const writeResult = await sdk.writeFsFile({ path: "./hello.txt" }, "hello");
console.log(health.status, agents.agents.length, entries.length, writeResult.path);
```
## Error handling
```ts
import { SandboxAgentError } from "sandbox-agent";
try {
await sdk.listAgents();
} catch (error) {
if (error instanceof SandboxAgentError) {
console.error(error.status, error.problem);
}
}
```
## Inspector URL
```ts
import { buildInspectorUrl } from "sandbox-agent";
const url = buildInspectorUrl({
baseUrl: "https://your-sandbox-agent.example.com",
headers: { "X-Custom-Header": "value" },
});
console.log(url);
```
Parameters:
- `baseUrl` (required unless `fetch` is provided): Sandbox Agent server URL
- `token` (optional): Bearer token for authenticated servers
- `headers` (optional): Additional request headers
- `fetch` (optional): Custom fetch implementation used by SDK HTTP and session calls
- `skipHealthCheck` (optional): set `true` to skip the startup `/v1/health` wait
- `waitForHealth` (optional, defaults to enabled): waits for `/v1/health` before HTTP helpers and session setup proceed; pass `false` to disable or `{ timeoutMs }` to bound the wait
- `signal` (optional): aborts the startup `/v1/health` wait used by `connect()`
## LLM credentials
Sandbox Agent supports personal API keys, shared organization keys, and per-tenant gateway keys with budget enforcement. See [LLM Credentials](/llm-credentials) for setup details.