Production Guide

Deploy, secure, and operate StateSet Sandbox.

StateSet Sandbox - Production Guide

Overview

StateSet Sandbox is a secure, isolated execution environment for running code on behalf of AI agents. It provides containerized sandboxes with full lifecycle management, checkpointing, artifact storage, and usage tracking.


Architecture

┌─────────────────────────────────────────────────────────────────────────┐
│                              DEVELOPER                                   │
└─────────────────────────────────────────────────────────────────────────┘
         │                           │                          │
         │ 1. Register               │ 2. Use SDK              │ 3. Dashboard
         ▼                           ▼                          ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                         SANDBOX CONTROLLER                               │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  ┌─────────────┐  │
│  │ Registration │  │   Sandbox    │  │  Checkpoint  │  │   Webhook   │  │
│  │   Service    │  │   Manager    │  │   Manager    │  │   Manager   │  │
│  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘  └──────┬──────┘  │
└─────────┼─────────────────┼─────────────────┼─────────────────┼─────────┘
          │                 │                 │                 │
          ▼                 ▼                 ▼                 ▼
┌─────────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────────┐
│   PostgreSQL    │  │ Kubernetes  │  │ Cloud       │  │ External        │
│ (Managed DB)   │  │ (Pods)      │  │ Storage     │  │ Webhooks        │
│                 │  │             │  │ (GCS/S3)    │  │                 │
│ • organizations │  │ • sandbox   │  │ • artifacts │  │ • your-app.com  │
│ • api_keys      │  │   pods      │  │ • checkpts  │  │                 │
│ • usage_events  │  │             │  │             │  │                 │
│ • checkpoints   │  │             │  │             │  │                 │
└─────────────────┘  └─────────────┘  └─────────────┘  └─────────────────┘

Component Details

ComponentTechnologyPurpose
ControllerNode.js + ExpressAPI server, orchestration
DatabasePostgreSQL (managed)Persistent storage
SandboxesKubernetes PodsIsolated execution
StorageGCS/S3Artifact & checkpoint files
DashboardNext.js 14Web UI for management
SDKTypeScriptClient library

User Flow

1. Registration

Developer signs up via API or dashboard:

bash
curl -X POST https://api.sandbox.stateset.app/api/v1/register \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "Ada",
    "last_name": "Lovelace",
    "email": "dev@company.com",
    "organization_name": "Acme Corp",
    "use_case": "CI automation"
  }'

**Response:**

json
{
  "organization": {
    "id": "org_abc123",
    "name": "Acme Corp",
    "slug": "acme-corp",
    "plan": "hobby"
  },
  "user": {
    "id": "user_abc123",
    "email": "dev@company.com",
    "role": "owner"
  },
  "api_key": {
    "key": "sk-sandbox-xxxxxxxxxxxxxxxxxxxx",
    "key_prefix": "sk-sandbox-xxxx",
    "name": "Default API Key"
  }
}

2. SDK Installation

Node.js:

bash
npm install @stateset/sandbox-sdk

Python:

bash
pip install stateset-sandbox

Additional preview SDKs are available in this repo:

  • Rust: sdk-rust/README.md
  • Ruby: sdk-ruby/README.md
  • Go: sdk-go/README.md
  • PHP: sdk-php/README.md
  • Java: sdk-java/README.md
  • Kotlin: sdk-kotlin/README.md
  • Swift: sdk-swift/README.md

3. Basic Usage

typescript
import { StateSetSandbox } from '@stateset/sandbox-sdk';

// Initialize client
const client = new StateSetSandbox({
  baseUrl: 'https://api.sandbox.stateset.app',
  authToken: 'sk-sandbox-xxxxxxxxxxxx'
});

// Create a sandbox
const sandbox = await client.create({
  timeout_seconds: 300, // 5 minutes
  cpus: '1',           // 1 vCPU
  memory: '1Gi',       // 1GB RAM
  env: {
    NODE_ENV: 'production'
  }
});

console.log(`Sandbox created: ${sandbox.sandbox_id}`);
console.log(`Expires at: ${sandbox.expires_at}`);

// Execute commands
const result = await client.execute(sandbox.sandbox_id, {
  command: ['node', '-e', 'console.log("Hello from sandbox!")']
});

console.log(result.stdout);  // "Hello from sandbox!"
console.log(result.exit_code); // 0

// Write files
await client.writeFiles(sandbox.sandbox_id, [
  { path: '/workspace/app.js', content: 'console.log("app");' }
]);

// Read files
const content = await client.readFile(sandbox.sandbox_id, '/workspace/app.js');

