diff --git a/.github/media/inspector.png b/.github/media/inspector.png new file mode 100644 index 0000000..1c16ed2 Binary files /dev/null and b/.github/media/inspector.png differ diff --git a/CLAUDE.md b/CLAUDE.md index 6cf9786..5d4edcd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,6 +30,7 @@ Universal schema guidance: - Keep CLI subcommands in sync with every HTTP endpoint. - Update `CLAUDE.md` to keep CLI endpoints in sync with HTTP API changes. +- When adding or modifying CLI commands, update `docs/cli.mdx` to reflect the changes. - When changing the HTTP API, update the TypeScript SDK and CLI together. - Do not make breaking changes to API endpoints. - When changing API routes, ensure the HTTP/SSE test suite has full coverage of every route. @@ -39,10 +40,10 @@ Universal schema guidance: - Never use synthetic data or mocked responses in tests. - Never manually write agent types; always use generated types in `resources/agent-schemas/`. If types are broken, fix the generated types. - The universal schema must provide consistent behavior across providers; avoid requiring frontend/client logic to special-case agents. -- The UI must reflect every field in AgentCapabilities; keep it in sync with the README feature matrix and `agent_capabilities_for`. +- The UI must reflect every field in AgentCapabilities; keep it in sync with the README feature matrix, `docs/agent-compatibility.mdx`, and `agent_capabilities_for`. - When parsing agent data, if something is unexpected or does not match the schema, bail out and surface the error rather than trying to continue with partial parsing. - When defining the universal schema, choose the option most compatible with native agent APIs, and add synthetics to fill gaps for other agents. -- Use `docs/glossary.md` as the source of truth for universal schema terminology and keep it updated alongside schema changes. +- Use `docs/universal-schema.mdx` as the source of truth for universal schema terminology and keep it updated alongside schema changes. - On parse failures, emit an `agent.unparsed` event (source=daemon, synthetic=true) and treat it as a test failure. Preserve raw payloads when `include_raw=true`. - Track subagent support in `docs/conversion.md`. For now, normalize subagent activity into normal message/tool flow, but revisit explicit subagent modeling later. - Keep the FAQ in `README.md` and `frontend/packages/website/src/components/FAQ.tsx` in sync. When adding or modifying FAQ entries, update both files. @@ -56,6 +57,7 @@ Universal schema guidance: - `sandbox-agent api sessions create` ↔ `POST /v1/sessions/{sessionId}` - `sandbox-agent api sessions send-message` ↔ `POST /v1/sessions/{sessionId}/messages` - `sandbox-agent api sessions send-message-stream` ↔ `POST /v1/sessions/{sessionId}/messages/stream` +- `sandbox-agent api sessions terminate` ↔ `POST /v1/sessions/{sessionId}/terminate` - `sandbox-agent api sessions events` / `get-messages` ↔ `GET /v1/sessions/{sessionId}/events` - `sandbox-agent api sessions events-sse` ↔ `GET /v1/sessions/{sessionId}/events/sse` - `sandbox-agent api sessions reply-question` ↔ `POST /v1/sessions/{sessionId}/questions/{questionId}/reply` diff --git a/README.md b/README.md index 24ca32b..9ed0393 100644 --- a/README.md +++ b/README.md @@ -9,11 +9,11 @@ - **Any coding agent**: Universal API to interact with all agents with full feature coverage - **Server or SDK mode**: Run as an HTTP server or with the TypeScript SDK -- **Universal session schema**: Universal schema to store agent transcripts +- **Universal session schema**: [Universal schema](https://sandboxagent.dev/docs/universal-schema) to store agent transcripts - **Supports your sandbox provider**: Daytona, E2B, Vercel Sandboxes, and more - **Lightweight, portable Rust binary**: Install anywhere with 1 curl command - **Automatic agent installation**: Agents are installed on-demand when first used -- **OpenAPI spec**: https://sandboxagent.dev/docs/api +- **OpenAPI spec**: Well documented and easy to integrate [Documentation](https://sandboxagent.dev/docs) — [Discord](https://rivet.dev/discord) @@ -37,7 +37,7 @@ | MCP Tools | | ✓ | | | | Streaming Deltas | | ✓ | ✓ | | -* Claude headless CLI does not natively support tool calls/results or HITL questions/permissions yet; these are WIP. +\* Coming imminently Want support for another agent? [Open an issue](https://github.com/anthropics/sandbox-agent/issues/new) to request it. @@ -116,7 +116,7 @@ for await (const event of client.streamEvents("demo", { offset: 0 })) { } ``` -[Documentation](https://sandboxagent.dev/docs/sdks/typescript) +[Documentation](https://sandboxagent.dev/docs/sdks/typescript) — [Building a Chat UI](https://sandboxagent.dev/docs/building-chat-ui) — [Managing Sessions](https://sandboxagent.dev/docs/manage-sessions) ### Server @@ -144,8 +144,7 @@ To disable auth locally: sandbox-agent server --no-token --host 127.0.0.1 --port 2468 ``` -[Documentation](https://sandboxagent.dev/docs/quickstart) -[Integration guides](https://sandboxagent.dev/docs/deployments) +[Documentation](https://sandboxagent.dev/docs/quickstart) - [Integration guides](https://sandboxagent.dev/docs/deploy) ### CLI @@ -169,7 +168,23 @@ You can also use npx like: npx sandbox-agent --help ``` -[Documentation](https://rivet.dev/docs/cli) +[Documentation](https://sandboxagent.dev/docs/cli) + +### Inspector + +Debug sessions and events with the [Inspector UI](https://inspect.sandboxagent.dev). + +![Sandbox Agent Inspector](./.github/media/inspector.png) + +[Documentation](https://sandboxagent.dev/docs/inspector) + +### OpenAPI Specification + +[Explore API](https://sandboxagent.dev/docs/api-reference) — [View Specification](https://github.com/rivet-dev/sandbox-agent/blob/main/docs/openapi.json) + +### Universal Schema + +All events follow a [universal schema](https://sandboxagent.dev/docs/universal-schema) that normalizes differences between agents. ### Tip: Extract credentials @@ -183,33 +198,47 @@ This prints environment variables for your OpenAI/Anthropic/etc API keys to test ## FAQ -**Does this replace the Vercel AI SDK?** +
+Does this replace the Vercel AI SDK? No, they're complementary. AI SDK is for building chat interfaces and calling LLMs. This SDK is for controlling autonomous coding agents that write code and run commands. Use AI SDK for your UI, use this when you need an agent to actually code. +
-**Which coding agents are supported?** +
+Which coding agents are supported? Claude Code, Codex, OpenCode, and Amp. The SDK normalizes their APIs so you can swap between them without changing your code. +
-**How is session data persisted?** +
+How is session data persisted? -This SDK does not handle persisting session data. Events stream in a universal JSON schema that you can persist anywhere. Consider using Postgres or [Rivet Actors](https://rivet.gg) for data persistence. +This SDK does not handle persisting session data. Events stream in a universal JSON schema that you can persist anywhere. See [Managing Sessions](https://sandboxagent.dev/docs/manage-sessions) for patterns using Postgres or [Rivet Actors](https://rivet.gg). +
-**Can I run this locally or does it require a sandbox provider?** +
+Can I run this locally or does it require a sandbox provider? Both. Run locally for development, deploy to E2B, Daytona, or Vercel Sandboxes for production. +
-**Does it support [platform]?** +
+Does it support [platform]? The server is a single Rust binary that runs anywhere with a curl install. If your platform can run Linux binaries (Docker, VMs, etc.), it works. See the deployment guides for E2B, Daytona, and Vercel Sandboxes. +
-**Can I use this with my personal API keys?** +
+Can I use this with my personal API keys? Yes. Use `sandbox-agent credentials extract-env` to extract API keys from your local agent configs (Claude Code, Codex, OpenCode, Amp) and pass them to the sandbox environment. +
-**Why Rust and not [language]?** +
+Why Rust and not [language]? Rust gives us a single static binary, fast startup, and predictable memory usage. That makes it easy to run inside sandboxes or in CI without shipping a large runtime, such as Node.js. +
## Project Goals diff --git a/docs/agent-compatibility.mdx b/docs/agent-compatibility.mdx index 2c87c07..3f38bd8 100644 --- a/docs/agent-compatibility.mdx +++ b/docs/agent-compatibility.mdx @@ -1,28 +1,96 @@ --- title: "Agent Compatibility" -description: "Supported agents, install methods, and streaming formats." +description: "Feature support across coding agents." +icon: "table" --- -## Compatibility matrix +The universal API normalizes different coding agents into a consistent interface. Each agent has different native capabilities; the daemon fills gaps with synthetic events where possible. -| Agent | Provider | Binary | Install method | Session ID | Streaming format | -|-------|----------|--------|----------------|------------|------------------| -| Claude Code | Anthropic | `claude` | curl raw binary from GCS | `session_id` | JSONL via stdout | -| Codex | OpenAI | `codex` | curl tarball from GitHub releases | `thread_id` | JSON-RPC over stdio | -| OpenCode | Multi-provider | `opencode` | curl tarball from GitHub releases | `session_id` | SSE or JSONL | -| Amp | Sourcegraph | `amp` | curl raw binary from GCS | `session_id` | JSONL via stdout | -| Mock | Built-in | — | bundled | `mock-*` | daemon-generated | +## Feature Matrix -## Agent modes +| Feature | [Claude Code](https://docs.anthropic.com/en/docs/agents-and-tools/claude-code/overview)* | [Codex](https://github.com/openai/codex) | [OpenCode](https://github.com/opencode-ai/opencode) | [Amp](https://ampcode.com) | +|---------|:-----------:|:-----:|:--------:|:---:| +| Stability | Stable | Stable | Experimental | Experimental | +| Text Messages | ✓ | ✓ | ✓ | ✓ | +| Tool Calls | —* | ✓ | ✓ | ✓ | +| Tool Results | —* | ✓ | ✓ | ✓ | +| Questions (HITL) | —* | | ✓ | | +| Permissions (HITL) | —* | | ✓ | | +| Images | | ✓ | ✓ | | +| File Attachments | | ✓ | ✓ | | +| Session Lifecycle | | ✓ | ✓ | | +| Error Events | | ✓ | ✓ | ✓ | +| Reasoning/Thinking | | ✓ | | | +| Command Execution | | ✓ | | | +| File Changes | | ✓ | | | +| MCP Tools | | ✓ | | | +| Streaming Deltas | | ✓ | ✓ | | -- **OpenCode**: discovered via the server API. -- **Claude Code / Codex / Amp**: hardcoded modes (typically `build`, `plan`, or `custom`). +\* Coming imminently -## Capability notes +## Feature Descriptions -- **Questions / permissions**: OpenCode natively supports these workflows. Claude plan approval is normalized into a question event (tests do not currently exercise Claude question/permission flows). -- **Streaming**: all agents stream events; OpenCode uses SSE, Codex uses JSON-RPC over stdio, others use JSONL. Codex is currently normalized to thread/turn starts plus user/assistant completed items (deltas and tool/reasoning items are not emitted yet). -- **User messages**: Claude CLI output does not include explicit user-message events in our snapshots, so only assistant messages are surfaced for Claude today. -- **Files and images**: normalized via `UniversalMessagePart` with `File` and `Image` parts. +### Text Messages -See [Universal API](/universal-api) for feature coverage details. +Basic message exchange between user and assistant. + +### Tool Calls & Results + +Visibility into tool invocations (file reads, command execution, etc.) and their results. When not natively supported, tool activity is embedded in message content. + +### Questions (HITL) + +Interactive questions the agent asks the user. Emits `question.requested` and `question.resolved` events. + +### Permissions (HITL) + +Permission requests for sensitive operations. Emits `permission.requested` and `permission.resolved` events. + +### Images + +Support for image attachments in messages. + +### File Attachments + +Support for file attachments in messages. + +### Session Lifecycle + +Native `session.started` and `session.ended` events. When not supported, the daemon emits synthetic lifecycle events. + +### Error Events + +Structured error events for runtime failures. + +### Reasoning/Thinking + +Extended thinking or reasoning content with visibility controls. + +### Command Execution + +Detailed command execution events with stdout/stderr. + +### File Changes + +Structured file modification events with diffs. + +### MCP Tools + +Model Context Protocol tool support. + +### Streaming Deltas + +Native streaming of content deltas. When not supported, the daemon emits a single synthetic delta before `item.completed`. + +## Synthetic Events + +For features not natively supported, the daemon generates synthetic events to maintain a consistent event stream. Synthetic events have: + +- `source: "daemon"` +- `synthetic: true` + +This lets you build UIs that work with any agent without special-casing each provider. + +## Request Support + +Want support for another agent? [Open an issue](https://github.com/rivet-dev/sandbox-agent/issues/new) to request it. diff --git a/docs/building-chat-ui.mdx b/docs/building-chat-ui.mdx index 240b8a4..0f3b559 100644 --- a/docs/building-chat-ui.mdx +++ b/docs/building-chat-ui.mdx @@ -1,57 +1,76 @@ --- title: "Building a Chat UI" -description: "Design a client that renders universal session events consistently across providers." +description: "Build a chat interface using the universal event stream." +icon: "comments" --- -This guide explains how to build a chat UI that works across all agents using the universal event -stream. +## Setup -## High-level flow +### List agents -1. List agents and read their capabilities. -2. Create a session for the selected agent. -3. Send user messages. -4. Subscribe to events (polling or SSE). -5. Render items and deltas into a stable message timeline. +```ts +const { agents } = await client.listAgents(); -## Use agent capabilities +// Each agent has capabilities that determine what UI to show +const claude = agents.find((a) => a.id === "claude"); +if (claude?.capabilities.permissions) { + // Show permission approval UI +} +if (claude?.capabilities.questions) { + // Show question response UI +} +``` -Capabilities tell you which features are supported for the selected agent: +### Create a session -- `tool_calls` and `tool_results` indicate tool execution events. -- `questions` and `permissions` indicate HITL flows. -- `plan_mode` indicates that the agent supports plan-only execution. -- `reasoning` and `status` indicate that the agent can emit reasoning/status content parts. -- `item_started` indicates that the agent emits `item.started` on its own; when false the daemon will emit a synthetic `item.started` immediately after sending a user message. +```ts +const sessionId = `session-${crypto.randomUUID()}`; -Use these to enable or disable UI affordances (tool panels, approval buttons, etc.). +await client.createSession(sessionId, { + agent: "claude", + agentMode: "code", // Optional: agent-specific mode + permissionMode: "default", // Optional: "default" | "plan" | "bypass" + model: "claude-sonnet-4", // Optional: model override +}); +``` -## Event model +### Send a message -Every event includes: +```ts +await client.postMessage(sessionId, { message: "Hello, world!" }); +``` -- `event_id`, `sequence`, and `time` for ordering. -- `session_id` for the universal session. -- `native_session_id` for provider-specific debugging. -- `type` with one of: - - `session.started`, `session.ended` - - `item.started`, `item.delta`, `item.completed` - - `permission.requested`, `permission.resolved` - - `question.requested`, `question.resolved` - - `error`, `agent.unparsed` -- `data` which holds the payload for the event type. -- `synthetic` and `source` to show daemon-generated events. -- `raw` (optional) when `include_raw=true`. +### Stream events -## Rendering items +Three options for receiving events: -Items are emitted in three phases: +```ts +// Option 1: SSE (recommended for real-time UI) +const stream = client.streamEvents(sessionId, { offset: 0 }); +for await (const event of stream) { + handleEvent(event); +} -- `item.started`: first snapshot of a message or tool item. -- `item.delta`: incremental updates (token streaming or synthetic deltas). -- `item.completed`: final snapshot. +// Option 2: Polling +const { events, hasMore } = await client.getEvents(sessionId, { offset: 0 }); +events.forEach(handleEvent); -Recommended render flow: +// Option 3: Turn streaming (send + stream in one call) +const stream = client.streamTurn(sessionId, { message: "Hello" }); +for await (const event of stream) { + handleEvent(event); +} +``` + +Use `offset` to track the last seen `sequence` number and resume from where you left off. + +--- + +## Handling Events + +### Bare minimum + +Handle these three events to render a basic chat: ```ts type ItemState = { @@ -60,108 +79,278 @@ type ItemState = { }; const items = new Map(); -const order: string[] = []; -function applyEvent(event: UniversalEvent) { - if (event.type === "item.started") { - const item = event.data.item; - items.set(item.item_id, { item, deltas: [] }); - order.push(item.item_id); - } - - if (event.type === "item.delta") { - const { item_id, delta } = event.data; - const state = items.get(item_id); - if (state) { - state.deltas.push(delta); +function handleEvent(event: UniversalEvent) { + switch (event.type) { + case "item.started": { + const { item } = event.data as ItemEventData; + items.set(item.item_id, { item, deltas: [] }); + break; } - } - if (event.type === "item.completed") { - const item = event.data.item; - const state = items.get(item.item_id); - if (state) { - state.item = item; + case "item.delta": { + const { item_id, delta } = event.data as ItemDeltaData; + const state = items.get(item_id); + if (state) { + state.deltas.push(delta); + } + break; + } + + case "item.completed": { + const { item } = event.data as ItemEventData; + const state = items.get(item.item_id); + if (state) { + state.item = item; + state.deltas = []; // Clear deltas, use final content + } + break; } } } ``` -When rendering, combine the item content with accumulated deltas. If you receive a delta before a -started event (should not happen), treat it as an error. +When rendering, show a loading indicator while `item.status === "in_progress"`: -## Content parts +```ts +function renderItem(state: ItemState) { + const { item, deltas } = state; + const isLoading = item.status === "in_progress"; -Each `UniversalItem` has `content` parts. Your UI can branch on `part.type`: + // For streaming text, combine item content with accumulated deltas + const text = item.content + .filter((p) => p.type === "text") + .map((p) => p.text) + .join(""); + const streamedText = text + deltas.join(""); -- `text` for normal chat text. -- `tool_call` and `tool_result` for tool execution. -- `file_ref` for file read/write/patch previews. -- `reasoning` if you display public reasoning text. -- `status` for progress updates. -- `image` for image outputs. - -Treat `item.kind` as the primary layout decision (message vs tool call vs system), and use content -parts for the detailed rendering. - -## Questions and permissions - -Question and permission events are out-of-band from item flow. Render them as modal or inline UI -blocks that must be resolved via: - -- `POST /v1/sessions/{session_id}/questions/{question_id}/reply` -- `POST /v1/sessions/{session_id}/questions/{question_id}/reject` -- `POST /v1/sessions/{session_id}/permissions/{permission_id}/reply` - -If an agent does not advertise these capabilities, keep those UI controls hidden. - -## Error and unparsed events - -- `error` events are structured failures from the daemon or agent. -- `agent.unparsed` indicates the provider emitted something the converter could not parse. - -Treat `agent.unparsed` as a hard failure in development so you can fix converters quickly. - -## Event ordering - -Prefer `sequence` for ordering. It is monotonic for a given session. The `time` field is for -timestamps, not ordering. - -## Handling session end - -`session.ended` includes the reason and who terminated it. Disable input after a terminal event. - -## Optional raw payloads - -If you need provider-level debugging, pass `include_raw=true` when streaming or polling events -(including one-turn streams) to receive the `raw` payload for each event. - -## SSE vs polling vs turn streaming - -- SSE gives low-latency updates and simplifies streaming UIs. -- Polling is simpler to debug and works in any environment. -- Turn streaming (`POST /v1/sessions/{session_id}/messages/stream`) is a one-shot stream tied to a - single prompt. The stream closes automatically once the turn completes. - -Both yield the same event payloads. - -## Mock agent for UI testing - -Use the built-in `mock` agent to exercise UI behaviors without external credentials: - -```bash -curl -X POST http://127.0.0.1:2468/v1/sessions/demo-session \ - -H "content-type: application/json" \ - -d '{"agent":"mock"}' + return { + content: streamedText, + isLoading, + role: item.role, + kind: item.kind, + }; +} ``` -The mock agent sends a prompt telling you what commands it accepts. Send messages like `demo`, -`markdown`, or `permission` to emit specific event sequences. Any other text is echoed back as an -assistant message so you can test rendering, streaming, and approval flows on demand. +### Extra events -## Reference implementation +Handle these for a complete implementation: -The [Inspector chat UI](https://github.com/rivet-dev/sandbox-agent/blob/main/frontend/packages/inspector/src/App.tsx) -is a complete reference implementation showing how to build a chat interface using the universal event -stream. It demonstrates session management, event rendering, item lifecycle handling, and HITL approval -flows. +```ts +function handleEvent(event: UniversalEvent) { + switch (event.type) { + // ... bare minimum events above ... + + case "session.started": { + // Session is ready + break; + } + + case "session.ended": { + const { reason, terminated_by } = event.data as SessionEndedData; + // Disable input, show end reason + // reason: "completed" | "error" | "terminated" + // terminated_by: "agent" | "daemon" + break; + } + + case "error": { + const { message, code } = event.data as ErrorData; + // Display error to user + break; + } + + case "agent.unparsed": { + const { error, location } = event.data as AgentUnparsedData; + // Parsing failure - treat as bug in development + console.error(`Parse error at ${location}: ${error}`); + break; + } + } +} +``` + +### Content parts + +Each item has `content` parts. Render based on `type`: + +```ts +function renderContentPart(part: ContentPart) { + switch (part.type) { + case "text": + return {part.text}; + + case "tool_call": + return ; + + case "tool_result": + return ; + + case "file_ref": + return ; + + case "reasoning": + return {part.text}; + + case "status": + return ; + + case "image": + return ; + } +} +``` + +--- + +## Handling Permissions + +When `permission.requested` arrives, show an approval UI: + +```ts +const pendingPermissions = new Map(); + +function handleEvent(event: UniversalEvent) { + if (event.type === "permission.requested") { + const data = event.data as PermissionEventData; + pendingPermissions.set(data.permission_id, data); + } + + if (event.type === "permission.resolved") { + const data = event.data as PermissionEventData; + pendingPermissions.delete(data.permission_id); + } +} + +// User clicks approve/deny +async function replyPermission(id: string, reply: "once" | "always" | "reject") { + await client.replyPermission(sessionId, id, { reply }); + pendingPermissions.delete(id); +} +``` + +Render permission requests: + +```ts +function PermissionRequest({ data }: { data: PermissionEventData }) { + return ( +
+

Allow: {data.action}

+ + + +
+ ); +} +``` + +--- + +## Handling Questions + +When `question.requested` arrives, show a selection UI: + +```ts +const pendingQuestions = new Map(); + +function handleEvent(event: UniversalEvent) { + if (event.type === "question.requested") { + const data = event.data as QuestionEventData; + pendingQuestions.set(data.question_id, data); + } + + if (event.type === "question.resolved") { + const data = event.data as QuestionEventData; + pendingQuestions.delete(data.question_id); + } +} + +// User selects answer(s) +async function answerQuestion(id: string, answers: string[][]) { + await client.replyQuestion(sessionId, id, { answers }); + pendingQuestions.delete(id); +} + +async function rejectQuestion(id: string) { + await client.rejectQuestion(sessionId, id); + pendingQuestions.delete(id); +} +``` + +Render question requests: + +```ts +function QuestionRequest({ data }: { data: QuestionEventData }) { + const [selected, setSelected] = useState([]); + + return ( +
+

