sandbox-agent/docs/sdk-overview.mdx
Nathan Flurry febe8601f6
feat: add process management support (#207)
* feat: improve inspector UI for processes and fix PTY terminal

- Simplify ProcessRunTab layout: compact form with collapsible Advanced section for timeout/maxOutputBytes
- Rewrite ProcessesTab: collapsible create form, lightweight list items with status dots, clean detail panel with tabs
- Extract error details: use problem.detail instead of generic "Stream Error" title for better error messages
- Fix GhosttyTerminal binary frame parsing: handle server's binary ArrayBuffer control frames (ready/exit/error)
- Enable WebSocket proxying in Vite dev server with ws: true
- Set TERM=xterm-256color default for TTY processes so tools like tmux, vim, htop work out of the box
- Remove orange gradient background from terminal container for cleaner look
- Remove orange left border from selected process list items
- Update inspector CSS with new process/terminal styles

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

* fix: address review issues and add processes documentation

- Fix unstable onExit callback in ProcessesTab (useCallback)
- Fix SSE follow stream race condition (subscribe before history read)
- Update inspector.mdx with new process management features
- Change observability icon to avoid conflict with processes
- Add docs/processes.mdx covering the full process management API

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

* docs: simplify processes doc — rename sections, remove low-level protocol

- Rename "Interactive terminals" to "Terminals" with "Connect to a terminal" sub-heading
- Add TTY process creation step at top of Terminals section
- Remove low-level WebSocket protocol table and raw WebSocket example
- Keep browser terminal emulator reference with Ghostty link

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

* docs: update GhosttyTerminal permalink to latest commit

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

* docs: use main branch permalink for GhosttyTerminal reference

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

* feat: refine process API — WebSocket binary protocol, SDK terminal session, updated tests

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

* docs: update GhosttyTerminal permalink to 636eefb

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

* inspector: use websocket terminal API

* sdk: restore high-level terminal session

* docs: update inspector terminal permalink

* inspector: update run once placeholder

* Fix lazy install v1 API test fixture

* Add reusable React terminal component

* Fix terminal WebSocket ready state checks

---------

Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com>
2026-03-07 17:58:31 -08:00

214 lines
5 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.2.x
```
</Tab>
<Tab title="bun">
```bash
bun add sandbox-agent@0.2.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 persistence drivers
```bash
npm install @sandbox-agent/persist-indexeddb@0.2.x @sandbox-agent/persist-sqlite@0.2.x @sandbox-agent/persist-postgres@0.2.x
```
## Optional React components
```bash
npm install @sandbox-agent/react@0.2.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:
```ts
import { SandboxAgent } from "sandbox-agent";
import { SQLiteSessionPersistDriver } from "@sandbox-agent/persist-sqlite";
const persist = new SQLiteSessionPersistDriver({
filename: "./sessions.db",
});
const sdk = await SandboxAgent.connect({
baseUrl: "http://127.0.0.1:2468",
persist,
});
```
Local autospawn (Node.js only):
```ts
import { SandboxAgent } from "sandbox-agent";
const localSdk = await SandboxAgent.start();
await localSdk.dispose();
```
## Session flow
```ts
const session = await sdk.createSession({
agent: "mock",
sessionInit: {
cwd: "/",
mcpServers: [],
},
});
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();
```
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 ACP calls
- `waitForHealth` (optional, defaults to enabled): waits for `/v1/health` before HTTP helpers and ACP session setup proceed; pass `false` to disable or `{ timeoutMs }` to bound the wait
- `signal` (optional): aborts the startup `/v1/health` wait used by `connect()`