// Stop sandbox when done
await client.stop(sandbox.sandbox_id);

Advanced endpoints (checkpoints, artifacts, webhooks, templates) are available via StateSetSandboxExtended:

typescript
import { StateSetSandboxExtended } from '@stateset/sandbox-sdk';

const client = new StateSetSandboxExtended({
  baseUrl: 'https://api.sandbox.stateset.app',
  authToken: 'sk-sandbox-xxxxxxxxxxxx'
});

4. Advanced: Checkpoints

Save and restore sandbox state:

typescript
// Save current state
const checkpoint = await client.createCheckpoint(sandbox.sandbox_id, {
  name: 'after-npm-install',
  description: 'All dependencies installed'
});

console.log(`Checkpoint created: ${checkpoint.id}`);

// Later: Restore to that state (same sandbox)
await client.restoreCheckpoint(sandbox.sandbox_id, checkpoint.id, {
  restore_files: true,
  restore_env: true,
  overwrite: true
});

// Clone a checkpoint
const cloned = await client.cloneCheckpoint(checkpoint.id, 'feature-branch-base');

// Compare checkpoints
const diff = await client.compareCheckpoints(
  checkpoint1.id,
  checkpoint2.id
);

5. Advanced: Artifacts

Upload and download files:

typescript
// Upload file from sandbox to cloud storage
const artifact = await client.uploadArtifact(sandbox.sandbox_id, {
  path: '/workspace/output/report.pdf',
  remote_path: 'reports/2024/report.pdf', // stored under artifacts/<organization-id>/...
  content_type: 'application/pdf',
  expires_in: 86400 * 7  // 7 days
});

// Download artifact to sandbox
await client.downloadArtifact(
  sandbox.sandbox_id,
  artifact.id,
  '/workspace/downloads/report.pdf'
);

// Get presigned URL for direct download
const { url } = await client.getArtifactUrl(artifact.id, 3600);
console.log(`Artifact URL: ${url}`);

6. Advanced: Webhooks

Get notified of sandbox events:

typescript
// Register webhook
const webhook = await client.createWebhook({
  url: 'https://your-app.com/webhooks/sandbox',
  events: [
    'sandbox.created',
    'sandbox.ready',
    'sandbox.error',
    'sandbox.stopped',
    'command.completed',
    'checkpoint.created'
  ],
  secret: 'whsec_your_secret_key'
});

// Test webhook
const testResult = await client.testWebhook(webhook.id);
console.log(`Test successful: ${testResult.success}`);

// List webhook deliveries
const deliveries = await client.getWebhookDeliveries(webhook.id, 10);

**Webhook Payload:**

json
{
  "id": "evt_abc123",
  "event": "sandbox.ready",
  "timestamp": "2024-01-15T12:00:00Z",
  "sandboxId": "sbx_xyz789",
  "orgId": "org_abc123",
  "data": {
    "podIp": "10.0.1.5",
    "startupMs": 1234
  }
}

**Signature Verification:**

typescript
import { createHmac } from 'crypto';

function verifyWebhook(payload: string, signature: string, secret: string): boolean {
  const expected = createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  return `sha256=${expected}` === signature;
}

7. Templates

Create sandboxes from pre-configured templates:

typescript
// List available templates
const templates = await client.listTemplates();

// Create from template
const sandbox = await client.createFromTemplate('python-data-science', {
  timeout_seconds: 600,
  env: {
    DATASET_URL: 'https://example.com/data.csv'
  }
});

**Available Templates:**

TemplateDescriptionPre-installed
python-basicPython 3.11pip, venv
node-basicNode.js 22npm, yarn
go-basicGo 1.22go mod
rust-basicRust stablecargo
python-data-scienceData analysispandas, numpy, matplotlib
node-express-apiWeb APIsexpress, typescript
claude-agentAI agentsclaude-code, MCP servers

API Reference

Authentication

All API requests require authentication via header:

Authorization: ApiKey sk-sandbox-xxxxxxxxxxxx

The organization is inferred from the API key or JWT claims; no org header is required.

Or with JWT:

Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

Endpoints

Registration & API Keys

MethodEndpointDescription
POST/api/v1/registerCreate organization + API key
GET/api/v1/api-keysList API keys
POST/api/v1/api-keysCreate new API key
DELETE/api/v1/api-keys/:idRevoke API key

Sandboxes

