← Blog

BLOG

Agent Sandbox: The Browser Runtime AI Agents Actually Need

An agent sandbox is the isolated execution environment your AI agent runs in. Learn what it must provide, how to evaluate one, and how to wire it up.

9 min readRemote Browser
Ivory computer towers connected across terracotta platforms in a quiet desert landscape
The infrastructure behind your browserREMOTE BROWSER / ILLUSTRATION

An agent sandbox is the isolated execution environment an AI agent runs inside: its own browser process, its own filesystem and network boundary, its own credentials, and its own lifecycle. For browser-using agents, the sandbox is usually a hosted Chromium instance reachable over the Chrome DevTools Protocol (CDP). The sandbox matters because agents are unpredictable by design — they generate actions at runtime, so the blast radius of a bad action has to be contained by infrastructure, not by prompt instructions. This guide covers what an agent sandbox must provide, how to evaluate one, and how to connect a Playwright agent to a hosted sandbox in production.

What an agent sandbox is (and what it is not)

The term gets used loosely. Three things are often conflated:

  1. A code sandbox — a container or microVM that runs untrusted code (e.g., a Python interpreter the agent writes to).
  2. A browser sandbox — the OS-level Chromium sandbox that isolates renderer processes from the host.
  3. An agent sandbox — the full runtime envelope around an agent: browser session, network egress, credentials, storage, and observability.

When people search for "agent sandbox" in the context of web automation, they usually mean the third. The agent needs to click, type, and navigate real sites, and that activity has to happen somewhere that is not the developer's laptop and not the production API server.

A hosted browser runtime — a service that provisions Chromium sessions on demand and exposes them over CDP — is the most common implementation of an agent sandbox for web tasks. See Remote Browser for AI agents for the runtime-layer view of this.

What an agent sandbox is *not*: it is not a security guarantee on its own. Isolation is a property of the whole stack — the browser process, the network path, the credential store, and the session teardown logic. A sandbox that leaks cookies between sessions is not a sandbox.

Why agents need a sandbox at all

A deterministic Playwright test suite runs the same steps every time. An agent does not. It reads a page, decides on an action, executes it, and repeats. That loop produces failure modes a test suite never hits:

  • Prompt-injected navigation. A page contains text telling the agent to visit an attacker-controlled URL or exfiltrate a token. The agent complies.
  • Credential exposure. The agent is logged into a real account. A malicious page reads the DOM or triggers a download.
  • Runaway sessions. A retry loop opens many tabs or hammers a site until it rate-limits or blocks the source IP.
  • State bleed. Two concurrent tasks share a browser profile and one sees the other's session cookies.

None of these are solved by better prompting. They are solved by the runtime: per-session isolation, scoped credentials, egress control, and hard limits on session lifetime and concurrency.

What a production agent sandbox must provide

Use this as an evaluation checklist. Each item maps to a concrete failure it prevents.

Session isolation

Every agent task should get a fresh browser context or a fresh browser process, depending on the isolation level you need. Context-level isolation separates cookies, localStorage, and cache. Process-level isolation additionally separates memory and any browser-level state. For tasks touching authenticated accounts, process-level isolation is the safer default.

Ask: does the runtime guarantee a clean profile per session, or does it reuse a warm pool that may carry state? Both are valid, but the answer changes your threat model.

CDP access

The sandbox has to be drivable by the tools your agent already uses. CDP is the common denominator: Playwright's connectOverCDP, Puppeteer's connect, and Selenium's CDP bridge all speak it. A runtime that only exposes a proprietary action API forces you to rewrite your agent loop.

The Chrome DevTools Protocol is the authoritative reference for what a CDP endpoint exposes. Confirm that the runtime gives you a WebSocket endpoint, not just an HTTP screenshot API.

Network and egress control

An agent sandbox should let you constrain where the browser can go. At minimum, you want configurable proxy settings so traffic exits from a known region or IP pool. For higher-assurance workloads, you want the ability to block egress to internal networks and metadata endpoints.

This is also where "stealth" claims need scrutiny. Configurable browser settings — user agent, locale, timezone, proxy — are legitimate and useful. Claims of undetectable automation are not something to build a compliance posture on.

Credential scoping

The agent should never hold long-lived credentials in its prompt or its code. The sandbox should support injecting secrets at the session level, scoped to the task, and revoking them at teardown. Persistent profiles are useful for keeping a logged-in state across sessions, but they should be opt-in per workload, not the default.

Lifecycle and usage controls

Sessions must have a maximum lifetime and a clean teardown path. You also need visibility into how many sessions are running and how long they have been up. Metering matters because agent workloads are bursty: a single task might run for 40 seconds or 40 minutes. Check /pricing for how the runtime you choose meters browser time.

Observability

When an agent fails, you need to see what it saw. A live viewer for in-progress sessions and recordings or logs for completed ones turn a 30-minute debugging session into a 2-minute one. This is the difference between a sandbox you can operate and one you can only hope works.

Comparison: local browser vs. self-hosted vs. hosted sandbox

