BLOG
Agent Sandboxing: The Browser Runtime Layer That Holds
Agent sandboxing explained: what an isolated browser runtime must provide, how CDP sessions work, and the criteria that matter in production.

Agent sandboxing is the practice of running an AI agent's browser work inside an isolated, disposable, remotely hosted environment rather than on the machine that runs the agent loop. The sandbox is not a security feature bolted on at the end. It is the execution boundary that determines what an agent can touch, what survives a crash, and what you can audit after the fact. For browser-using agents, that boundary is a Chromium session with its own profile, its own network identity, and its own lifecycle — reachable over the Chrome DevTools Protocol (CDP) and nothing else.
This guide covers what agent sandboxing actually requires, where naive implementations break, and how to evaluate a runtime before you put it behind production traffic.
What agent sandboxing has to isolate
Most teams start with a mental model of "run the browser somewhere else." That is the easy half. The hard half is deciding what the isolation boundary contains. A useful sandbox for browser agents isolates at least five things:
- Process and filesystem. The agent's browser must not share a filesystem with your application server, your CI runner, or another tenant's session. Downloads, uploads, and temp files stay inside the sandbox.
- Credentials and cookies. Session state — logged-in cookies, localStorage, saved passwords — should live in a profile scoped to one agent or one workflow, not in a shared browser instance.
- Network identity. Egress IP, proxy configuration, and DNS resolution belong to the sandbox, not the host. This matters when a task depends on a specific region or when you need to correlate traffic to a single agent run.
- Compute. A runaway page with a memory leak or a tight
requestAnimationFrameloop should degrade one session, not the host. - Lifecycle. The sandbox must be creatable and destroyable on demand, with a clear answer to "what happens to this session if the agent process dies mid-task?"
If any of those five leak across sessions, you do not have agent sandboxing. You have a shared browser with extra steps.
Why local Chrome is a weak sandbox
Running Chromium on the same host as the agent is the default because it is the path of least resistance: chromium.launch() and you are done. It is also the configuration that produces the most incident reports.
The failure modes are predictable. A headless Chrome process left behind by a crashed agent keeps holding a profile lock, and the next run fails with a cryptic "profile in use" error. Two agents writing to the same user data directory corrupt each other's cookies. A page that triggers a download writes into the application's working directory. A memory-hungry page takes down the container that also serves your API. And when something goes wrong, there is no recording, no live view, and no way to reconstruct what the agent saw.
Local Chrome also makes concurrency awkward. Each browser instance costs a few hundred megabytes of resident memory plus CPU for rendering, and the cost scales linearly with parallel agents. You end up building a scheduler, a pool, and a cleanup job — which is to say, you end up building a worse version of a hosted runtime.
The sandbox contract: what a hosted session gives you
A hosted browser runtime replaces the local process with a remote session you connect to over CDP. The contract is narrow and worth stating explicitly, because it is what you should test against any provider.
| Concern | Local Chrome | Hosted sandbox session |
|---|---|---|
| Isolation | Shared host, shared profile by default | Per-session process, profile, and network namespace |
| Connection | In-process launch | WebSocket CDP endpoint |
| State persistence | Manual userDataDir management | Named persistent profiles, opt-in |
| Observability | Screenshots you remember to take | Live viewer plus session recordings |
| Failure recovery | Orphaned processes, locked profiles | Session teardown on disconnect or timeout |
| Concurrency | Bounded by host memory | Bounded by your plan's session limits |
| Credential handling | Cookies on disk next to your code | Cookies inside the sandbox profile |
| Cost model | Fixed infra plus ops time | Metered per browser-hour |
The right-hand column is not automatically better. It is better *if* the provider honors the contract: real isolation, a stable CDP endpoint, and predictable teardown. A hosted runtime that shares profiles across tenants is worse than local Chrome, because you have added a network hop and lost control of the blast radius.
Connecting an agent to a sandboxed session
The connection path is the same CDP surface Playwright and Puppeteer already speak. You request a session, get a WebSocket debugger URL, and connect. The Playwright documentation for `browserType.connectOverCDP` is the authoritative reference for the client side.
import { chromium, type Browser, type BrowserContext } from "playwright";
type SandboxSession = {
id: string;
cdpUrl: string;
};
async function openSandboxedSession(): Promise<{
browser: Browser;
context: BrowserContext;
session: SandboxSession;
}> {
// Your runtime's session-creation endpoint. Exact shape is provider-specific;
// check /documentation for the current request and response schema.
const res = await fetch(`${process.env.BROWSER_API_URL}/sessions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.BROWSER_API_KEY}`,
},
body: JSON.stringify({
// Persistent profiles keep cookies and storage across runs.
profile: "checkout-agent-prod",
// Region and proxy settings are configurable per session.
region: "us-east",
timeoutSeconds: 900,
}),
});
if (!res.ok) {
throw new Error(`session create failed: ${res.status} ${await res.text()}`);
}
const session = (await res.json()) as SandboxSession;
const browser = await chromium.connectOverCDP(session.cdpUrl, {
timeout: 30_000,
});
// A hosted session typically exposes one default context.
const context = browser.contexts()[0] ?? (await browser.newContext());
return { browser, context, session };
}
async function runTask() {
const { browser, context } = await openSandboxedSession();
try {
const page = await context.newPage();
await page.goto("https://example.com", { waitUntil: "domcontentloaded" });
// ...agent actions...
} finally {
// Closing the CDP connection releases the client side.
// Session teardown is governed by the runtime's timeout or an explicit stop call.
await browser.close();
}
}Two details matter more than they look. First, connectOverCDP gives you a Browser handle but not a launched process — browser.close() disconnects, it does not necessarily terminate the remote session. Confirm your provider's teardown semantics and call the explicit stop endpoint when a task finishes early, or you will pay for idle browser-hours. Second, the default context is where your cookies live. If you create a new context per task, you lose the persistence that makes profiles useful.
Production criteria for an agent sandbox
Once the connection works, the questions shift from "can it connect" to "will it hold under load." These are the criteria worth testing before you commit.
Session lifecycle and teardown
Ask what happens when the agent process is killed, the network drops, or the task hangs. A good runtime has a hard timeout, terminates the session, and releases the profile lock. A bad one leaves the session running until you notice the bill. Test this deliberately: kill the client mid-task and watch whether the session disappears.
Profile semantics
Persistent profiles are the difference between an agent that logs in once and one that logs in every run. But persistence has a cost: a corrupted profile propagates failures across every future run. Look for the ability to reset a profile, version it, and scope it per environment. If you run staging and production agents, they must not share a profile.
Network controls
Proxy configuration, region selection, and egress identity should be per-session settings, not global. This is also where careful wording matters: a runtime may offer configurable browser and network settings that reduce obvious automation signals, but you should verify what is actually configurable rather than assume stealth is automatic. Treat stealth as a set of concrete, testable settings — user agent, timezone, locale, proxy — and validate them against your target sites.
Observability
The live viewer is the single most useful debugging tool in this category. When an agent fails, you want to see the page it saw, not a stack trace. Session recordings extend that to post-hoc analysis. Both should be available without extra instrumentation on your side.
Isolation guarantees
Ask directly: does each session get its own process and filesystem? Are profiles shared across tenants? Is there any path by which one session's cookies or downloads reach another? For regulated workloads, ask about data retention and whether recordings are stored.
Usage controls
Metered browser-hours are the standard model, and the number that matters is not the headline rate but the ratio of useful task time to billed session time. Idle sessions, retries, and hung tasks all bill. Look for concurrency limits you can reason about and a way to cap spend. Current rates and plan limits are on the pricing page.
Where sandboxing fits in the agent stack
It helps to separate three layers that are often conflated:
- The agent framework decides what to do — planning, tool selection, retries. Browser-use, Stagehand, and custom loops live here.
- The automation library translates intent into browser actions — Playwright, Puppeteer, Selenium.
- The sandbox provides the browser process, the profile, and the network identity.
Agent sandboxing is layer three. It is deliberately dumb: it does not plan, it does not retry, it does not know what a task is. That separation is what makes it composable. You can swap the agent framework without touching the sandbox, and you can run the same agent against a local browser in development and a hosted session in production, provided both speak CDP.
This is also why "sandbox" and "cloud browser" are not quite synonyms in practice. A cloud browser is the product; agent sandboxing is the property you are buying. Two providers can both sell cloud browsers while only one gives you real per-session isolation. For a broader treatment of the runtime layer, see Remote browsers for AI agents.
Common mistakes
- Sharing one session across concurrent tasks. Two agents driving the same page will interleave actions and corrupt each other's state. One session per task, or one session per agent with a queue.
- Treating the CDP URL as a secret you can log. The debugger URL grants full control of the session. Treat it like a credential and keep it out of logs and error reports.
- Skipping teardown on the happy path. Explicitly stop sessions when tasks complete. Timeout-based cleanup is a backstop, not a strategy.
- Assuming persistence is free. Persistent profiles accumulate state, including stale cookies and expired tokens. Rotate them on a schedule.
- Testing only against friendly sites. The sandbox's network and browser settings matter most on sites that challenge automation. Validate early.
Getting started
The shortest path is to run one real task end to end: create a session, connect over CDP, complete a multi-step flow that requires a login, then inspect the recording. If the session tears down cleanly, the profile persists correctly on a second run, and the live viewer showed you what the agent saw, the sandbox is doing its job.
From there, the work is operational: naming profiles per environment, setting timeouts that match your task durations, and watching the ratio of billed time to useful time. The documentation covers session creation, profile management, and the CDP connection details; running a remote browser online walks through the first-session setup if you want a guided path.
Agent sandboxing is not a feature you enable. It is a boundary you design, and the browser runtime is where that boundary becomes real.