# Agent Sandbox — Direct API Usage Prompt

How to authenticate and execute code against the Sandbox API.

## Overview

1. Redirects the user to sign in with their Google account
2. Returns a short-lived **JWT access token** and a long-lived **API key**
3. You use the JWT or API key as a `Bearer` token on all `/v1/*` endpoints

**Base URL:** `https://api.agentsandbox.co`

## Authentication

### Quick Path: API Key via Environment Variable

If the `SANDBOX_API_KEY` environment variable is set, use its value directly as a `Bearer` token — no OAuth flow needed.

If you have a key, skip to **[Using the Sandbox API](#using-the-sandbox-api)**.

### Full Flow: Google Sign-In (OAuth 2.0 + PKCE)

If no API key is available, authenticate the user via Google Sign-In. The agent builds the authorization URL, the user opens it, and the agent captures the redirect.

### Step 1 — Generate PKCE Parameters

```typescript
import crypto from "node:crypto";

const verifier = crypto.randomBytes(32).toString("base64url");
const challenge = crypto
  .createHash("sha256")
  .update(verifier)
  .digest("base64url");
```

### Step 2 — Build the Authorization URL

Construct the URL and present it to the user:

```typescript
const redirectUri = "http://localhost:51199/callback";
const state = crypto.randomBytes(16).toString("hex");

const params = new URLSearchParams({
  client_id: "openclaw-plugin-client",
  redirect_uri: redirectUri,
  response_type: "code",
  code_challenge: challenge,
  code_challenge_method: "S256",
  state,
  scope: "sandbox",
});

const authorizeUrl = `${BASE_URL}/oauth/authorize?${params}`;
```

**Tell the user to open this URL in their browser:**

> Please open this link to sign in with Google and authorize Sandbox API access:
> `{authorizeUrl}`

### Step 3 — Capture the Authorization Code

After the user signs in with Google and grants consent, the browser redirects to your `redirect_uri` with the authorization code:

```
http://localhost:51199/callback?code=<authorization_code>&state=<state>
```

To capture this redirect, either:
- Run a local HTTP server listening on `redirect_uri`
- Ask the user to copy the URL from their browser's address bar after the redirect

Parse the `code` query parameter from the redirect URL. Verify the `state` matches what you sent.

### Step 4 — Exchange the Code for Tokens

```
POST /oauth/token
Content-Type: application/x-www-form-urlencoded
```

| Parameter | Required | Value |
|---|---|---|
| `grant_type` | Yes | `authorization_code` |
| `code` | Yes | The authorization code from Step 3 |
| `redirect_uri` | Yes | Same `redirect_uri` used in Step 2 |
| `client_id` | Yes | `openclaw-plugin-client` |
| `code_verifier` | Yes | The PKCE verifier from Step 1 |

```typescript
const tokenRes = await fetch(`${BASE_URL}/oauth/token`, {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams({
    grant_type: "authorization_code",
    code,
    redirect_uri: redirectUri,
    client_id: "openclaw-plugin-client",
    code_verifier: verifier,
  }),
});
const tokens = await tokenRes.json();
```

**Response:**

```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "bearer",
  "expires_in": 3600,
  "refresh_token": "UodsM5Lvxv8brYJy...",
  "email": "user@example.com",
  "scope": "sandbox",
  "api_key": "sk-sandbox-lFvxBiLd8yOu..."
}
```

The `api_key` is returned on the user's first sign-in. On subsequent sign-ins it will be `null` (the existing key is still valid).

### What to Store

Save **all** of these in your credential store (see [Credential Storage](#credential-storage) below):

| Value | Lifetime | Usage |
|---|---|---|
| `email` | Permanent | Identify the account |
| `access_token` | 1 hour | `Authorization: Bearer <access_token>` on `/v1/*` endpoints |
| `refresh_token` | 30 days (single-use, rotated) | Exchange for a new token pair via `/oauth/token` |
| `api_key` | Permanent | `Authorization: Bearer <api_key>` on `/v1/*` endpoints |

#### Create a permanent API key (if none was returned or you don't have access to one already)

```bash
curl -X POST https://api.agentsandbox.co/v1/api-keys \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{"name": "agent-api-key"}'
```

### Step 5 — Refresh Tokens

When your access token expires, exchange the refresh token:

```
POST /oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token&refresh_token=<refresh_token>
```

Response contains a new `access_token` and a new `refresh_token`. The old refresh token is revoked (rotation). Store the new ones and use the new refresh token for subsequent refreshes.

### Step 6 — Re-authentication

If your refresh token expires or is revoked, repeat the flow from Step 1. The user will sign in with Google again — no new account is created, and the existing API key remains valid.

## Using the Sandbox API

Once authenticated, call `/v1/*` endpoints with a `Bearer` token (either the JWT access token or the API key).

### Execute Code

```
POST /v1/execute
Authorization: Bearer <token>
Content-Type: application/json
```

```json
{
  "language": "python",
  "code": "print('hello from the sandbox')",
  "session_id": null,
  "env_vars": null,
  "file_ids": null
}
```

| Field | Type | Required | Description |
|---|---|---|---|
| `language` | `"python"` or `"bash"` | Yes | Language to execute |
| `code` | string | Yes | Code to run |
| `session_id` | string or null | No | Reuse a persistent session. If `null`, a one-shot sandbox is created and destroyed after execution. |
| `env_vars` | object or null | No | Environment variables to inject into the sandbox |
| `file_ids` | string[] or null | No | File IDs to inject into `/workspace` before execution |

> **Note:** When `file_ids` is provided, files are copied to `/workspace` before code runs. File ownership is validated — you can only inject your own files. The operation is atomic: if any file ID is invalid or access is denied, execution does not proceed.

**Response:**

```json
{
  "session_id": "sandbox_5a79fed5bbb1",
  "stdout": "hello from the sandbox\n",
  "stderr": "",
  "return_code": 0,
  "files": []
}
```

### Persistent Sessions

Create a session to reuse the same sandbox across multiple executions (preserves filesystem state and installed packages) - Make sure to delete sessions when done to free up resources:

```
POST /v1/sessions
Authorization: Bearer <token>
Content-Type: application/json

{"env_vars": null, "file_ids": null}
```

| Field | Type | Required | Description |
|---|---|---|---|
| `env_vars` | object or null | No | Environment variables to inject into the sandbox |
| `file_ids` | string[] or null | No | File IDs to pre-populate in `/workspace` on creation |

Response:

```json
{"session_id": "sandbox_abc123", "created": true}
```

#### Pre-populate Sessions with Files

You can create a session with existing files already in `/workspace` by passing `file_ids`:

```json
{
  "env_vars": null,
  "file_ids": ["f-abc123", "f-def456"]
}
```

This is useful when you've uploaded reference files first and want them available immediately when the session starts.

> **Note:** File ownership is validated — you can only inject your own files. The operation is atomic: if any file ID is invalid or access is denied, no session is created.

Then pass that `session_id` in subsequent `/v1/execute` calls:

```json
{
  "language": "bash",
  "code": "echo 'hello' > /tmp/shared.txt",
  "session_id": "sandbox_abc123"
}
```

```json
{
  "language": "bash",
  "code": "cat /tmp/shared.txt",
  "session_id": "sandbox_abc123"
}
```

The second call prints `hello` because the filesystem persists across executions in the same session. Installed packages (`pip install`, `apt-get`) also persist.

**Other session endpoints:**

| Method | Path | Description |
|---|---|---|
| `GET` | `/v1/sessions` | List active sessions |
| `GET` | `/v1/sessions/{session_id}` | Get session info |
| `POST` | `/v1/sessions/{session_id}/files` | Inject files into running session |
| `DELETE` | `/v1/sessions/{session_id}` | Destroy session and terminate sandbox |

Sessions are automatically cleaned up after an idle timeout (default 5 minutes).

### Inject Files into Running Sessions

You can add files to an already-running session's `/workspace` directory:

```
POST /v1/sessions/{session_id}/files
Authorization: Bearer <token>
Content-Type: application/json
```

```json
{
  "file_ids": ["f-abc123", "f-def456"]
}
```

| Field | Type | Required | Description |
|---|---|---|---|
| `file_ids` | string[] | Yes | File IDs to inject (minimum 1) |

**Response:** `204 No Content`

This enables workflows where you dynamically add files to long-running sessions as needed.

> **Note:** File ownership is validated — you can only inject your own files. The operation is atomic: if any file ID is invalid or access is denied, no files are injected.

### Upload Files

Upload files to cloud storage, optionally injecting them into a sandbox session's `/workspace` directory.

```
POST /v1/files
Authorization: Bearer <token>
Content-Type: multipart/form-data
```

| Query Parameter | Type | Required | Description |
|---|---|---|---|
| `session_id` | string or null | No | Optional session ID to inject the file into the sandbox's `/workspace` |

| Form Field | Type | Required | Description |
|---|---|---|---|
| `file` | binary | Yes | The file to upload |

**Response:**

```json
{
  "file_id": "f-abc123",
  "filename": "data.csv",
  "mime_type": "text/csv",
  "size_bytes": 1024,
  "session_id": "sess-xyz789",
  "created_at": "2025-06-01T12:00:00Z"
}
```

| Field | Type | Description |
|---|---|---|
| `file_id` | string | Unique file identifier |
| `filename` | string | Original filename |
| `mime_type` | string | MIME type (default `application/octet-stream`) |
| `size_bytes` | int | File size in bytes |
| `session_id` | string or null | Session the file was injected into, if any |
| `created_at` | string | ISO 8601 creation timestamp |

When a `session_id` is provided, the file is automatically placed in the sandbox's `/workspace` directory and can be accessed by subsequent code executions in that session.

### Get Execution Details

Retrieve detailed information about a past execution, including the code that was run and its output:

```
GET /v1/executions/{execution_id}
Authorization: Bearer <token>
```

| Path Parameter | Type | Description |
|---|---|---|
| `execution_id` | string | The execution ID (from usage logs) |

**Response:**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "endpoint": "/v1/execute",
  "method": "POST",
  "status_code": 200,
  "duration_ms": 1234.56,
  "session_id": "sandbox_abc123",
  "language": "python",
  "code": "print('hello')",
  "stdout": "hello\n",
  "stderr": "",
  "return_code": 0,
  "files_count": 0,
  "error": null,
  "request_meta": { "has_env_vars": false, "files": [] },
  "created_at": "2025-06-01T12:00:00Z"
}
```

| Field | Type | Description |
|---|---|---|
| `id` | string | Execution identifier |
| `endpoint` | string | API endpoint called |
| `method` | string | HTTP method |
| `status_code` | int or null | HTTP response code |
| `duration_ms` | float or null | Execution duration in milliseconds |
| `session_id` | string or null | Associated sandbox session |
| `language` | string or null | Code language (python/bash) |
| `code` | string or null | The executed code |
| `stdout` | string or null | Standard output |
| `stderr` | string or null | Standard error |
| `return_code` | int or null | Process exit code |
| `files_count` | int | Number of output files |
| `error` | string or null | Error message if failed |
| `request_meta` | object or null | Request metadata |
| `created_at` | string | ISO 8601 timestamp |

### Download Output Files

If executed code writes files, they appear in the `files` array:

```json
{
  "files": [
    {"file_id": "abc123", "filename": "output.csv"}
  ]
}
```

Download with:

```
GET /v1/files/<file_id>
Authorization: Bearer <token>
```

## Recommended Architecture

### Token Strategy

Prefer the **API key** for day-to-day requests (no expiry, no refresh overhead). Fall back to the **JWT access token** if:

- You're on a subsequent sign-in and no API key was returned
- The API key has been revoked or deactivated

```
if api_key exists and works:
    use api_key
else if access_token is not expired:
    use access_token
else if refresh_token exists:
    refresh -> get new access_token
    use access_token
else:
    re-run OAuth flow (user signs in with Google again)
```

### Credential Storage

Store credentials in your auth profile:

```json
{
  "profiles": {
    "sandbox-api:user@example.com": {
      "type": "oauth",
      "provider": "sandbox-api",
      "access": "<jwt_access_token>",
      "refresh": "<refresh_token>",
      "expires": 1769991426000,
      "email": "user@example.com",
      "key": "sk-sandbox-..."
    }
  }
}
```

Read this from `<agentDir>/auth-profiles.json` at tool invocation time.

### Error Handling

| HTTP Status | Meaning | Action |
|---|---|---|
| `200` | Success | Parse response |
| `400` | Bad request / OAuth error | Check `error` and `error_description` fields |
| `401` | Token expired or invalid | Refresh your token or re-authenticate |
| `422` | Validation error | Fix the request body |
| `500` | Server error | Retry with backoff |

OAuth errors follow RFC 6749 format:

```json
{"error": "invalid_grant", "error_description": "Authorization code is invalid or expired"}
```

## Quick Reference

```bash
# Health check (no auth)
curl https://api.agentsandbox.co/health

# Execute Python
curl -X POST https://api.agentsandbox.co/v1/execute \
  -H "Authorization: Bearer sk-sandbox-..." \
  -H "Content-Type: application/json" \
  -d '{"language":"python","code":"print(2+2)"}'

# Execute Bash
curl -X POST https://api.agentsandbox.co/v1/execute \
  -H "Authorization: Bearer sk-sandbox-..." \
  -H "Content-Type: application/json" \
  -d '{"language":"bash","code":"echo hello && uname -a"}'

# Execute with files injected into /workspace
curl -X POST https://api.agentsandbox.co/v1/execute \
  -H "Authorization: Bearer sk-sandbox-..." \
  -H "Content-Type: application/json" \
  -d '{"language":"python","code":"import os; print(os.listdir(\"/workspace\"))","file_ids":["f-abc123"]}'

# Create persistent session
curl -X POST https://api.agentsandbox.co/v1/sessions \
  -H "Authorization: Bearer sk-sandbox-..." \
  -H "Content-Type: application/json" \
  -d '{}'

# Create session with pre-populated files
curl -X POST https://api.agentsandbox.co/v1/sessions \
  -H "Authorization: Bearer sk-sandbox-..." \
  -H "Content-Type: application/json" \
  -d '{"file_ids": ["f-abc123", "f-def456"]}'

# Inject files into running session
curl -X POST https://api.agentsandbox.co/v1/sessions/sandbox_abc123/files \
  -H "Authorization: Bearer sk-sandbox-..." \
  -H "Content-Type: application/json" \
  -d '{"file_ids": ["f-xyz789"]}'

# Upload file (to cloud storage)
curl -X POST https://api.agentsandbox.co/v1/files \
  -H "Authorization: Bearer sk-sandbox-..." \
  -F "file=@data.csv"

# Upload file (inject into session's /workspace)
curl -X POST "https://api.agentsandbox.co/v1/files?session_id=sandbox_abc123" \
  -H "Authorization: Bearer sk-sandbox-..." \
  -F "file=@data.csv"

# Get execution details
curl https://api.agentsandbox.co/v1/executions/550e8400-e29b-41d4-a716-446655440000 \
  -H "Authorization: Bearer sk-sandbox-..."

# Destroy session
curl -X DELETE https://api.agentsandbox.co/v1/sessions/sandbox_abc123 \
  -H "Authorization: Bearer sk-sandbox-..."
```