CriterionLocal browser on dev machineSelf-hosted Chromium fleetHosted agent sandbox
Isolation from your machineNoneDepends on container configPer-session by default
Concurrency1–3 realisticallyBounded by your infra budgetProvisioned per session
CDP endpointLocal portYou build and expose itProvided
Proxy / egress controlManualYou configure and maintainConfigurable per session
Persistent profilesLocal profile dirYou build storageManaged, opt-in
Live debuggingYou watch the windowYou build a viewerBuilt-in viewer
Ops burdenLow, but blocks your machineHigh: scaling, patching, cleanupLow
Cost modelFree, but consumes your hardwareFixed infra + engineering timeMetered per browser-hour

The self-hosted column is where most teams start and where most teams stall. Running a Chromium fleet means managing container images, Chromium version pinning, zombie process cleanup, outbound proxy configuration, and a CDP proxy that survives reconnects. That is a real engineering project, and it is not the project you set out to do.

Wiring a Playwright agent to a hosted sandbox

The connection pattern is the same across runtimes that expose CDP. The runtime gives you a WebSocket endpoint; you pass it to connectOverCDP.

import { chromium, Browser, BrowserContext, Page } from "playwright";

interface SandboxSession {
  cdpUrl: string;
  sessionId: string;
}

// Your runtime's session-creation call returns a CDP WebSocket URL.
async function createSandboxSession(): Promise<SandboxSession> {
  const res = await fetch("https://api.remote-browser.dev/v1/sessions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.REMOTE_BROWSER_API_KEY}`,
    },
    body: JSON.stringify({
      // Keep sessions short-lived; the agent should finish or be killed.
      maxDurationSeconds: 600,
      // Route egress through a known region.
      proxy: { region: "us-east" },
    }),
  });
  if (!res.ok) throw new Error(`session create failed: ${res.status}`);
  const data = await res.json();
  return { cdpUrl: data.cdpUrl, sessionId: data.id };
}

async function runAgentTask(task: (page: Page) => Promise<void>) {
  const session = await createSandboxSession();
  let browser: Browser | undefined;
  try {
    browser = await chromium.connectOverCDP(session.cdpUrl);
    // Reuse the sandbox's default context so the agent sees a clean profile.
    const context: BrowserContext = browser.contexts()[0];
    const page: Page = context.pages()[0] ?? (await context.newPage());

    page.setDefaultTimeout(15_000);
    await task(page);
  } finally {
    // Always close the connection; the runtime tears down the session.
    await browser?.close();
  }
}

Three details matter here:

  • `connectOverCDP` returns a `Browser`, not a launched instance. You do not own the process. Closing the connection does not necessarily kill the session — check your runtime's teardown semantics and call its stop endpoint explicitly if needed.
  • Use the existing context. browser.contexts()[0] is the sandbox's default profile. Creating a new context is fine for isolation within a session, but it will not carry the persistent profile if you configured one.
  • Set timeouts on the page, not just the task. Agent loops can hang on a single waitForSelector. A page-level default timeout bounds each step.

For the CLI-driven variant of this pattern, see Remote Browser online.

Sandbox design decisions that bite in production

Warm pools vs. cold starts

Cold-starting a Chromium process takes time. Runtimes that keep a warm pool trade isolation purity for latency. If your workload is latency-sensitive and does not touch authenticated state, warm pools are fine. If it does, ask for a cold, clean session and accept the startup cost.

Persistent profiles are a feature and a risk

Persistent profiles let an agent stay logged in across sessions, which is essential for long-running workflows. They also mean a compromised session can poison future ones. Scope profiles per user or per tenant, never globally, and rotate them on a schedule.

Concurrency limits are real

Every runtime has a concurrency ceiling, whether it is a plan limit or a physical one. Design your agent orchestrator to queue tasks rather than assume unbounded parallel sessions. If you fan out 200 tasks and the runtime allows 25 concurrent browsers, 175 of them will fail or wait — decide which, explicitly.

Teardown is part of the contract

A session that is not explicitly stopped should still be reaped by the runtime after its max duration. Verify this. Leaked sessions are the most common source of surprise bills in browser-agent deployments.

How to evaluate an agent sandbox in an afternoon

You do not need a two-week bake-off. Run this sequence:

  1. Create a session and connect over CDP with the snippet above. Confirm you get a Browser object and can navigate.
  2. Open two sessions concurrently and verify cookie isolation by setting a cookie in one and reading it in the other.
  3. Kill a session mid-task and confirm the runtime reaps it and stops metering.
  4. Check the live viewer while a task runs. Can you see the page? Can you take over?
  5. Inspect the teardown logs. Does the runtime tell you when and why a session ended?

If all five pass, you have a sandbox you can operate. If any fail, you have found the thing that will page you at 2 a.m.

Where the sandbox fits in your architecture

The agent sandbox is a runtime layer, not an application. Your orchestrator owns task planning, retries, and result validation. The sandbox owns browser execution, isolation, and lifecycle. Keeping that boundary clean means you can swap runtimes without rewriting the agent, and you can scale the browser layer independently of the reasoning layer.

Start with the documentation to see the session API, CDP endpoint format, and profile management. If you are still deciding between a local browser and a hosted runtime, remote web browser covers the trade-offs in more depth. And if you want to drive sessions interactively while debugging, remote control browser explains the live-viewer workflow.

The short version: an agent sandbox is the part of your stack that makes it safe to let an LLM click things on the internet. Treat it as infrastructure, evaluate it like infrastructure, and the rest of the agent gets much easier to reason about.