{data.prompt}

+ {data.options.map((option) => ( + + ))} + + +
+ ); +} +``` + +--- + +## Testing with Mock Agent + +The `mock` agent lets you test UI behaviors without external credentials: + +```ts +await client.createSession("test-session", { agent: "mock" }); +``` + +Send `help` to see available commands: + +| Command | Tests | +|---------|-------| +| `help` | Lists all commands | +| `demo` | Full UI coverage sequence with markers | +| `markdown` | Streaming markdown rendering | +| `tool` | Tool call + result with file refs | +| `status` | Status item updates | +| `image` | Image content part | +| `permission` | Permission request flow | +| `question` | Question request flow | +| `error` | Error + unparsed events | +| `end` | Session ended event | +| `echo ` | Echo text as assistant message | + +Any unrecognized text is echoed back as an assistant message. + +--- + +## Reference Implementation + +The [Inspector UI](https://github.com/rivet-dev/sandbox-agent/blob/main/frontend/packages/inspector/src/App.tsx) +is a complete reference showing session management, event rendering, and HITL flows. diff --git a/docs/cli.mdx b/docs/cli.mdx index 16cea87..39508c4 100644 --- a/docs/cli.mdx +++ b/docs/cli.mdx @@ -1,140 +1,310 @@ --- -title: "CLI" -description: "CLI reference and server flags." +title: "CLI Reference" +description: "Complete CLI reference for sandbox-agent." +sidebarTitle: "CLI" +icon: "terminal" --- -The `sandbox-agent api` subcommand mirrors the HTTP API so you can script everything without writing client code. +## Server -## Server flags +Start the HTTP server: ```bash -sandbox-agent server --token "$SANDBOX_TOKEN" --host 127.0.0.1 --port 2468 +sandbox-agent server [OPTIONS] ``` -- `--token`: global token for all requests. -- `--no-token`: disable auth (local dev only). -- `--host`, `--port`: bind address. -- `--cors-allow-origin`, `--cors-allow-method`, `--cors-allow-header`, `--cors-allow-credentials`: configure CORS. -- `--no-telemetry`: disable anonymous telemetry. +| Option | Default | Description | +|--------|---------|-------------| +| `-t, --token ` | - | Authentication token for all requests | +| `-n, --no-token` | - | Disable authentication (local dev only) | +| `-H, --host ` | `127.0.0.1` | Host to bind to | +| `-p, --port ` | `2468` | Port to bind to | +| `-O, --cors-allow-origin ` | - | CORS allowed origin (repeatable) | +| `-M, --cors-allow-method ` | - | CORS allowed method (repeatable) | +| `-A, --cors-allow-header
` | - | CORS allowed header (repeatable) | +| `-C, --cors-allow-credentials` | - | Enable CORS credentials | +| `--no-telemetry` | - | Disable anonymous telemetry | -## Install agent (no server required) +```bash +sandbox-agent server --token "$TOKEN" --port 3000 +``` -
-install-agent +--- + +## Install Agent (Local) + +Install an agent without running the server: + +```bash +sandbox-agent install-agent [OPTIONS] +``` + +| Option | Description | +|--------|-------------| +| `-r, --reinstall` | Force reinstall even if already installed | ```bash sandbox-agent install-agent claude --reinstall ``` -
-## API agent commands +--- -
-api agents list +## Credentials + +### Extract + +Extract locally discovered credentials: ```bash -sandbox-agent api agents list --endpoint http://127.0.0.1:2468 +sandbox-agent credentials extract [OPTIONS] ``` -
-
-api agents install +| Option | Description | +|--------|-------------| +| `-a, --agent ` | Filter by agent (`claude`, `codex`, `opencode`, `amp`) | +| `-p, --provider ` | Filter by provider (`anthropic`, `openai`) | +| `-d, --home-dir ` | Custom home directory for credential search | +| `-r, --reveal` | Show full credential values (default: redacted) | +| `--no-oauth` | Exclude OAuth credentials | ```bash -sandbox-agent api agents install claude --reinstall --endpoint http://127.0.0.1:2468 +sandbox-agent credentials extract --agent claude --reveal +sandbox-agent credentials extract --provider anthropic ``` -
-
-api agents modes +### Extract as Environment Variables + +Output credentials as shell environment variables: ```bash -sandbox-agent api agents modes claude --endpoint http://127.0.0.1:2468 +sandbox-agent credentials extract-env [OPTIONS] ``` -
-## API session commands - -
-api sessions list +| Option | Description | +|--------|-------------| +| `-e, --export` | Prefix each line with `export` | +| `-d, --home-dir ` | Custom home directory for credential search | +| `--no-oauth` | Exclude OAuth credentials | ```bash -sandbox-agent api sessions list --endpoint http://127.0.0.1:2468 +# Source directly into shell +eval "$(sandbox-agent credentials extract-env --export)" ``` -
-
-api sessions create +--- + +## API Commands + +The `sandbox-agent api` subcommand mirrors the HTTP API for scripting without client code. + +All API commands support: + +| Option | Default | Description | +|--------|---------|-------------| +| `-e, --endpoint ` | `http://127.0.0.1:2468` | API endpoint | +| `-t, --token ` | - | Authentication token | + +--- + +### Agents + +#### List Agents + +```bash +sandbox-agent api agents list +``` + +#### Install Agent + +```bash +sandbox-agent api agents install [OPTIONS] +``` + +| Option | Description | +|--------|-------------| +| `-r, --reinstall` | Force reinstall | + +```bash +sandbox-agent api agents install claude --reinstall +``` + +#### Get Agent Modes + +```bash +sandbox-agent api agents modes +``` + +```bash +sandbox-agent api agents modes claude +``` + +--- + +### Sessions + +#### List Sessions + +```bash +sandbox-agent api sessions list +``` + +#### Create Session + +```bash +sandbox-agent api sessions create [OPTIONS] +``` + +| Option | Description | +|--------|-------------| +| `-a, --agent ` | Agent identifier (required) | +| `-g, --agent-mode ` | Agent mode | +| `-p, --permission-mode ` | Permission mode (`default`, `plan`, `bypass`) | +| `-m, --model ` | Model override | +| `-v, --variant ` | Model variant | +| `-A, --agent-version ` | Agent version | ```bash sandbox-agent api sessions create my-session \ --agent claude \ - --agent-mode build \ - --permission-mode default \ - --endpoint http://127.0.0.1:2468 + --agent-mode code \ + --permission-mode default ``` -
-
-api sessions send-message +#### Send Message + +```bash +sandbox-agent api sessions send-message [OPTIONS] +``` + +| Option | Description | +|--------|-------------| +| `-m, --message ` | Message text (required) | ```bash sandbox-agent api sessions send-message my-session \ - --message "Summarize the repository" \ - --endpoint http://127.0.0.1:2468 + --message "Summarize the repository" ``` -
-
-api sessions send-message-stream +#### Send Message (Streaming) + +Send a message and stream the response: + +```bash +sandbox-agent api sessions send-message-stream [OPTIONS] +``` + +| Option | Description | +|--------|-------------| +| `-m, --message ` | Message text (required) | +| `--include-raw` | Include raw agent data | ```bash sandbox-agent api sessions send-message-stream my-session \ - --message "Summarize the repository" \ - --endpoint http://127.0.0.1:2468 + --message "Help me debug this" ``` -
-
-api sessions events +#### Terminate Session ```bash -sandbox-agent api sessions events my-session --offset 0 --limit 50 --endpoint http://127.0.0.1:2468 +sandbox-agent api sessions terminate ``` -
- -
-api sessions events-sse ```bash -sandbox-agent api sessions events-sse my-session --offset 0 --endpoint http://127.0.0.1:2468 +sandbox-agent api sessions terminate my-session ``` -
-
-api sessions reply-question +#### Get Events + +Fetch session events: ```bash -sandbox-agent api sessions reply-question my-session QUESTION_ID \ - --answers "yes" \ - --endpoint http://127.0.0.1:2468 +sandbox-agent api sessions events [OPTIONS] ``` -
-
-api sessions reject-question +| Option | Description | +|--------|-------------| +| `-o, --offset ` | Event offset | +| `-l, --limit ` | Max events to return | +| `--include-raw` | Include raw agent data | ```bash -sandbox-agent api sessions reject-question my-session QUESTION_ID --endpoint http://127.0.0.1:2468 +sandbox-agent api sessions events my-session --offset 0 --limit 50 ``` -
-
-api sessions reply-permission +`get-messages` is an alias for `events`. + +#### Stream Events (SSE) + +Stream session events via Server-Sent Events: ```bash -sandbox-agent api sessions reply-permission my-session PERMISSION_ID \ - --reply once \ - --endpoint http://127.0.0.1:2468 +sandbox-agent api sessions events-sse [OPTIONS] ``` -
+ +| Option | Description | +|--------|-------------| +| `-o, --offset ` | Event offset to start from | +| `--include-raw` | Include raw agent data | + +```bash +sandbox-agent api sessions events-sse my-session --offset 0 +``` + +#### Reply to Question + +```bash +sandbox-agent api sessions reply-question [OPTIONS] +``` + +| Option | Description | +|--------|-------------| +| `-a, --answers ` | JSON array of answers (required) | + +```bash +sandbox-agent api sessions reply-question my-session q1 \ + --answers '[["yes"]]' +``` + +#### Reject Question + +```bash +sandbox-agent api sessions reject-question +``` + +```bash +sandbox-agent api sessions reject-question my-session q1 +``` + +#### Reply to Permission + +```bash +sandbox-agent api sessions reply-permission [OPTIONS] +``` + +| Option | Description | +|--------|-------------| +| `-r, --reply ` | `once`, `always`, or `reject` (required) | + +```bash +sandbox-agent api sessions reply-permission my-session perm1 --reply once +``` + +--- + +## CLI to HTTP Mapping + +| CLI Command | HTTP Endpoint | +|-------------|---------------| +| `api agents list` | `GET /v1/agents` | +| `api agents install` | `POST /v1/agents/{agent}/install` | +| `api agents modes` | `GET /v1/agents/{agent}/modes` | +| `api sessions list` | `GET /v1/sessions` | +| `api sessions create` | `POST /v1/sessions/{sessionId}` | +| `api sessions send-message` | `POST /v1/sessions/{sessionId}/messages` | +| `api sessions send-message-stream` | `POST /v1/sessions/{sessionId}/messages/stream` | +| `api sessions terminate` | `POST /v1/sessions/{sessionId}/terminate` | +| `api sessions events` | `GET /v1/sessions/{sessionId}/events` | +| `api sessions events-sse` | `GET /v1/sessions/{sessionId}/events/sse` | +| `api sessions reply-question` | `POST /v1/sessions/{sessionId}/questions/{questionId}/reply` | +| `api sessions reject-question` | `POST /v1/sessions/{sessionId}/questions/{questionId}/reject` | +| `api sessions reply-permission` | `POST /v1/sessions/{sessionId}/permissions/{permissionId}/reply` | diff --git a/docs/cors.mdx b/docs/cors.mdx new file mode 100644 index 0000000..6d79b79 --- /dev/null +++ b/docs/cors.mdx @@ -0,0 +1,60 @@ +--- +title: "CORS Configuration" +description: "Configure CORS for browser-based applications." +sidebarTitle: "CORS" +icon: "globe" +--- + +When calling the Sandbox Agent server from a browser, you need to enable CORS (Cross-Origin Resource Sharing) explicitly. + +## Basic Configuration + +```bash +sandbox-agent server \ + --token "$SANDBOX_TOKEN" \ + --cors-allow-origin "http://localhost:5173" \ + --cors-allow-method "GET" \ + --cors-allow-method "POST" \ + --cors-allow-header "Authorization" \ + --cors-allow-header "Content-Type" \ + --cors-allow-credentials +``` + +## Options + +| Flag | Description | +|------|-------------| +| `--cors-allow-origin` | Origins allowed to make requests (e.g., `http://localhost:5173`) | +| `--cors-allow-method` | HTTP methods to allow (can be specified multiple times) | +| `--cors-allow-header` | Headers to allow (can be specified multiple times) | +| `--cors-allow-credentials` | Allow credentials (cookies, authorization headers) | + +## Multiple Origins + +You can allow multiple origins by specifying the flag multiple times: + +```bash +sandbox-agent server \ + --token "$SANDBOX_TOKEN" \ + --cors-allow-origin "http://localhost:5173" \ + --cors-allow-origin "http://localhost:3000" \ + --cors-allow-method "GET" \ + --cors-allow-method "POST" \ + --cors-allow-header "Authorization" \ + --cors-allow-header "Content-Type" +``` + +## Production + +In production, replace `localhost` origins with your actual domain: + +```bash +sandbox-agent server \ + --token "$SANDBOX_TOKEN" \ + --cors-allow-origin "https://your-app.com" \ + --cors-allow-method "GET" \ + --cors-allow-method "POST" \ + --cors-allow-header "Authorization" \ + --cors-allow-header "Content-Type" \ + --cors-allow-credentials +``` diff --git a/docs/deploy/daytona.mdx b/docs/deploy/daytona.mdx index 2500cb4..d78efde 100644 --- a/docs/deploy/daytona.mdx +++ b/docs/deploy/daytona.mdx @@ -1,21 +1,90 @@ --- title: "Daytona" -description: "Run the daemon in a Daytona workspace." +description: "Run the daemon in a Daytona workspace." --- -## Steps + +Daytona has [network egress limits](https://www.daytona.io/docs/en/network-limits/) on lower tiers. OpenAI and Anthropic APIs are whitelisted on all tiers, but other external services may be restricted on Tier 1 & 2. + -1. Create a Daytona workspace with Rust and curl available. -2. Install or build the sandbox-agent binary. -3. Start the daemon and expose port `2468` (or your preferred port). +## Prerequisites -```bash -export SANDBOX_TOKEN="..." +- `DAYTONA_API_KEY` environment variable +- `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` for the coding agents -cargo run -p sandbox-agent -- server \ - --token "$SANDBOX_TOKEN" \ - --host 0.0.0.0 \ - --port 2468 +## TypeScript Example + +```typescript +import { Daytona, Image } from "@daytonaio/sdk"; +import { SandboxAgent } from "sandbox-agent"; + +const daytona = new Daytona(); + +// Pass API keys to the sandbox +const envVars: Record = {}; +if (process.env.ANTHROPIC_API_KEY) envVars.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; +if (process.env.OPENAI_API_KEY) envVars.OPENAI_API_KEY = process.env.OPENAI_API_KEY; + +const sandbox = await daytona.create({ envVars }); + +// Install sandbox-agent +await sandbox.process.executeCommand( + "curl -fsSL https://releases.rivet.dev/sandbox-agent/latest/install.sh | sh" +); + +// Start the server in the background +await sandbox.process.executeCommand( + "nohup sandbox-agent server --no-token --host 0.0.0.0 --port 3000 >/tmp/sandbox-agent.log 2>&1 &" +); + +// Wait for server to be ready +await new Promise((r) => setTimeout(r, 2000)); + +// Get the public URL +const baseUrl = (await sandbox.getSignedPreviewUrl(3000, 4 * 60 * 60)).url; + +// Connect and use the SDK +const client = await SandboxAgent.connect({ baseUrl }); + +await client.createSession("my-session", { + agent: "claude", + permissionMode: "default", +}); + +// Cleanup when done +await sandbox.delete(); ``` -4. Use your Daytona port forwarding to reach the daemon from your client. +## Using Snapshots for Faster Startup + +For production, use snapshots with pre-installed binaries: + +```typescript +import { Daytona, Image } from "@daytonaio/sdk"; + +const daytona = new Daytona(); +const SNAPSHOT = "sandbox-agent-ready"; + +// Create snapshot once (takes 2-3 minutes) +const hasSnapshot = await daytona.snapshot.get(SNAPSHOT).then(() => true, () => false); + +if (!hasSnapshot) { + await daytona.snapshot.create({ + name: SNAPSHOT, + image: Image.base("ubuntu:22.04").runCommands( + "apt-get update && apt-get install -y curl ca-certificates", + "curl -fsSL https://releases.rivet.dev/sandbox-agent/latest/install.sh | sh", + "sandbox-agent install-agent claude", + "sandbox-agent install-agent codex", + ), + }); +} + +// Now sandboxes start instantly +const sandbox = await daytona.create({ + snapshot: SNAPSHOT, + envVars, +}); +``` + +See [Daytona Snapshots](https://daytona.io/docs/snapshots) for details. diff --git a/docs/deploy/docker.mdx b/docs/deploy/docker.mdx index 5cccd43..5152f60 100644 --- a/docs/deploy/docker.mdx +++ b/docs/deploy/docker.mdx @@ -1,27 +1,75 @@ --- -title: "Docker (dev)" +title: "Docker" description: "Build and run the daemon in a Docker container." --- -## Build the binary + +Docker is not recommended for production. Standard Docker containers don't provide sufficient isolation for running untrusted code. Use a dedicated sandbox provider like E2B or Daytona for production workloads. + -Use the release Dockerfile to build a static binary: +## Quick Start + +Run sandbox-agent in a container with agents pre-installed: + +```bash +docker run --rm -p 3000:3000 \ + -e ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" \ + -e OPENAI_API_KEY="$OPENAI_API_KEY" \ + debian:bookworm-slim bash -lc "\ + apt-get update && apt-get install -y curl ca-certificates && \ + curl -fsSL https://releases.rivet.dev/sandbox-agent/latest/install.sh | sh && \ + sandbox-agent install-agent claude && \ + sandbox-agent install-agent codex && \ + sandbox-agent server --no-token --host 0.0.0.0 --port 3000" +``` + +Access the API at `http://localhost:3000`. + +## TypeScript with dockerode + +```typescript +import Docker from "dockerode"; +import { SandboxAgent } from "sandbox-agent"; + +const docker = new Docker(); +const PORT = 3000; + +const container = await docker.createContainer({ + Image: "debian:bookworm-slim", + Cmd: ["bash", "-lc", [ + "apt-get update && apt-get install -y curl ca-certificates", + "curl -fsSL https://releases.rivet.dev/sandbox-agent/latest/install.sh | sh", + "sandbox-agent install-agent claude", + "sandbox-agent install-agent codex", + `sandbox-agent server --no-token --host 0.0.0.0 --port ${PORT}`, + ].join(" && ")], + ExposedPorts: { [`${PORT}/tcp`]: {} }, + HostConfig: { + AutoRemove: true, + PortBindings: { [`${PORT}/tcp`]: [{ HostPort: `${PORT}` }] }, + }, +}); + +await container.start(); + +// Wait for server and connect +const baseUrl = `http://127.0.0.1:${PORT}`; +const client = await SandboxAgent.connect({ baseUrl }); + +// Use the client... +await client.createSession("my-session", { + agent: "claude", + permissionMode: "default", +}); +``` + +## Building from Source + +To build a static binary for use in minimal containers: ```bash docker build -f docker/release/linux-x86_64.Dockerfile -t sandbox-agent-build . - docker run --rm -v "$PWD/artifacts:/artifacts" sandbox-agent-build ``` -The binary will be written to `./artifacts/sandbox-agent-x86_64-unknown-linux-musl`. - -## Run the daemon - -```bash -docker run --rm -p 2468:2468 \ - -v "$PWD/artifacts:/artifacts" \ - debian:bookworm-slim \ - /artifacts/sandbox-agent-x86_64-unknown-linux-musl server --token "$SANDBOX_TOKEN" --host 0.0.0.0 --port 2468 -``` - -You can now access the API at `http://localhost:2468`. +The binary will be at `./artifacts/sandbox-agent-x86_64-unknown-linux-musl`. diff --git a/docs/deploy/e2b.mdx b/docs/deploy/e2b.mdx index 682c6f8..233a9af 100644 --- a/docs/deploy/e2b.mdx +++ b/docs/deploy/e2b.mdx @@ -3,23 +3,77 @@ title: "E2B" description: "Deploy the daemon inside an E2B sandbox." --- -## Steps +## Prerequisites -1. Start an E2B sandbox with network access. -2. Install the agent binaries you need (Claude, Codex, OpenCode, Amp). -3. Run the daemon and expose its port. +- `E2B_API_KEY` environment variable +- `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` for the coding agents -Example startup script: +## TypeScript Example -```bash -export SANDBOX_TOKEN="..." +```typescript +import { Sandbox } from "@e2b/code-interpreter"; +import { SandboxAgent } from "sandbox-agent"; -# Install sandbox-agent binary (or build from source) -# TODO: replace with release download once published -cargo run -p sandbox-agent -- server \ - --token "$SANDBOX_TOKEN" \ - --host 0.0.0.0 \ - --port 2468 +// Pass API keys to the sandbox +const envs: Record = {}; +if (process.env.ANTHROPIC_API_KEY) envs.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; +if (process.env.OPENAI_API_KEY) envs.OPENAI_API_KEY = process.env.OPENAI_API_KEY; + +const sandbox = await Sandbox.create({ envs }); + +// Install sandbox-agent +await sandbox.commands.run( + "curl -fsSL https://releases.rivet.dev/sandbox-agent/latest/install.sh | sh" +); + +// Start the server in the background +await sandbox.commands.run( + "sandbox-agent server --no-token --host 0.0.0.0 --port 3000", + { background: true } +); + +// Connect to the server +const baseUrl = `https://${sandbox.getHost(3000)}`; +const client = await SandboxAgent.connect({ baseUrl }); + +// Wait for server to be ready +for (let i = 0; i < 30; i++) { + try { + await client.getHealth(); + break; + } catch { + await new Promise((r) => setTimeout(r, 1000)); + } +} + +// Install agents (or pre-install in a custom template) +await client.installAgent("claude"); +await client.installAgent("codex"); + +// Create a session and start coding +await client.createSession("my-session", { + agent: "claude", + permissionMode: "default", +}); + +await client.postMessage("my-session", { + message: "Summarize this repository", +}); + +for await (const event of client.streamEvents("my-session")) { + console.log(event.type, event.data); +} + +// Cleanup +await sandbox.kill(); ``` -4. Configure your client to connect to the sandbox endpoint. +## Faster Cold Starts + +For faster startup, create a custom E2B template with sandbox-agent and agents pre-installed: + +1. Create a template with the install script baked in +2. Pre-install agents: `sandbox-agent install-agent claude codex` +3. Use the template ID when creating sandboxes + +See [E2B Custom Templates](https://e2b.dev/docs/sandbox-template) for details. diff --git a/docs/deploy/index.mdx b/docs/deploy/index.mdx index aa4b1b3..8b29c30 100644 --- a/docs/deploy/index.mdx +++ b/docs/deploy/index.mdx @@ -1,4 +1,21 @@ --- -sidebarTitle: Overview +title: "Deploy" +sidebarTitle: "Overview" +description: "Choose where to run the sandbox-agent server." +icon: "server" --- + + + Run locally for development. The SDK can auto-spawn the server. + + + Deploy inside an E2B sandbox with network access. + + + Run in a Daytona workspace with port forwarding. + + + Build and run in a container (development only). + + diff --git a/docs/deploy/local.mdx b/docs/deploy/local.mdx new file mode 100644 index 0000000..e70a14f --- /dev/null +++ b/docs/deploy/local.mdx @@ -0,0 +1,43 @@ +--- +title: "Local" +description: "Run the daemon locally for development." +--- + +For local development, you can run the daemon directly on your machine. + +## With the CLI + +```bash +# Install +curl -fsSL https://releases.rivet.dev/sandbox-agent/latest/install.sh | sh + +# Run +sandbox-agent server --no-token --host 127.0.0.1 --port 2468 +``` + +Or with npm: + +```bash +npx sandbox-agent server --no-token --host 127.0.0.1 --port 2468 +``` + +## With the TypeScript SDK + +The SDK can automatically spawn and manage the server as a subprocess: + +```typescript +import { SandboxAgent } from "sandbox-agent"; + +// Spawns sandbox-agent server as a subprocess +const client = await SandboxAgent.start(); + +await client.createSession("my-session", { + agent: "claude", + permissionMode: "default", +}); + +// When done +await client.dispose(); +``` + +This installs the binary (if needed) and starts the server on a random available port. No manual setup required. diff --git a/docs/deploy/vercel-sandboxes.mdx b/docs/deploy/vercel-sandboxes.mdx deleted file mode 100644 index ea460ae..0000000 --- a/docs/deploy/vercel-sandboxes.mdx +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: "Vercel Sandboxes" -description: "Run the daemon inside Vercel Sandboxes." ---- - -## Steps - -1. Provision a Vercel Sandbox with network access and storage. -2. Install the agent binaries you need. -3. Run the daemon and expose the port. - -```bash -export SANDBOX_TOKEN="..." - -cargo run -p sandbox-agent -- server \ - --token "$SANDBOX_TOKEN" \ - --host 0.0.0.0 \ - --port 2468 -``` - -4. Configure your client to use the sandbox URL. diff --git a/docs/docs.json b/docs/docs.json index bbf3174..dddabed 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -34,38 +34,43 @@ "pages": [ { "group": "Getting started", - "pages": [ - "index", - "quickstart", - "architecture", - "agent-compatibility", - "universal-api", - "frontend", - "building-chat-ui", - "manage-session-state" - ] - }, - { - "group": "SDKs", - "pages": ["sdks/typescript"] - }, - { - "group": "AI", - "pages": ["ai/skill", "ai/llms-txt"] - }, - { - "group": "Reference", - "pages": ["cli", "telemetry", "http-api"] + "pages": ["quickstart", "building-chat-ui", "manage-sessions"] }, { "group": "Deploy", "pages": [ "deploy/index", - "deploy/docker", + "deploy/local", "deploy/e2b", "deploy/daytona", - "deploy/vercel-sandboxes" + "deploy/docker" ] + }, + { + "group": "SDKs", + "pages": ["sdks/typescript", "sdks/python"] + }, + { + "group": "Reference", + "pages": [ + "cli", + "inspector", + "universal-schema", + "agent-compatibility", + "cors", + { + "group": "AI", + "pages": ["ai/skill", "ai/llms-txt"] + }, + { + "group": "Advanced", + "pages": ["telemetry"] + } + ] + }, + { + "group": "HTTP API Reference", + "openapi": "openapi.json" } ] } diff --git a/docs/favicon.svg b/docs/favicon.svg index b785c73..d36cc7e 100644 --- a/docs/favicon.svg +++ b/docs/favicon.svg @@ -1,19 +1,10 @@ - - - - - - - - - - - - - - - - - - + + + SA + + + + + + diff --git a/docs/frontend.mdx b/docs/frontend.mdx deleted file mode 100644 index fca7c8c..0000000 --- a/docs/frontend.mdx +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: "Frontend Demo" -description: "Run the Vite + React UI for testing the server." ---- - -The demo frontend lives at `frontend/packages/inspector`. - -## Run locally - -```bash -pnpm install -pnpm --filter @sandbox-agent/inspector dev -``` - -The UI expects: - -- Endpoint (e.g. `http://127.0.0.1:2468`) -- Optional token - -When running the server, the inspector is also served automatically at `http://127.0.0.1:2468/ui`. - -If you see CORS errors, enable CORS on the server with `sandbox-agent server --cors-allow-origin` and related flags. diff --git a/docs/glossary.md b/docs/glossary.md deleted file mode 100644 index 1079b88..0000000 --- a/docs/glossary.md +++ /dev/null @@ -1,62 +0,0 @@ -# Glossary (Universal Schema) - -This glossary defines the universal schema terms used across the daemon, SDK, and tests. - -Session terms -- session_id: daemon-generated identifier for a universal session. -- native_session_id: provider-native thread/session/run identifier (thread_id merged here). -- session.started: event emitted at session start (native or synthetic). -- session.ended: event emitted at session end (native or synthetic); includes reason and terminated_by. -- terminated_by: who ended the session: agent or daemon. -- reason: why the session ended: completed, error, or terminated. - -Event terms -- UniversalEvent: envelope that wraps all events; includes source, type, data, raw. -- event_id: unique identifier for the event. -- sequence: monotonic event sequence number within a session. -- time: RFC3339 timestamp for the event. -- source: event origin: agent (native) or daemon (synthetic). -- raw: original provider payload for native events; optional for synthetic events. - -Item terms -- item_id: daemon-generated identifier for a universal item. -- native_item_id: provider-native item/message identifier when available; null otherwise. -- parent_id: item_id of the parent item (e.g., tool call/result parented to a message). -- kind: item category: message, tool_call, tool_result, system, status, unknown. -- role: actor role for message items: user, assistant, system, tool (or null). -- status: item lifecycle status: in_progress, completed, failed (or null). - -Item event terms -- item.started: item creation event (may be synthetic). -- item.delta: streaming delta event (native where supported; synthetic otherwise). -- item.completed: final item event with complete content. - -Content terms -- content: ordered list of parts that make up an item payload. -- content part: a typed element inside content (text, json, tool_call, tool_result, file_ref, image, status, reasoning). -- text: plain text content part. -- json: structured JSON content part. -- tool_call: tool invocation content part (name, arguments, call_id). -- tool_result: tool result content part (call_id, output). -- file_ref: file reference content part (path, action, diff). -- image: image content part (path, mime). -- status: status content part (label, detail). -- reasoning: reasoning content part (text, visibility). -- visibility: reasoning visibility: public or private. - -HITL terms -- permission.requested / permission.resolved: human-in-the-loop permission flow events. -- permission_id: identifier for the permission request. -- question.requested / question.resolved: human-in-the-loop question flow events. -- question_id: identifier for the question request. -- options: question answer options. -- response: selected answer for a question. - -Synthetic terms -- synthetic event: a daemon-emitted event used to fill gaps in provider-native schemas. -- source=daemon: marks synthetic events. -- synthetic delta: a single full-content delta emitted for providers without native deltas. - -Provider terms -- agent: the native provider (claude, codex, opencode, amp). -- native payload: the provider’s original event/message object stored in raw. diff --git a/docs/http-api.mdx b/docs/http-api.mdx deleted file mode 100644 index 5b39919..0000000 --- a/docs/http-api.mdx +++ /dev/null @@ -1,169 +0,0 @@ ---- -title: "HTTP API" -description: "Endpoint reference for the sandbox agent daemon." ---- - -All endpoints are under `/v1`. Authentication uses the daemon-level token via `Authorization: Bearer `. - -## Health - -
-
GET /v1/health - Connectivity check - -Response: - -```json -{ "status": "ok" } -``` - - -## Sessions - -
-POST /v1/sessions/{sessionId} - Create session - -Request: - -```json -{ - "agent": "claude", - "agentMode": "build", - "permissionMode": "default", - "model": "claude-3-5-sonnet", - "variant": "high", - "agentVersion": "latest" -} -``` - -Response: - -```json -{ - "healthy": true, - "agentSessionId": "..." -} -``` -
- -
-POST /v1/sessions/{sessionId}/messages - Send message - -Request: - -```json -{ - "message": "Describe the repository." -} -``` -
- -
-GET /v1/sessions/{sessionId}/events - Fetch events - -Query params: - -- `offset`: last-seen event id (exclusive) -- `limit`: max number of events - -Response: - -```json -{ - "events": [ - { - "id": 1, - "timestamp": "2026-01-25T10:00:00Z", - "sessionId": "my-session", - "agent": "claude", - "agentSessionId": "...", - "data": { "message": { "role": "assistant", "parts": [{ "type": "text", "text": "..." }] } } - } - ], - "hasMore": false -} -``` -
- -
-GET /v1/sessions/{sessionId}/events/sse - Stream events (SSE) - -Query params: - -- `offset`: last-seen event id (exclusive) - -SSE payloads are `UniversalEvent` JSON. -
- -
-POST /v1/sessions/{sessionId}/questions/{questionId}/reply - -Request: - -```json -{ "answers": [["Option A"], ["Option B", "Option C"]] } -``` -
- -
-POST /v1/sessions/{sessionId}/questions/{questionId}/reject - -Request: - -```json -{} -``` -
- -
-POST /v1/sessions/{sessionId}/permissions/{permissionId}/reply - -Request: - -```json -{ "reply": "once" } -``` -
- -## Agents - -
-GET /v1/agents - List agents - -Response: - -```json -{ - "agents": [ - { "id": "claude", "installed": true, "version": "...", "path": "/usr/local/bin/claude" } - ] -} -``` -
- -
-POST /v1/agents/{agentId}/install - Install agent - -Request: - -```json -{ "reinstall": false } -``` -
- -
-GET /v1/agents/{agentId}/modes - List modes - -Response: - -```json -{ - "modes": [ - { "id": "build", "name": "Build", "description": "Default coding mode" } - ] -} -``` -
- -## Error handling - -All errors use RFC 7807 Problem Details and stable `type` strings (e.g. `urn:sandbox-agent:error:session_not_found`). diff --git a/docs/images/inspector.png b/docs/images/inspector.png new file mode 100644 index 0000000..1c16ed2 Binary files /dev/null and b/docs/images/inspector.png differ diff --git a/docs/index.mdx b/docs/index.mdx deleted file mode 100644 index 0503d76..0000000 --- a/docs/index.mdx +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: "Overview" -description: "Universal API for running Claude Code, Codex, OpenCode, and Amp inside sandboxes." ---- - -Sandbox Agent SDK is a universal API and daemon for running coding agents inside sandboxes. It standardizes agent sessions, events, and human-in-the-loop workflows across Claude Code, Codex, OpenCode, and Amp. - -## At a glance - -- Universal HTTP API and TypeScript SDK -- Runs inside sandboxes with a lightweight Rust daemon -- Streams events in a shared UniversalEvent schema -- Supports questions and permission workflows -- Designed for multi-provider sandbox environments - -## Quickstart - -Run the daemon locally: - -```bash -sandbox-agent server --token "$SANDBOX_TOKEN" --host 127.0.0.1 --port 2468 -``` - -Send a message: - -```bash -curl -X POST "http://127.0.0.1:2468/v1/sessions/my-session" \ - -H "Authorization: Bearer $SANDBOX_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{"agent":"claude"}' - -curl -X POST "http://127.0.0.1:2468/v1/sessions/my-session/messages" \ - -H "Authorization: Bearer $SANDBOX_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{"message":"Explain the repo structure."}' -``` - -See the full quickstart in [Quickstart](/quickstart). - -## What this project solves - -- **Universal Coding Agent API**: standardize tool calls, messages, and events across agents. -- **Agents in sandboxes**: run a single HTTP daemon inside any sandbox provider. -- **Agent transcripts**: stream or persist a universal event log in your own storage. - -## Project scope - -**In scope** - -- Agent session orchestration inside a sandbox -- Streaming events in a universal schema -- Human-in-the-loop questions and permissions -- TypeScript SDK and CLI wrappers - -**Out of scope** - -- Persistent storage of sessions on disk -- Building custom LLM agents (use Vercel AI SDK for that) -- Sandbox provider APIs (use provider SDKs or custom glue) -- Git repo management - -## Next steps - -- Read the [Architecture](/architecture) overview -- Review [Agent compatibility](/agent-compatibility) -- See the [HTTP API](/http-api) and [CLI](/cli) -- Run the [Frontend demo](/frontend) -- Use the [TypeScript SDK](/typescript-sdk) diff --git a/docs/inspector.mdx b/docs/inspector.mdx new file mode 100644 index 0000000..b095ff2 --- /dev/null +++ b/docs/inspector.mdx @@ -0,0 +1,45 @@ +--- +title: "Inspector" +description: "Debug and inspect agent sessions with the Inspector UI." +icon: "magnifying-glass" +--- + +The Inspector is a web-based GUI for debugging and inspecting Sandbox Agent sessions. Use it to view events, send messages, and troubleshoot agent behavior in real-time. + + + Sandbox Agent Inspector + + +## Open the Inspector + +Visit [inspect.sandboxagent.dev](https://inspect.sandboxagent.dev) and enter your server URL and token to connect. + +You can also generate a pre-filled Inspector URL from the TypeScript SDK: + +```typescript +import { buildInspectorUrl } from "sandbox-agent"; + +const url = buildInspectorUrl({ + baseUrl: "http://127.0.0.1:2468", + token: process.env.SANDBOX_TOKEN, +}); +console.log(url); +// https://inspect.sandboxagent.dev?url=http%3A%2F%2F127.0.0.1%3A2468&token=... +``` + +## Features + +- **Session list**: View all active sessions and their status +- **Event stream**: See events in real-time as they arrive (SSE or polling) +- **Event details**: Expand any event to see its full JSON payload +- **Send messages**: Post messages to a session directly from the UI +- **Agent selection**: Switch between agents and modes +- **Request log**: View raw HTTP requests and responses for debugging + +## When to Use + +The Inspector is useful for: + +- **Development**: Test your integration without writing client code +- **Debugging**: Inspect event payloads and timing issues +- **Learning**: Understand how agents respond to different prompts diff --git a/docs/manage-sessions.mdx b/docs/manage-sessions.mdx index 6424a72..a43c371 100644 --- a/docs/manage-sessions.mdx +++ b/docs/manage-sessions.mdx @@ -1,21 +1,261 @@ --- -title: "Manage Session State" -description: "TODO" +title: "Manage Sessions" +description: "Persist and replay agent transcripts across connections." +icon: "database" --- -TODO +Sandbox Agent stores sessions in memory only. When the server restarts or the sandbox is destroyed, all session data is lost. It's your responsibility to persist events to your own database. + +See the [Building a Chat UI](/building-chat-ui) guide for understanding session lifecycle events like `session.started` and `session.ended`. ## Recommended approach -- Store the offset of the last message you have seen (the last event id). -- Update your server to stream events from the Events API using that offset. -- Write the resulting messages and events to your own database. +1. Store events to your database as they arrive +2. On reconnect, get the last event's `sequence` and pass it as `offset` +3. The API returns events where `sequence > offset` -This lets you resume from a known offset after a disconnect and prevents duplicate writes. +This prevents duplicate writes and lets you recover from disconnects. -## Recommended: Rivet Actors +## Receiving Events -If you want a managed way to keep long-running streams alive, consider [Rivet Actors](https://rivet.dev). -They handle continuous event streaming plus fast reads and writes of data for agents, with built-in -realtime support and observability. You can use them to stream `/events/sse` per session and persist -each event to your database as it arrives. +Two ways to receive events: SSE streaming (recommended) or polling. + +### Streaming + +Use SSE for real-time events with automatic reconnection support. + +```typescript +import { SandboxAgent } from "sandbox-agent"; + +const client = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", +}); + +// Get offset from last stored event (0 returns all events) +const lastEvent = await db.getLastEvent("my-session"); +const offset = lastEvent?.sequence ?? 0; + +// Stream from where you left off +for await (const event of client.streamEvents("my-session", { offset })) { + await db.insertEvent("my-session", event); +} +``` + +### Polling + +If you can't use SSE streaming, poll the events endpoint: + +```typescript +const lastEvent = await db.getLastEvent("my-session"); +let offset = lastEvent?.sequence ?? 0; + +while (true) { + const { events } = await client.getEvents("my-session", { + offset, + limit: 100 + }); + + for (const event of events) { + await db.insertEvent("my-session", event); + offset = event.sequence; + } + + await sleep(1000); +} +``` + +## Database options + +Choose where to persist events based on your requirements. For most use cases, we recommend Rivet Actors. + +| | Durable | Real-time | Multiplayer | Scaling | Throughput | Complexity | +|---------|:-------:|:---------:|:-----------:|---------|------------|------------| +| Rivet Actors | ✓ | ✓ | ✓ | Auto-sharded, one actor per session | Millions of concurrent sessions | Zero infrastructure | +| PostgreSQL | ✓ | | | Manual sharding | Connection pool limited | Connection pools, migrations | +| Redis | | ✓ | | Redis Cluster | High, in-memory | Memory management, Sentinel for failover | + +### Rivet Actors + +For production workloads, [Rivet Actors](https://rivet.gg) provide a managed solution for: + +- **Persistent state**: Events survive crashes and restarts +- **Real-time streaming**: Built-in WebSocket support for clients +- **Horizontal scaling**: Run thousands of concurrent sessions +- **Observability**: Built-in logging and metrics + +#### Actor + +```typescript +import { actor } from "rivetkit"; +import { Daytona } from "@daytonaio/sdk"; +import { SandboxAgent, SandboxAgentClient, AgentEvent } from "sandbox-agent"; + +interface CodingSessionState { + sandboxId: string; + baseUrl: string; + sessionId: string; + events: AgentEvent[]; +} + +interface CodingSessionVars { + client: SandboxAgentClient; +} + +const daytona = new Daytona(); + +const codingSession = actor({ + createState: async (): Promise => { + const sandbox = await daytona.create({ + snapshot: "sandbox-agent-ready", + envVars: { + ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY, + OPENAI_API_KEY: process.env.OPENAI_API_KEY, + }, + autoStopInterval: 0, + }); + + await sandbox.process.executeCommand( + "nohup sandbox-agent server --no-token --host 0.0.0.0 --port 3000 &" + ); + + const baseUrl = (await sandbox.getSignedPreviewUrl(3000)).url; + const sessionId = crypto.randomUUID(); + + return { + sandboxId: sandbox.id, + baseUrl, + sessionId, + events: [], + }; + }, + + createVars: async (c): Promise => { + const client = await SandboxAgent.connect({ baseUrl: c.state.baseUrl }); + await client.createSession(c.state.sessionId, { agent: "claude" }); + return { client }; + }, + + onDestroy: async (c) => { + const sandbox = await daytona.get(c.state.sandboxId); + await sandbox.delete(); + }, + + run: async (c) => { + for await (const event of c.vars.client.streamEvents(c.state.sessionId)) { + c.state.events.push(event); + c.broadcast("agentEvent", event); + } + }, + + actions: { + postMessage: async (c, message: string) => { + await c.vars.client.postMessage(c.state.sessionId, message); + }, + + getTranscript: (c) => c.state.events, + }, +}); +``` + +#### Client + + + +```typescript TypeScript +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const session = client.codingSession.getOrCreate(["my-session"]); + +const conn = session.connect(); +conn.on("agentEvent", (event) => { + console.log(event.type, event.data); +}); + +await conn.postMessage("Create a new React component for user profiles"); + +const transcript = await conn.getTranscript(); +``` + +```typescript React +import { createRivetKit } from "@rivetkit/react"; + +const { useActor } = createRivetKit(); + +function CodingSession() { + const [messages, setMessages] = useState([]); + const session = useActor({ name: "codingSession", key: ["my-session"] }); + + session.useEvent("agentEvent", (event) => { + setMessages((prev) => [...prev, event]); + }); + + const sendPrompt = async (prompt: string) => { + await session.connection?.postMessage(prompt); + }; + + return ( +
+ {messages.map((msg, i) => ( +
{JSON.stringify(msg)}
+ ))} + +
+ ); +} +``` + +
+ +### PostgreSQL + +```sql +CREATE TABLE agent_events ( + event_id TEXT PRIMARY KEY, + session_id TEXT NOT NULL, + native_session_id TEXT, + sequence INTEGER NOT NULL, + time TIMESTAMPTZ NOT NULL, + type TEXT NOT NULL, + source TEXT NOT NULL, + synthetic BOOLEAN NOT NULL DEFAULT FALSE, + data JSONB NOT NULL, + UNIQUE(session_id, sequence) +); + +CREATE INDEX idx_events_session ON agent_events(session_id, sequence); +``` + +### Redis + +```typescript +// Append event to list +await redis.rpush(`session:${sessionId}`, JSON.stringify(event)); + +// Get events from offset +const events = await redis.lrange(`session:${sessionId}`, offset, -1); +``` + +## Handling disconnects + +The SSE stream may disconnect due to network issues. Handle reconnection gracefully: + +```typescript +async function streamWithRetry(sessionId: string) { + while (true) { + try { + const lastEvent = await db.getLastEvent(sessionId); + const offset = lastEvent?.sequence ?? 0; + + for await (const event of client.streamEvents(sessionId, { offset })) { + await db.insertEvent(sessionId, event); + } + } catch (error) { + console.error("Stream disconnected, reconnecting...", error); + await sleep(1000); + } + } +} +``` diff --git a/docs/quickstart.mdx b/docs/quickstart.mdx index 9162441..ad2e970 100644 --- a/docs/quickstart.mdx +++ b/docs/quickstart.mdx @@ -1,103 +1,288 @@ --- title: "Quickstart" description: "Start the server and send your first message." +icon: "rocket" --- -## 1. Run the server + + + ```bash + npx skills add https://sandboxagent.dev/docs + ``` + -Use the installed binary, or `cargo run` in development. + + Each coding agent requires API keys to connect to their respective LLM providers. -```bash -sandbox-agent server --token "$SANDBOX_TOKEN" --host 127.0.0.1 --port 2468 -``` + + + ```bash + export ANTHROPIC_API_KEY="sk-ant-..." + export OPENAI_API_KEY="sk-..." + ``` + -If you want to run without auth (local dev only): + + ```typescript + import { Sandbox } from "@e2b/code-interpreter"; -```bash -sandbox-agent server --no-token --host 127.0.0.1 --port 2468 -``` + const envs: Record = {}; + if (process.env.ANTHROPIC_API_KEY) envs.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; + if (process.env.OPENAI_API_KEY) envs.OPENAI_API_KEY = process.env.OPENAI_API_KEY; -If you're running from source instead of the installed CLI: + const sandbox = await Sandbox.create({ envs }); + ``` + -```bash -cargo run -p sandbox-agent -- server --token "$SANDBOX_TOKEN" --host 127.0.0.1 --port 2468 -``` + + ```typescript + import { Daytona } from "@daytonaio/sdk"; -### CORS (frontend usage) + const envVars: Record = {}; + if (process.env.ANTHROPIC_API_KEY) envVars.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; + if (process.env.OPENAI_API_KEY) envVars.OPENAI_API_KEY = process.env.OPENAI_API_KEY; -If you are calling the server from a browser, enable CORS explicitly: + const daytona = new Daytona(); + const sandbox = await daytona.create({ + snapshot: "sandbox-agent-ready", + envVars, + }); + ``` + -```bash -sandbox-agent server \ - --token "$SANDBOX_TOKEN" \ - --cors-allow-origin "http://localhost:5173" \ - --cors-allow-method "GET" \ - --cors-allow-method "POST" \ - --cors-allow-header "Authorization" \ - --cors-allow-header "Content-Type" \ - --cors-allow-credentials -``` + + ```bash + docker run -e ANTHROPIC_API_KEY="sk-ant-..." \ + -e OPENAI_API_KEY="sk-..." \ + your-image + ``` + + -## 2. Install agents (optional) + + + Use `sandbox-agent credentials extract-env --export` to extract your existing API keys (Anthropic, OpenAI, etc.) from your existing Claude Code or Codex config files on your machine. + + + If you want to test Sandbox Agent without API keys, use the `mock` agent to test the SDK without any credentials. It simulates agent responses for development and testing. + + + -Agents install lazily on first use. To preinstall everything up front: + + + + Install and run the binary directly. -```bash -sandbox-agent install-agent claude -sandbox-agent install-agent codex -sandbox-agent install-agent opencode -sandbox-agent install-agent amp -``` + ```bash + curl -fsSL https://releases.rivet.dev/sandbox-agent/latest/install.sh | sh + sandbox-agent server --token "$SANDBOX_TOKEN" --host 127.0.0.1 --port 2468 + ``` + -## 3. Create a session + + Run without installing globally. -```bash -curl -X POST "http://127.0.0.1:2468/v1/sessions/my-session" \ - -H "Authorization: Bearer $SANDBOX_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{"agent":"claude","agentMode":"build","permissionMode":"default"}' -``` + ```bash + npx sandbox-agent server --token "$SANDBOX_TOKEN" --host 127.0.0.1 --port 2468 + ``` + -## 4. Send a message + + Install globally, then run. -```bash -curl -X POST "http://127.0.0.1:2468/v1/sessions/my-session/messages" \ - -H "Authorization: Bearer $SANDBOX_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{"message":"Summarize the repository and suggest next steps."}' -``` + ```bash + npm install -g @sandbox-agent/cli + sandbox-agent server --token "$SANDBOX_TOKEN" --host 127.0.0.1 --port 2468 + ``` + -## 5. Read events + + If you're running from source instead of the installed CLI. -```bash -curl "http://127.0.0.1:2468/v1/sessions/my-session/events?offset=0&limit=50" \ - -H "Authorization: Bearer $SANDBOX_TOKEN" -``` + ```bash + cargo run -p sandbox-agent -- server --token "$SANDBOX_TOKEN" --host 127.0.0.1 --port 2468 + ``` + -For streaming output, use SSE: + + For local development, use `SandboxAgent.start()` to automatically spawn and manage the server as a subprocess. -```bash -curl "http://127.0.0.1:2468/v1/sessions/my-session/events/sse?offset=0" \ - -H "Authorization: Bearer $SANDBOX_TOKEN" -``` + ```typescript + import { SandboxAgent } from "sandbox-agent"; -For a single-turn stream (post a message and get one streamed response): + const client = await SandboxAgent.start(); + ``` -```bash -curl -N -X POST "http://127.0.0.1:2468/v1/sessions/my-session/messages/stream" \ - -H "Authorization: Bearer $SANDBOX_TOKEN" \ - -H "content-type: application/json" \ - -d '{"message":"Hello"}' -``` + This installs the binary and starts the server for you. No manual setup required. + + -## 6. CLI shortcuts + + + If endpoint is not public, use `--no-token` to disable authentication. Most sandbox providers already secure their networking, so tokens are not required. + + + If you're calling the server from a browser, see the [CORS configuration guide](/docs/cors). + + + -The `sandbox-agent api` subcommand mirrors the HTTP API: + + To preinstall agents: -```bash -sandbox-agent api sessions create my-session --agent claude --endpoint http://127.0.0.1:2468 --token "$SANDBOX_TOKEN" + ```bash + sandbox-agent install-agent claude + sandbox-agent install-agent codex + sandbox-agent install-agent opencode + sandbox-agent install-agent amp + ``` -sandbox-agent api sessions send-message my-session --message "Hello" --endpoint http://127.0.0.1:2468 --token "$SANDBOX_TOKEN" + If agents are not installed up front, they will be lazily installed when creating a session. It's recommended to pre-install agents then take a snapshot of the sandbox for faster coldstarts. + -sandbox-agent api sessions send-message-stream my-session --message "Hello" --endpoint http://127.0.0.1:2468 --token "$SANDBOX_TOKEN" -``` + + + + ```typescript + import { SandboxAgent } from "sandbox-agent"; + + const client = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", + token: process.env.SANDBOX_TOKEN, + }); + + await client.createSession("my-session", { + agent: "claude", + agentMode: "build", + permissionMode: "default", + }); + ``` + + + + ```bash + curl -X POST "http://127.0.0.1:2468/v1/sessions/my-session" \ + -H "Authorization: Bearer $SANDBOX_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"agent":"claude","agentMode":"build","permissionMode":"default"}' + ``` + + + + ```bash + sandbox-agent api sessions create my-session \ + --agent claude \ + --endpoint http://127.0.0.1:2468 \ + --token "$SANDBOX_TOKEN" + ``` + + + + + + + + ```typescript + await client.postMessage("my-session", { + message: "Summarize the repository and suggest next steps.", + }); + ``` + + + + ```bash + curl -X POST "http://127.0.0.1:2468/v1/sessions/my-session/messages" \ + -H "Authorization: Bearer $SANDBOX_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"message":"Summarize the repository and suggest next steps."}' + ``` + + + + ```bash + sandbox-agent api sessions send-message my-session \ + --message "Summarize the repository and suggest next steps." \ + --endpoint http://127.0.0.1:2468 \ + --token "$SANDBOX_TOKEN" + ``` + + + + + + + + ```typescript + // Poll for events + const events = await client.getEvents("my-session", { offset: 0, limit: 50 }); + + // Or stream events + for await (const event of client.streamEvents("my-session", { offset: 0 })) { + console.log(event.type, event.data); + } + ``` + + + + ```bash + # Poll for events + curl "http://127.0.0.1:2468/v1/sessions/my-session/events?offset=0&limit=50" \ + -H "Authorization: Bearer $SANDBOX_TOKEN" + + # Stream events via SSE + curl "http://127.0.0.1:2468/v1/sessions/my-session/events/sse?offset=0" \ + -H "Authorization: Bearer $SANDBOX_TOKEN" + + # Single-turn stream (post message and get streamed response) + curl -N -X POST "http://127.0.0.1:2468/v1/sessions/my-session/messages/stream" \ + -H "Authorization: Bearer $SANDBOX_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"message":"Hello"}' + ``` + + + + ```bash + # Poll for events + sandbox-agent api sessions events my-session \ + --endpoint http://127.0.0.1:2468 \ + --token "$SANDBOX_TOKEN" + + # Stream events via SSE + sandbox-agent api sessions events-sse my-session \ + --endpoint http://127.0.0.1:2468 \ + --token "$SANDBOX_TOKEN" + + # Single-turn stream + sandbox-agent api sessions send-message-stream my-session \ + --message "Hello" \ + --endpoint http://127.0.0.1:2468 \ + --token "$SANDBOX_TOKEN" + ``` + + + + + + Open the [Inspector UI](https://inspect.sandboxagent.dev) to inspect session state using a GUI. + + + Sandbox Agent Inspector + + + + +## Next steps + + + + Learn how to build a chat interface for your agent. + + + Persist and replay agent transcripts. + + + Deploy your agent to E2B, Daytona, or Vercel Sandboxes. + + diff --git a/docs/sdks/python.mdx b/docs/sdks/python.mdx new file mode 100644 index 0000000..80f667a --- /dev/null +++ b/docs/sdks/python.mdx @@ -0,0 +1,41 @@ +--- +title: "Python" +description: "Python client for managing sessions and streaming events." +icon: "python" +tag: "Coming Soon" +--- + +The Python SDK is on our roadmap. It will provide a typed client for managing sessions and streaming events, similar to the TypeScript SDK. + +In the meantime, you can use the [HTTP API](/http-api) directly with any HTTP client like `requests` or `httpx`. + +```python +import httpx + +base_url = "http://127.0.0.1:2468" +headers = {"Authorization": f"Bearer {token}"} + +# Create a session +httpx.post( + f"{base_url}/v1/sessions/my-session", + headers=headers, + json={"agent": "claude", "permissionMode": "default"} +) + +# Send a message +httpx.post( + f"{base_url}/v1/sessions/my-session/messages", + headers=headers, + json={"message": "Hello from Python"} +) + +# Get events +response = httpx.get( + f"{base_url}/v1/sessions/my-session/events", + headers=headers, + params={"offset": 0, "limit": 50} +) +events = response.json()["events"] +``` + +Want the Python SDK sooner? [Open an issue](https://github.com/rivet-dev/sandbox-agent/issues) to let us know. diff --git a/docs/sdks/typescript.mdx b/docs/sdks/typescript.mdx index 7c5974d..cbaf598 100644 --- a/docs/sdks/typescript.mdx +++ b/docs/sdks/typescript.mdx @@ -1,6 +1,7 @@ --- -title: "TypeScript SDK" +title: "TypeScript" description: "Use the generated client to manage sessions and stream events." +icon: "js" --- The TypeScript SDK is generated from the OpenAPI spec that ships with the server. It provides a typed @@ -147,4 +148,4 @@ The SDK exports OpenAPI-derived types for events, items, and capabilities: import type { UniversalEvent, UniversalItem, AgentCapabilities } from "sandbox-agent"; ``` -See `docs/universal-api.mdx` for the universal schema fields and semantics. +See the [API Reference](/api) for schema details. diff --git a/docs/telemetry.mdx b/docs/telemetry.mdx index 029dd4c..aaa4cc5 100644 --- a/docs/telemetry.mdx +++ b/docs/telemetry.mdx @@ -24,8 +24,3 @@ Disable it with: sandbox-agent server --no-telemetry ``` -Debug builds disable telemetry automatically. You can opt in with: - -```bash -SANDBOX_AGENT_TELEMETRY_DEBUG=1 sandbox-agent server -``` diff --git a/docs/theme.css b/docs/theme.css index 4286d2c..daeb719 100644 --- a/docs/theme.css +++ b/docs/theme.css @@ -20,6 +20,7 @@ body { color: var(--sa-text); } +/* a { color: var(--sa-primary); } @@ -40,13 +41,6 @@ select { color: var(--sa-text); } -code, -pre { - background-color: var(--sa-card); - border: 1px solid var(--sa-border); - color: var(--sa-text); -} - .card, .mintlify-card, .docs-card { @@ -70,3 +64,4 @@ pre { .alert-danger { border-color: var(--sa-danger); } +*/ diff --git a/docs/universal-api.mdx b/docs/universal-api.mdx deleted file mode 100644 index c4f494f..0000000 --- a/docs/universal-api.mdx +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: "Universal API" -description: "Feature checklist and normalization rules." ---- - -## Feature checklist - -- [x] Session creation and lifecycle events -- [x] Message streaming (assistant and tool messages) -- [x] Tool call and tool result normalization -- [x] File and image parts -- [x] Human-in-the-loop questions -- [x] Permission prompts and replies -- [x] Plan approval normalization (Claude -> question) -- [x] Event streaming over SSE -- [ ] Persistent storage (out of scope) - -## Normalization rules - -- **Session ID** is always the client-provided ID. -- **Agent session ID** is surfaced in events but never replaces the primary session ID. -- **Tool calls** map to `UniversalMessagePart::ToolCall` and results to `ToolResult`. -- **File and image parts** map to `AttachmentSource` with `Path`, `Url`, or base64 `Data`. - -## Agent mode vs permission mode - -- **agentMode**: behavior or system prompt strategy (build/plan/custom). -- **permissionMode**: capability restrictions (default/plan/bypass). - -These are separate concepts and must be configured independently. diff --git a/docs/universal-schema.mdx b/docs/universal-schema.mdx new file mode 100644 index 0000000..f33609f --- /dev/null +++ b/docs/universal-schema.mdx @@ -0,0 +1,291 @@ +--- +title: "Universal Schema" +description: "Reference for the universal event and item schema." +icon: "brackets-curly" +--- + +The universal schema normalizes events from all supported agents (Claude Code, Codex, OpenCode, Amp) into a consistent format. This lets you build UIs and persistence layers that work with any agent without special-casing. + +The schema is defined in [OpenAPI format](https://github.com/rivet-dev/sandbox-agent/blob/main/docs/openapi.json). See the [HTTP API Reference](/api-reference) for endpoint documentation. + +## UniversalEvent + +Every event from the API is wrapped in a `UniversalEvent` envelope. + +| Field | Type | Description | +|-------|------|-------------| +| `event_id` | string | Unique identifier for this event | +| `sequence` | integer | Monotonic sequence number within the session (starts at 1) | +| `time` | string | RFC3339 timestamp | +| `session_id` | string | Daemon-generated session identifier | +| `native_session_id` | string? | Provider-native session/thread identifier (e.g., Codex `threadId`, OpenCode `sessionID`) | +| `source` | string | Event origin: `agent` (native) or `daemon` (synthetic) | +| `synthetic` | boolean | Whether this event was generated by the daemon to fill gaps | +| `type` | string | Event type (see [Event Types](#event-types)) | +| `data` | object | Event-specific payload | +| `raw` | any? | Original provider payload (only when `include_raw=true`) | + +```json +{ + "event_id": "evt_abc123", + "sequence": 1, + "time": "2025-01-28T12:00:00Z", + "session_id": "my-session", + "native_session_id": "thread_xyz", + "source": "agent", + "synthetic": false, + "type": "item.completed", + "data": { ... } +} +``` + +## Event Types + +### Session Lifecycle + +| Type | Description | Data | +|------|-------------|------| +| `session.started` | Session has started | `{ metadata?: any }` | +| `session.ended` | Session has ended | `{ reason, terminated_by }` | + +**SessionEndedData** + +| Field | Type | Values | +|-------|------|--------| +| `reason` | string | `completed`, `error`, `terminated` | +| `terminated_by` | string | `agent`, `daemon` | + +### Item Lifecycle + +| Type | Description | Data | +|------|-------------|------| +| `item.started` | Item creation | `{ item }` | +| `item.delta` | Streaming content delta | `{ item_id, native_item_id?, delta }` | +| `item.completed` | Item finalized | `{ item }` | + +Items follow a consistent lifecycle: `item.started` → `item.delta` (0 or more) → `item.completed`. + +### HITL (Human-in-the-Loop) + +| Type | Description | Data | +|------|-------------|------| +| `permission.requested` | Permission request pending | `{ permission_id, action, status, metadata? }` | +| `permission.resolved` | Permission granted or denied | `{ permission_id, action, status, metadata? }` | +| `question.requested` | Question pending user input | `{ question_id, prompt, options, status }` | +| `question.resolved` | Question answered or rejected | `{ question_id, prompt, options, status, response? }` | + +**PermissionEventData** + +| Field | Type | Description | +|-------|------|-------------| +| `permission_id` | string | Identifier for the permission request | +| `action` | string | What the agent wants to do | +| `status` | string | `requested`, `approved`, `denied` | +| `metadata` | any? | Additional context | + +**QuestionEventData** + +| Field | Type | Description | +|-------|------|-------------| +| `question_id` | string | Identifier for the question | +| `prompt` | string | Question text | +| `options` | string[] | Available answer options | +| `status` | string | `requested`, `answered`, `rejected` | +| `response` | string? | Selected answer (when resolved) | + +### Errors + +| Type | Description | Data | +|------|-------------|------| +| `error` | Runtime error | `{ message, code?, details? }` | +| `agent.unparsed` | Parse failure | `{ error, location, raw_hash? }` | + +The `agent.unparsed` event indicates the daemon failed to parse an agent payload. This should be treated as a bug. + +## UniversalItem + +Items represent discrete units of content within a session. + +| Field | Type | Description | +|-------|------|-------------| +| `item_id` | string | Daemon-generated identifier | +| `native_item_id` | string? | Provider-native item/message identifier | +| `parent_id` | string? | Parent item ID (e.g., tool call/result parented to a message) | +| `kind` | string | Item category (see below) | +| `role` | string? | Actor role for message items | +| `status` | string | Lifecycle status | +| `content` | ContentPart[] | Ordered list of content parts | + +### ItemKind + +| Value | Description | +|-------|-------------| +| `message` | User or assistant message | +| `tool_call` | Tool invocation | +| `tool_result` | Tool execution result | +| `system` | System message | +| `status` | Status update | +| `unknown` | Unrecognized item type | + +### ItemRole + +| Value | Description | +|-------|-------------| +| `user` | User message | +| `assistant` | Assistant response | +| `system` | System prompt | +| `tool` | Tool-related message | + +### ItemStatus + +| Value | Description | +|-------|-------------| +| `in_progress` | Item is streaming or pending | +| `completed` | Item is finalized | +| `failed` | Item execution failed | + +## Content Parts + +The `content` array contains typed parts that make up an item's payload. + +### text + +Plain text content. + +```json +{ "type": "text", "text": "Hello, world!" } +``` + +### json + +Structured JSON content. + +```json +{ "type": "json", "json": { "key": "value" } } +``` + +### tool_call + +Tool invocation. + +| Field | Type | Description | +|-------|------|-------------| +| `name` | string | Tool name | +| `arguments` | string | JSON-encoded arguments | +| `call_id` | string | Unique call identifier | + +```json +{ + "type": "tool_call", + "name": "read_file", + "arguments": "{\"path\": \"/src/main.ts\"}", + "call_id": "call_abc123" +} +``` + +### tool_result + +Tool execution result. + +| Field | Type | Description | +|-------|------|-------------| +| `call_id` | string | Matching call identifier | +| `output` | string | Tool output | + +```json +{ + "type": "tool_result", + "call_id": "call_abc123", + "output": "File contents here..." +} +``` + +### file_ref + +File reference with optional diff. + +| Field | Type | Description | +|-------|------|-------------| +| `path` | string | File path | +| `action` | string | `read`, `write`, `patch` | +| `diff` | string? | Unified diff (for patches) | + +```json +{ + "type": "file_ref", + "path": "/src/main.ts", + "action": "write", + "diff": "@@ -1,3 +1,4 @@\n+import { foo } from 'bar';" +} +``` + +### image + +Image reference. + +| Field | Type | Description | +|-------|------|-------------| +| `path` | string | Image file path | +| `mime` | string? | MIME type | + +```json +{ "type": "image", "path": "/tmp/screenshot.png", "mime": "image/png" } +``` + +### reasoning + +Model reasoning/thinking content. + +| Field | Type | Description | +|-------|------|-------------| +| `text` | string | Reasoning text | +| `visibility` | string | `public` or `private` | + +```json +{ "type": "reasoning", "text": "Let me think about this...", "visibility": "public" } +``` + +### status + +Status indicator. + +| Field | Type | Description | +|-------|------|-------------| +| `label` | string | Status label | +| `detail` | string? | Additional detail | + +```json +{ "type": "status", "label": "Running tests", "detail": "3 of 10 passed" } +``` + +## Source & Synthetics + +### EventSource + +The `source` field indicates who emitted the event: + +| Value | Description | +|-------|-------------| +| `agent` | Native event from the agent | +| `daemon` | Synthetic event generated by the daemon | + +### Synthetic Events + +The daemon emits synthetic events (`synthetic: true`, `source: "daemon"`) to provide a consistent event stream across all agents. Common synthetics: + +| Synthetic | When | +|-----------|------| +| `session.started` | Agent doesn't emit explicit session start | +| `session.ended` | Agent doesn't emit explicit session end | +| `item.started` | Agent doesn't emit item start events | +| `item.delta` | Agent doesn't stream deltas natively | +| `question.*` | Claude Code plan mode (from ExitPlanMode tool) | + +### Raw Payloads + +Pass `include_raw=true` to event endpoints to receive the original agent payload in the `raw` field. Useful for debugging or accessing agent-specific data not in the universal schema. + +```typescript +const events = await client.getEvents("my-session", { includeRaw: true }); +// events[0].raw contains the original agent payload +``` diff --git a/frontend/packages/inspector/src/components/ConnectScreen.tsx b/frontend/packages/inspector/src/components/ConnectScreen.tsx index 12137ff..620b76c 100644 --- a/frontend/packages/inspector/src/components/ConnectScreen.tsx +++ b/frontend/packages/inspector/src/components/ConnectScreen.tsx @@ -102,7 +102,7 @@ const ConnectScreen = ({