MethodEndpointDescription
POST/api/v1/sandbox/createCreate sandbox
GET/api/v1/sandbox/:idGet sandbox details
GET/api/v1/sandbox/:id/statusGet sandbox status (lightweight)
POST/api/v1/sandbox/:id/executeExecute command
POST/api/v1/sandbox/:id/filesWrite files
GET/api/v1/sandbox/:id/files?path=...Read file
POST/api/v1/sandbox/:id/stopStop sandbox
DELETE/api/v1/sandbox/:idDelete sandbox
GET/api/v1/sandboxesList sandboxes

Checkpoints

MethodEndpointDescription
GET/api/v1/checkpointsList checkpoints
GET/api/v1/checkpoints/:idGet checkpoint
POST/api/v1/sandbox/:id/checkpointsCreate checkpoint
POST/api/v1/sandbox/:id/checkpoints/restoreRestore checkpoint
POST/api/v1/checkpoints/:id/cloneClone checkpoint
POST/api/v1/checkpoints/compareCompare checkpoints
DELETE/api/v1/checkpoints/:idDelete checkpoint

Artifacts

MethodEndpointDescription
GET/api/v1/artifactsList artifacts
GET/api/v1/artifacts/:idGet artifact details
GET/api/v1/artifacts/:id/urlGet presigned URL
POST/api/v1/sandbox/:id/artifacts/uploadUpload artifact
POST/api/v1/sandbox/:id/artifacts/downloadDownload artifact
DELETE/api/v1/artifacts/:idDelete artifact

Webhooks

MethodEndpointDescription
GET/api/v1/webhooksList webhooks
POST/api/v1/webhooksCreate webhook
DELETE/api/v1/webhooks/:idDelete webhook
POST/api/v1/webhooks/:id/testTest webhook
GET/api/v1/webhooks/:id/deliveriesGet delivery history

Webhook Events

EventDescription
sandbox.createdSandbox pod created
sandbox.readySandbox is ready for commands
sandbox.stoppedSandbox stopped
sandbox.errorSandbox encountered error
sandbox.timeoutSandbox timed out
command.startedCommand execution started
command.completedCommand finished successfully
command.failedCommand failed
file.writtenFile written to sandbox
checkpoint.createdCheckpoint created
checkpoint.restoredCheckpoint restored
checkpoint.clonedCheckpoint cloned
checkpoint.deletedCheckpoint deleted
artifact.uploadedArtifact uploaded
artifact.deletedArtifact deleted
resource.warningResource usage warning
resource.criticalResource usage critical
mcp.startedMCP server started
mcp.stoppedMCP server stopped

Pricing

Plans

PlanPriceSandboxes/MonthConcurrentMax DurationStorage
Free$05025 min1 GB
Pro$49/mo1,000101 hour50 GB
Team$299/mo10,000502 hours500 GB
EnterpriseCustomUnlimitedCustomCustomCustom

Usage-Based Pricing

ResourceRate
CPU$0.05 / vCPU-hour
Memory$0.02 / GB-hour
Network$0.10 / GB egress
Storage$0.20 / GB-month

Dashboard

Access at: https://sandbox.stateset.app/dashboard

Pages

PagePathDescription
Overview/dashboardActive sandboxes, metrics
Sandboxes/dashboard/sandboxesList and manage sandboxes
API Keys/dashboard/api-keysCreate/revoke keys
Checkpoints/dashboard/checkpointsManage checkpoints
Artifacts/dashboard/artifactsFile storage
Webhooks/dashboard/webhooksEvent notifications
Audit Logs/dashboard/audit-logsActivity history
Usage/dashboard/usageUsage and billing
Settings/dashboard/settingsOrganization settings

Security

API Key Security

  • Keys are hashed (SHA-256) before storage
  • Original key shown only once at creation
  • Keys can have scopes and expiration
  • Rate limiting per key

Sandbox Isolation

  • Each sandbox runs in isolated Kubernetes pod
  • Network policies restrict pod communication
  • Resource limits enforced (CPU, memory)
  • Read-only root filesystem
  • Non-root user execution

Data Protection

  • All data encrypted in transit (TLS)
  • Database encrypted at rest
  • Secrets stored encrypted with KMS
  • Audit logging for compliance

Logs

bash
# Controller logs
kubectl logs -n your-namespace -l app=sandbox-controller -c controller

# Database proxy logs
kubectl logs -n your-namespace -l app=sandbox-controller -c db-proxy

# Sandbox pod logs
kubectl logs -n your-namespace <sandbox-pod-name>

Support

  • GitHub Issues: https://github.com/stateset/sandbox/issues
  • Documentation: https://docs.stateset.io/sandbox
  • Email: support@stateset.io