Index of every page on this site: llms.txt
All skills
rivet-dev avatar

/sandbox-agent

@3b027b3 official
by Rivetrivet-dev/skills53 stars
14
Run it yourself

Deploy, configure, and integrate Sandbox Agent - a universal API for orchestrating AI coding agents (Claude Code, Codex, OpenCode, Amp) in sandboxed environments. Use when setting up sandbox-agent server locally or in cloud sandboxes (E2B, Daytona, Docker), creating and managing agent sessions via SDK or API, streaming agent events and handling human-in-the-loop interactions, building chat UIs for coding agents, or understanding the universal schema for agent responses.

Use this Skill: https://skilld.dev/gh/rivet-dev/skills/sandbox-agent

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesmanage-sessions.md

≈1.7k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Manage Sessions

Source: sandbox-agent/docs/content/docs/manage-sessions.mdx Canonical URL: https://rivet.dev/sandbox-agent/docs/manage-sessions Description: Persist and replay agent transcripts across connections.


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.

Recommended approach

  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 prevents duplicate writes and lets you recover from disconnects.

Receiving Events

Two ways to receive events: streaming (recommended) or polling.

Streaming

Use streaming for real-time events with automatic reconnection support.

import { SandboxAgentClient } from "sandbox-agent";

const client = new SandboxAgentClient({
  baseUrl: "http://127.0.0.1:2468",
  agent: "mock",
});

// 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 streaming, poll the events endpoint:

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 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
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<CodingSessionState> => {
    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<CodingSessionVars> => {
    const client = new SandboxAgentClient({
  baseUrl: c.state.baseUrl,
  agent: "mock",
});
    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
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();
import { createRivetKit } from "@rivetkit/react";

const { useActor } = createRivetKit();

function CodingSession() {
  const [messages, setMessages] = useState<AgentEvent[]>([]);
  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 (
    <div>
      {messages.map((msg, i) => (
        <div key={i}>{JSON.stringify(msg)}</div>
      ))}
      <button onClick={() => sendPrompt("Build a login page")}>
        Send Prompt
      </button>
    </div>
  );
}

PostgreSQL

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

// 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 event stream may disconnect due to network issues. Handle reconnection gracefully:

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);
    }
  }
}

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

3 alerts1d5 checks · Risk HIGH
  • Gen Agent Trust Hub1d

    The skill provides a universal API for orchestrating coding agents in sandboxed environments. It includes instructions for installing its own server components and various development tools using piped shell execution (remote code execution). The tool possesses broad capabilities for arbitrary command execution, filesystem access, and desktop control, and it features mechanisms for the agent to extract and export LLM credentials from the local host environment.

  • Socket1d

    1 alert: gptAnomaly

  • Snyk1d

    Risk: CRITICAL · 2 issues

  • Runlayer8mo

    34/41 files flagged

  • ZeroLeaks7mo

    1 finding · Score: 82/100

Signed by skilld at 3b027b3. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated 2 days ago
  • TypeScript
  • sandbox-agent
  • api-orchestration
  • ai-agents
  • claude
  • openai
  • e2b
  • daytona
  • docker
  • session-management

README badge

README badge for rivet-dev/skills/sandbox-agent

Provides a universal API and orchestration layer for running Claude, Codex, OpenCode, and Amp coding agents in sandboxed environments (E2B, Daytona, Docker). Covers server setup, session management, event streaming, and integration with chat UIs and LLM providers.

Generated from the current SKILL.md.

Which coding agents does Sandbox Agent support?
Sandbox Agent provides a universal API for Claude Code, Codex, OpenCode, and Amp. It also supports a mock agent for testing without provider credentials.
What sandbox providers can I deploy to?
Sandbox Agent runs on E2B, Daytona, Docker, local development, and cloud platforms like Vercel and Cloudflare. You can also run it as a local subprocess via Node.js or Bun.
Do I need API keys to test Sandbox Agent?
No. Use the mock agent for SDK and integration testing without Anthropic or OpenAI credentials. For real agents, you'll need to set ANTHROPIC_API_KEY and/or OPENAI_API_KEY.
Can I use this for per-user billing or multi-tenant setups?
Yes. Sandbox Agent supports LLM credential gateways like OpenRouter, LiteLLM, and Portkey for per-tenant token tracking, budget enforcement, and usage-based billing.
What persistence options are available for agent sessions?
Sessions can be persisted in-memory, to Rivet Actor state, IndexedDB, SQLite, or Postgres depending on your deployment target.

Generated from the current SKILL.md. These answers refresh after source changes.