Start the server with CORS enabled for browser access:
- sandbox-agent server --cors-allow-origin http://localhost:5173 + sandbox-agent server --cors-allow-origin {window.location.origin}

diff --git a/frontend/packages/website/.astro/content-assets.mjs b/frontend/packages/website/.astro/content-assets.mjs deleted file mode 100644 index 2b8b823..0000000 --- a/frontend/packages/website/.astro/content-assets.mjs +++ /dev/null @@ -1 +0,0 @@ -export default new Map(); \ No newline at end of file diff --git a/frontend/packages/website/.astro/content-modules.mjs b/frontend/packages/website/.astro/content-modules.mjs deleted file mode 100644 index 2b8b823..0000000 --- a/frontend/packages/website/.astro/content-modules.mjs +++ /dev/null @@ -1 +0,0 @@ -export default new Map(); \ No newline at end of file diff --git a/frontend/packages/website/.astro/content.d.ts b/frontend/packages/website/.astro/content.d.ts deleted file mode 100644 index c0082cc..0000000 --- a/frontend/packages/website/.astro/content.d.ts +++ /dev/null @@ -1,199 +0,0 @@ -declare module 'astro:content' { - export interface RenderResult { - Content: import('astro/runtime/server/index.js').AstroComponentFactory; - headings: import('astro').MarkdownHeading[]; - remarkPluginFrontmatter: Record; - } - interface Render { - '.md': Promise; - } - - export interface RenderedContent { - html: string; - metadata?: { - imagePaths: Array; - [key: string]: unknown; - }; - } -} - -declare module 'astro:content' { - type Flatten = T extends { [K: string]: infer U } ? U : never; - - export type CollectionKey = keyof AnyEntryMap; - export type CollectionEntry = Flatten; - - export type ContentCollectionKey = keyof ContentEntryMap; - export type DataCollectionKey = keyof DataEntryMap; - - type AllValuesOf = T extends any ? T[keyof T] : never; - type ValidContentEntrySlug = AllValuesOf< - ContentEntryMap[C] - >['slug']; - - export type ReferenceDataEntry< - C extends CollectionKey, - E extends keyof DataEntryMap[C] = string, - > = { - collection: C; - id: E; - }; - export type ReferenceContentEntry< - C extends keyof ContentEntryMap, - E extends ValidContentEntrySlug | (string & {}) = string, - > = { - collection: C; - slug: E; - }; - export type ReferenceLiveEntry = { - collection: C; - id: string; - }; - - /** @deprecated Use `getEntry` instead. */ - export function getEntryBySlug< - C extends keyof ContentEntryMap, - E extends ValidContentEntrySlug | (string & {}), - >( - collection: C, - // Note that this has to accept a regular string too, for SSR - entrySlug: E, - ): E extends ValidContentEntrySlug - ? Promise> - : Promise | undefined>; - - /** @deprecated Use `getEntry` instead. */ - export function getDataEntryById( - collection: C, - entryId: E, - ): Promise>; - - export function getCollection>( - collection: C, - filter?: (entry: CollectionEntry) => entry is E, - ): Promise; - export function getCollection( - collection: C, - filter?: (entry: CollectionEntry) => unknown, - ): Promise[]>; - - export function getLiveCollection( - collection: C, - filter?: LiveLoaderCollectionFilterType, - ): Promise< - import('astro').LiveDataCollectionResult, LiveLoaderErrorType> - >; - - export function getEntry< - C extends keyof ContentEntryMap, - E extends ValidContentEntrySlug | (string & {}), - >( - entry: ReferenceContentEntry, - ): E extends ValidContentEntrySlug - ? Promise> - : Promise | undefined>; - export function getEntry< - C extends keyof DataEntryMap, - E extends keyof DataEntryMap[C] | (string & {}), - >( - entry: ReferenceDataEntry, - ): E extends keyof DataEntryMap[C] - ? Promise - : Promise | undefined>; - export function getEntry< - C extends keyof ContentEntryMap, - E extends ValidContentEntrySlug | (string & {}), - >( - collection: C, - slug: E, - ): E extends ValidContentEntrySlug - ? Promise> - : Promise | undefined>; - export function getEntry< - C extends keyof DataEntryMap, - E extends keyof DataEntryMap[C] | (string & {}), - >( - collection: C, - id: E, - ): E extends keyof DataEntryMap[C] - ? string extends keyof DataEntryMap[C] - ? Promise | undefined - : Promise - : Promise | undefined>; - export function getLiveEntry( - collection: C, - filter: string | LiveLoaderEntryFilterType, - ): Promise, LiveLoaderErrorType>>; - - /** Resolve an array of entry references from the same collection */ - export function getEntries( - entries: ReferenceContentEntry>[], - ): Promise[]>; - export function getEntries( - entries: ReferenceDataEntry[], - ): Promise[]>; - - export function render( - entry: AnyEntryMap[C][string], - ): Promise; - - export function reference( - collection: C, - ): import('astro/zod').ZodEffects< - import('astro/zod').ZodString, - C extends keyof ContentEntryMap - ? ReferenceContentEntry> - : ReferenceDataEntry - >; - // Allow generic `string` to avoid excessive type errors in the config - // if `dev` is not running to update as you edit. - // Invalid collection names will be caught at build time. - export function reference( - collection: C, - ): import('astro/zod').ZodEffects; - - type ReturnTypeOrOriginal = T extends (...args: any[]) => infer R ? R : T; - type InferEntrySchema = import('astro/zod').infer< - ReturnTypeOrOriginal['schema']> - >; - - type ContentEntryMap = { - - }; - - type DataEntryMap = { - - }; - - type AnyEntryMap = ContentEntryMap & DataEntryMap; - - type ExtractLoaderTypes = T extends import('astro/loaders').LiveLoader< - infer TData, - infer TEntryFilter, - infer TCollectionFilter, - infer TError - > - ? { data: TData; entryFilter: TEntryFilter; collectionFilter: TCollectionFilter; error: TError } - : { data: never; entryFilter: never; collectionFilter: never; error: never }; - type ExtractDataType = ExtractLoaderTypes['data']; - type ExtractEntryFilterType = ExtractLoaderTypes['entryFilter']; - type ExtractCollectionFilterType = ExtractLoaderTypes['collectionFilter']; - type ExtractErrorType = ExtractLoaderTypes['error']; - - type LiveLoaderDataType = - LiveContentConfig['collections'][C]['schema'] extends undefined - ? ExtractDataType - : import('astro/zod').infer< - Exclude - >; - type LiveLoaderEntryFilterType = - ExtractEntryFilterType; - type LiveLoaderCollectionFilterType = - ExtractCollectionFilterType; - type LiveLoaderErrorType = ExtractErrorType< - LiveContentConfig['collections'][C]['loader'] - >; - - export type ContentConfig = typeof import("../src/content.config.mjs"); - export type LiveContentConfig = never; -} diff --git a/frontend/packages/website/.astro/data-store.json b/frontend/packages/website/.astro/data-store.json deleted file mode 100644 index e16f873..0000000 --- a/frontend/packages/website/.astro/data-store.json +++ /dev/null @@ -1 +0,0 @@ -[["Map",1,2],"meta::meta",["Map",3,4,5,6],"astro-version","5.16.15","astro-config-digest","{\"root\":{},\"srcDir\":{},\"publicDir\":{},\"outDir\":{},\"cacheDir\":{},\"compressHTML\":true,\"base\":\"/\",\"trailingSlash\":\"ignore\",\"output\":\"static\",\"scopedStyleStrategy\":\"attribute\",\"build\":{\"format\":\"directory\",\"client\":{},\"server\":{},\"assets\":\"_astro\",\"serverEntry\":\"entry.mjs\",\"redirects\":true,\"inlineStylesheets\":\"auto\",\"concurrency\":1},\"server\":{\"open\":false,\"host\":false,\"port\":4321,\"streaming\":true,\"allowedHosts\":[]},\"redirects\":{},\"image\":{\"endpoint\":{\"route\":\"/_image\"},\"service\":{\"entrypoint\":\"astro/assets/services/sharp\",\"config\":{}},\"domains\":[],\"remotePatterns\":[],\"responsiveStyles\":false},\"devToolbar\":{\"enabled\":true},\"markdown\":{\"syntaxHighlight\":{\"type\":\"shiki\",\"excludeLangs\":[\"math\"]},\"shikiConfig\":{\"langs\":[],\"langAlias\":{},\"theme\":\"github-dark\",\"themes\":{},\"wrap\":false,\"transformers\":[]},\"remarkPlugins\":[],\"rehypePlugins\":[],\"remarkRehype\":{},\"gfm\":true,\"smartypants\":true},\"security\":{\"checkOrigin\":true,\"allowedDomains\":[]},\"env\":{\"schema\":{},\"validateSecrets\":false},\"experimental\":{\"clientPrerender\":false,\"contentIntellisense\":false,\"headingIdCompat\":false,\"preserveScriptOrder\":false,\"liveContentCollections\":false,\"csp\":false,\"staticImportMetaEnv\":false,\"chromeDevtoolsWorkspace\":false,\"failOnPrerenderConflict\":false,\"svgo\":false},\"legacy\":{\"collections\":false}}"] \ No newline at end of file diff --git a/frontend/packages/website/.astro/settings.json b/frontend/packages/website/.astro/settings.json deleted file mode 100644 index 02040a5..0000000 --- a/frontend/packages/website/.astro/settings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "_variables": { - "lastUpdateCheck": 1769576078224 - } -} \ No newline at end of file diff --git a/frontend/packages/website/.astro/types.d.ts b/frontend/packages/website/.astro/types.d.ts deleted file mode 100644 index f964fe0..0000000 --- a/frontend/packages/website/.astro/types.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/frontend/packages/website/.gitignore b/frontend/packages/website/.gitignore new file mode 100644 index 0000000..2dc4284 --- /dev/null +++ b/frontend/packages/website/.gitignore @@ -0,0 +1,3 @@ +.astro +dist +node_modules diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json index ae48338..cc08c50 100644 --- a/sdks/typescript/package.json +++ b/sdks/typescript/package.json @@ -20,7 +20,7 @@ "dist" ], "scripts": { - "generate:openapi": "cargo check -p sandbox-agent-openapi-gen && cargo run -p sandbox-agent-openapi-gen -- --out ../../docs/openapi.json", + "generate:openapi": "SANDBOX_AGENT_SKIP_INSPECTOR=1 cargo run -p sandbox-agent-openapi-gen -- --out ../../docs/openapi.json", "generate:types": "openapi-typescript ../../docs/openapi.json -o src/generated/openapi.ts", "generate": "pnpm run generate:openapi && pnpm run generate:types", "build": "if [ -z \"$SKIP_OPENAPI_GEN\" ]; then pnpm run generate:openapi; fi && pnpm run generate:types && tsup", diff --git a/docs/architecture.mdx b/server/ARCHITECTURE.md similarity index 87% rename from docs/architecture.mdx rename to server/ARCHITECTURE.md index 165f04f..5951670 100644 --- a/docs/architecture.mdx +++ b/server/ARCHITECTURE.md @@ -1,7 +1,6 @@ ---- -title: "Architecture" -description: "How the daemon, schemas, and agents fit together." ---- +# Architecture + +How the daemon, schemas, and agents fit together. Sandbox Agent SDK is built around a single daemon that runs inside the sandbox and exposes a universal HTTP API. Clients use the API (or the TypeScript SDK / CLI) to create sessions, send messages, and stream events. @@ -348,3 +347,31 @@ The daemon uses a **global token** configured at startup. All HTTP and CLI opera | Event converters | `server/packages/universal-agent-schema/src/agents/*.rs` | | Schema extractors | `resources/agent-schemas/src/*.ts` | | TypeScript SDK | `sdks/typescript/src/` | + +--- + +# Agent Compatibility + +Supported agents, install methods, and streaming formats. + +## Compatibility Matrix + +| Agent | Provider | Binary | Install method | Session ID | Streaming format | +|-------|----------|--------|----------------|------------|------------------| +| Claude Code | Anthropic | `claude` | curl raw binary from GCS | `session_id` | JSONL via stdout | +| Codex | OpenAI | `codex` | curl tarball from GitHub releases | `thread_id` | JSON-RPC over stdio | +| OpenCode | Multi-provider | `opencode` | curl tarball from GitHub releases | `session_id` | SSE or JSONL | +| Amp | Sourcegraph | `amp` | curl raw binary from GCS | `session_id` | JSONL via stdout | +| Mock | Built-in | — | bundled | `mock-*` | daemon-generated | + +## Agent Modes + +- **OpenCode**: discovered via the server API. +- **Claude Code / Codex / Amp**: hardcoded modes (typically `build`, `plan`, or `custom`). + +## Capability Notes + +- **Questions / permissions**: OpenCode natively supports these workflows. Claude plan approval is normalized into a question event (tests do not currently exercise Claude question/permission flows). +- **Streaming**: all agents stream events; OpenCode uses SSE, Codex uses JSON-RPC over stdio, others use JSONL. Codex is currently normalized to thread/turn starts plus user/assistant completed items (deltas and tool/reasoning items are not emitted yet). +- **User messages**: Claude CLI output does not include explicit user-message events in our snapshots, so only assistant messages are surfaced for Claude today. +- **Files and images**: normalized via `UniversalMessagePart` with `File` and `Image` parts. diff --git a/server/CLAUDE.md b/server/CLAUDE.md index 9c08b48..0326376 100644 --- a/server/CLAUDE.md +++ b/server/CLAUDE.md @@ -1,3 +1,7 @@ +# Server + +See [ARCHITECTURE.md](./ARCHITECTURE.md) for detailed architecture documentation covering the daemon, agent schema pipeline, session management, agent execution patterns, and SDK modes. + # Server Testing ## Test placement