Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. πŸ”₯

Nick: (#2822)

Nicolasff07ff289feb
diff --git a/apps/api/requests/v2/browser.requests.http b/apps/api/requests/v2/browser.requests.http
new file mode 100644
index 000000000..5dde2b379
--- /dev/null
+++ b/apps/api/requests/v2/browser.requests.http
@@ -0,0 +1,67 @@
+s# Pick your baseUrl here:
+@baseUrl = http://localhost:3002
+# @baseUrl = https://api.firecrawl.dev
+
+### Create Browser Session (defaults)
+POST {{baseUrl}}/v2/browser HTTP/1.1
+Authorization: Bearer {{$dotenv TEST_API_KEY}}
+content-type: application/json
+
+{}
+
+### Create Browser Session (with options)
+POST {{baseUrl}}/v2/browser HTTP/1.1
+Authorization: Bearer {{$dotenv TEST_API_KEY}}
+content-type: application/json
+
+{
+ "ttlTotal": 600,
+ "ttlWithoutActivity": 120,
+ "streamWebView": false
+}
+
+### Create Browser Session (with webview streaming)
+POST {{baseUrl}}/v2/browser HTTP/1.1
+Authorization: Bearer {{$dotenv TEST_API_KEY}}
+content-type: application/json
+
+{
+ "ttlTotal": 300,
+ "streamWebView": true
+}
+
+### Execute Code (Python) β€” replace BROWSER_ID with actual browserId
+@browserId = REPLACE_WITH_BROWSER_ID
+
+POST {{baseUrl}}/v2/browser/execute HTTP/1.1
+Authorization: Bearer {{$dotenv TEST_API_KEY}}
+content-type: application/json
+
+{
+ "browserId": "{{browserId}}",
+ "code": "await page.goto(\"https://docs.firecrawl.dev\")\nprint(await page.title())",
+ "language": "python"
+}
+
+### Execute Code (JS) β€” replace BROWSER_ID with actual browserId
+POST {{baseUrl}}/v2/browser/execute HTTP/1.1
+Authorization: Bearer {{$dotenv TEST_API_KEY}}
+content-type: application/json
+
+{
+ "browserId": "{{browserId}}",
+ "code": "await page.goto('https://example.com');\nconst title = await page.title();\nconsole.log(title);",
+ "language": "js"
+}
+
+### Delete Browser Session β€” replace BROWSER_ID with actual browserId
+DELETE {{baseUrl}}/v2/browser HTTP/1.1
+Authorization: Bearer {{$dotenv TEST_API_KEY}}
+content-type: application/json
+
+{
+ "browserId": "{{browserId}}"
+}
+
+### WebSocket β€” webview stream (use a WS client, e.g. wscat)
+# wscat -c "ws://localhost:3002/v2/browser/{{browserId}}" -H "Authorization: Bearer YOUR_API_KEY"
diff --git a/apps/api/src/__tests__/snips/v2/browser.test.ts b/apps/api/src/__tests__/snips/v2/browser.test.ts
new file mode 100644
index 000000000..d46841181
--- /dev/null
+++ b/apps/api/src/__tests__/snips/v2/browser.test.ts
@@ -0,0 +1,131 @@
+import { describeIf, HAS_FIRE_ENGINE, TEST_SELF_HOST } from "../lib";
+import { scrapeTimeout, idmux, Identity, TEST_API_URL } from "./lib";
+import request from "./lib";
+import {
+ BrowserCreateRequest,
+ BrowserCreateResponse,
+ BrowserExecuteRequest,
+ BrowserExecuteResponse,
+ BrowserDeleteRequest,
+ BrowserDeleteResponse,
+} from "../../../controllers/v2/browser";
+
+let identity: Identity;
+
+beforeAll(async () => {
+ identity = await idmux({
+ name: "browser",
+ concurrency: 10,
+ credits: 100000,
+ });
+}, 10000);
+
+// Browser feature requires fire-engine and sandbox β€” skip in self-hosted
+describeIf(!TEST_SELF_HOST && HAS_FIRE_ENGINE)("Browser API", () => {
+ // ---------------------------------------------------------------
+ // Helpers
+ // ---------------------------------------------------------------
+
+ async function browserCreateRaw(body: Partial<BrowserCreateRequest>) {
+ return await request(TEST_API_URL)
+ .post("/v2/browser")
+ .set("Authorization", `Bearer ${identity.apiKey}`)
+ .set("Content-Type", "application/json")
+ .send(body);
+ }
+
+ async function browserExecuteRaw(body: BrowserExecuteRequest) {
+ return await request(TEST_API_URL)
+ .post("/v2/browser/execute")
+ .set("Authorization", `Bearer ${identity.apiKey}`)
+ .set("Content-Type", "application/json")
+ .send(body);
+ }
+
+ async function browserDeleteRaw(body: BrowserDeleteRequest) {
+ return await request(TEST_API_URL)
+ .delete("/v2/browser")
+ .set("Authorization", `Bearer ${identity.apiKey}`)
+ .set("Content-Type", "application/json")
+ .send(body);
+ }
+
+ // ---------------------------------------------------------------
+ // Tests
+ // ---------------------------------------------------------------
+
+ it(
+ "creates a browser session, executes code, then deletes it (happy path)",
+ async () => {
+ // 1. Create session
+ const createRes = await browserCreateRaw({});
+ expect(createRes.statusCode).toBe(200);
+ expect(createRes.body.success).toBe(true);
+ expect(typeof createRes.body.browserId).toBe("string");
+ expect(typeof createRes.body.cdpUrl).toBe("string");
+
+ const { browserId } = createRes.body as BrowserCreateResponse;
+
+ // 2. Execute code β€” navigate to example.com and get the title
+ const execRes = await browserExecuteRaw({
+ browserId: browserId!,
+ code: `
+await page.goto("https://example.com")
+print(await page.title())
+`,
+ language: "python",
+ });
+
+ expect(execRes.statusCode).toBe(200);
+ expect(execRes.body.success).toBe(true);
+ expect(typeof execRes.body.result).toBe("string");
+ expect(execRes.body.result).toContain("Example Domain");
+
+ // 3. Delete session
+ const deleteRes = await browserDeleteRaw({
+ browserId: browserId!,
+ });
+ expect(deleteRes.statusCode).toBe(200);
+ expect(deleteRes.body.success).toBe(true);
+ },
+ scrapeTimeout * 2,
+ );
+
+ it(
+ "returns 404 when executing code on a non-existent session",
+ async () => {
+ const execRes = await browserExecuteRaw({
+ browserId: "00000000-0000-7000-8000-000000000000",
+ code: "print('hello')",
+ language: "python",
+ });
+
+ expect(execRes.statusCode).toBe(404);
+ expect(execRes.body.success).toBe(false);
+ },
+ scrapeTimeout,
+ );
+
+ it(
+ "returns 404 when deleting a non-existent session",
+ async () => {
+ const deleteRes = await browserDeleteRaw({
+ browserId: "00000000-0000-7000-8000-000000000000",
+ });
+
+ expect(deleteRes.statusCode).toBe(404);
+ expect(deleteRes.body.success).toBe(false);
+ },
+ scrapeTimeout,
+ );
+
+ it("rejects unauthenticated requests", async () => {
+ const res = await request(TEST_API_URL)
+ .post("/v2/browser")
+ .set("Content-Type", "application/json")
+ .send({});
+
+ expect(res.statusCode).toBe(401);
+ expect(res.body.success).toBe(false);
+ });
+});
diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts
index 8b56294d3..bb9d6e198 100644
--- a/apps/api/src/config.ts
+++ b/apps/api/src/config.ts
@@ -219,6 +219,11 @@ const configSchema = z.object({
EXTRACT_V3_BETA_URL: z.string().optional(),
AGENT_INTEROP_SECRET: z.string().optional(),
+ // Browser / Sandbox
+ SANDBOX_API_URL: z.string().default("http://localhost:3002"),
+ SANDBOX_POD_URL_TEMPLATE: z.string().optional(),
+ CDP_PROXY_URL: z.string().default("ws://localhost:9222"),
+
NUQ_PREFETCH_WORKER_HEARTBEAT_URL: z.string().optional(),
});
diff --git a/apps/api/src/controllers/v1/types.ts b/apps/api/src/controllers/v1/types.ts
index c161731e8..7ef630eac 100644
--- a/apps/api/src/controllers/v1/types.ts
+++ b/apps/api/src/controllers/v1/types.ts
@@ -1246,6 +1246,7 @@ export type AuthCreditUsageChunk = {
extractStatus: number;
extractAgentPreview?: number;
scrapeAgentPreview?: number;
+ browser?: number;
};
concurrency: number;
flags: TeamFlags;
@@ -1267,6 +1268,7 @@ export type TeamFlags = {
skipCountryCheck?: boolean;
extractV3Beta?: boolean;
agentBeta?: boolean;
+ browserBeta?: boolean;
bypassCreditChecks?: boolean;
debugBranding?: boolean;
} | null;
diff --git a/apps/api/src/controllers/v2/browser.ts b/apps/api/src/controllers/v2/browser.ts
new file mode 100644
index 000000000..aae8a68c5
--- /dev/null
+++ b/apps/api/src/controllers/v2/browser.ts
@@ -0,0 +1,458 @@
+import { v7 as uuidv7 } from "uuid";
+import { Response } from "express";
+import { z } from "zod";
+import { logger as _logger } from "../../lib/logger";
+import { config } from "../../config";
+import {
+ createSandboxClient,
+ Workspace,
+ CodeContext,
+ Execution,
+} from "../../lib/sandbox-client";
+import { RequestWithAuth } from "./types";
+
+// ---------------------------------------------------------------------------
+// Zod schemas
+// ---------------------------------------------------------------------------
+
+const browserCreateRequestSchema = z.object({
+ ttlTotal: z.number().min(30).max(3600).default(300),
+ ttlWithoutActivity: z.number().min(10).max(3600).optional(),
+ streamWebView: z.boolean().default(false),
+});
+
+export type BrowserCreateRequest = z.infer<typeof browserCreateRequestSchema>;
+
+export interface BrowserCreateResponse {
+ success: boolean;
+ browserId?: string;
+ cdpUrl?: string;
+ error?: string;
+}
+
+const browserExecuteRequestSchema = z.object({
+ browserId: z.string(),
+ code: z.string().min(1).max(100_000),
+ language: z.enum(["python", "js"]).default("python"),
+});
+
+export type BrowserExecuteRequest = z.infer<typeof browserExecuteRequestSchema>;
+
+export interface BrowserExecuteResponse {
+ success: boolean;
+ result?: string;
+ error?: string;
+}
+
+const browserDeleteRequestSchema = z.object({
+ browserId: z.string(),
+});
+
+export type BrowserDeleteRequest = z.infer<typeof browserDeleteRequestSchema>;
+
+export interface BrowserDeleteResponse {
+ success: boolean;
+ error?: string;
+}
+
+// ---------------------------------------------------------------------------
+// In-memory session store
+// ---------------------------------------------------------------------------
+
+interface BrowserSession {
+ browserId: string;
+ teamId: string;
+ workspace: Workspace;
+ context: CodeContext;
+ cdpUrl: string;
+ cdpPath: string;
+ streamWebView: boolean;
+ createdAt: number;
+ lastActivity: number;
+ ttlTotal: number;
+ ttlWithoutActivity?: number;
+ destroyed: boolean;
+}
+
+const sessions = new Map<string, BrowserSession>();
+
+/** Periodic cleanup of expired sessions */
+// setInterval(() => {
+// const now = Date.now();
+// for (const [id, session] of sessions) {
+// if (session.destroyed) {
+// sessions.delete(id);
+// continue;
+// }
+// const totalExpired = now - session.createdAt > session.ttlTotal * 1000;
+// const activityExpired =
+// session.ttlWithoutActivity !== undefined &&
+// now - session.lastActivity > session.ttlWithoutActivity * 1000;
+// if (totalExpired || activityExpired) {
+// destroySession(session).catch(() => {});
+// }
+// }
+// }, 15_000);
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function getSandboxClient() {
+ return createSandboxClient({
+ baseUrl: config.SANDBOX_API_URL!,
+ podUrlTemplate: config.SANDBOX_POD_URL_TEMPLATE,
+ });
+}
+
+/**
+ * Extract the printable output from a sandbox Execution result.
+ */
+function executionToString(exec: Execution): string {
+ const parts: string[] = [];
+ return exec.text ?? "";
+
+ // // Collect stdout log lines
+ // if (exec.logs.stdout.length > 0) {
+ // parts.push(exec.logs.stdout.join("\n"));
+ // }
+
+ // // Collect stderr log lines
+ // if (exec.logs.stderr.length > 0) {
+ // parts.push(exec.logs.stderr.join("\n"));
+ // }
+
+ // // Collect result text
+ // if (exec.text) {
+ // parts.push(exec.text);
+ // }
+
+ // for (const r of exec.results) {
+ // if (r.text) {
+ // parts.push(r.text);
+ // }
+ // }
+
+ // // Collect error info
+ // if (exec.error) {
+ // parts.push(
+ // `${exec.error.name}: ${exec.error.value}${exec.error.traceback ? "\n" + exec.error.traceback : ""}`,
+ // );
+ // }
+
+ // return parts.join("\n");
+}
+
+async function destroySession(session: BrowserSession) {
+ if (session.destroyed) return;
+ session.destroyed = true;
+
+ const logger = _logger.child({
+ browserId: session.browserId,
+ module: "browser",
+ });
+
+ try {
+ // Tell the sandbox to close the browser
+ await session.context.runCode("await browser.close()").catch(() => {}); // best-effort
+
+ // Tear down the CDP session on fire-engine
+ if (config.FIRE_ENGINE_BETA_URL) {
+ await fetch(
+ `${config.FIRE_ENGINE_BETA_URL}/cdp-session/${session.browserId}`,
+ { method: "DELETE" },
+ ).catch(() => {});
+ }
+
+ // Destroy the sandbox workspace
+ await session.workspace.destroy().catch(() => {});
+
+ logger.info("Browser session destroyed");
+ } catch (err) {
+ logger.warn("Error while destroying browser session", { error: err });
+ } finally {
+ sessions.delete(session.browserId);
+ }
+}
+
+function getSession(browserId: string): BrowserSession | undefined {
+ return sessions.get(browserId);
+}
+
+// ---------------------------------------------------------------------------
+// Controllers
+// ---------------------------------------------------------------------------
+
+export async function browserCreateController(
+ req: RequestWithAuth<{}, BrowserCreateResponse, BrowserCreateRequest>,
+ res: Response<BrowserCreateResponse>,
+) {
+ if (!req.acuc?.flags?.browserBeta) {
+ return res.status(403).json({
+ success: false,
+ error:
+ "Browser is currently in beta. Please contact [email protected] to request access.",
+ });
+ }
+
+ const browserId = uuidv7();
+ const logger = _logger.child({
+ browserId,
+ teamId: req.auth.team_id,
+ module: "api/v2",
+ method: "browserCreateController",
+ });
+
+ req.body = browserCreateRequestSchema.parse(req.body);
+
+ const { ttlTotal, ttlWithoutActivity, streamWebView } = req.body;
+
+ if (!config.FIRE_ENGINE_BETA_URL) {
+ return res.status(503).json({
+ success: false,
+ error:
+ "Browser feature is not configured (FIRE_ENGINE_BETA_URL is missing).",
+ });
+ }
+
+ if (!config.SANDBOX_API_URL) {
+ return res.status(503).json({
+ success: false,
+ error: "Browser feature is not configured (SANDBOX_API_URL is missing).",
+ });
+ }
+
+ logger.info("Creating browser session", {
+ ttlTotal,
+ ttlWithoutActivity,
+ streamWebView,
+ });
+
+ // 1. Acquire a CDP session from fire-engine
+ const cdpRes = await fetch(`${config.FIRE_ENGINE_BETA_URL}/cdp-session`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ country: "us",
+ mobileProxy: false,
+ useProxy: true,
+ }),
+ });
+
+ if (!cdpRes.ok) {
+ const text = await cdpRes.text();
+ logger.error("Failed to create CDP session", {
+ status: cdpRes.status,
+ text,
+ });
+ return res.status(502).json({
+ success: false,
+ error: "Failed to create browser CDP session.",
+ });
+ }
+
+ const { browserId: feBrowserId, cdpPath } = (await cdpRes.json()) as {
+ browserId: string;
+ cdpPath: string;
+ };
+
+ // 2. Create a sandbox workspace and context
+ const client = getSandboxClient();
+ const workspace = await client.createWorkspace({ ttlSeconds: ttlTotal });
+ const ctx = await workspace.createContext();
+
+ // 3. Bridge CDP into the sandbox
+ await ctx.enableBrowser(cdpPath);
+
+ // 4. Initialize Playwright inside the sandbox
+ // TODO: fix - setup session reuse for context and page
+ const initExec = await ctx.runCode(`
+from playwright.async_api import async_playwright
+
+__pw__ = await async_playwright().start()
+browser = await __pw__.chromium.connect_over_cdp("ws://127.0.0.1:9222")
+context = await browser.new_context()
+page = await context.new_page()
+`);
+
+ if (initExec.error) {
+ // Cleanup on failure
+ await workspace.destroy().catch(() => {});
+ if (config.FIRE_ENGINE_BETA_URL) {
+ await fetch(`${config.FIRE_ENGINE_BETA_URL}/cdp-session/${feBrowserId}`, {
+ method: "DELETE",
+ }).catch(() => {});
+ }
+
+ return res.status(502).json({
+ success: false,
+ error: `Failed to initialize browser: ${initExec.error.name}: ${initExec.error.value}`,
+ });
+ }
+
+ // Build the user-facing CDP URL
+ const cdpUrl = `${config.CDP_PROXY_URL}${cdpPath}`;
+
+ // 5. Store the session
+ const session: BrowserSession = {
+ browserId: feBrowserId,
+ teamId: req.auth.team_id,
+ workspace,
+ context: ctx,
+ cdpUrl,
+ cdpPath,
+ streamWebView,
+ createdAt: Date.now(),
+ lastActivity: Date.now(),
+ ttlTotal,
+ ttlWithoutActivity,
+ destroyed: false,
+ };
+
+ sessions.set(feBrowserId, session);
+
+ logger.info("Browser session created", {
+ browserId: feBrowserId,
+ cdpUrl,
+ });
+
+ return res.status(200).json({
+ success: true,
+ browserId: feBrowserId,
+ cdpUrl,
+ });
+}
+
+export async function browserExecuteController(
+ req: RequestWithAuth<{}, BrowserExecuteResponse, BrowserExecuteRequest>,
+ res: Response<BrowserExecuteResponse>,
+) {
+ if (!req.acuc?.flags?.browserBeta) {
+ return res.status(403).json({
+ success: false,
+ error:
+ "Browser is currently in beta. Please contact [email protected] to request access.",
+ });
+ }
+
+ req.body = browserExecuteRequestSchema.parse(req.body);
+
+ const { browserId, code, language } = req.body;
+
+ const logger = _logger.child({
+ browserId,
+ teamId: req.auth.team_id,
+ module: "api/v2",
+ method: "browserExecuteController",
+ });
+
+ const session = sessions.get(browserId);
+
+ if (!session) {
+ return res.status(404).json({
+ success: false,
+ error: "Browser session not found.",
+ });
+ }
+
+ if (session.teamId !== req.auth.team_id) {
+ return res.status(403).json({
+ success: false,
+ error: "Forbidden.",
+ });
+ }
+
+ if (session.destroyed) {
+ return res.status(410).json({
+ success: false,
+ error: "Browser session has been destroyed.",
+ });
+ }
+
+ session.lastActivity = Date.now();
+
+ logger.info("Executing code in browser session", { language });
+
+ // The sandbox currently only accepts Python via runCode.
+ // For JS, we could wrap it differently in the future.
+ console.log(`[browser-execute] Running code for session ${browserId}:`, code);
+ const exec = await session.context.runCode(code);
+
+ const output = executionToString(exec);
+
+ console.log(
+ `[browser-execute] Execution result for session ${browserId}:`,
+ JSON.stringify(
+ {
+ text: exec.text,
+ results: exec.results,
+ logs: exec.logs,
+ error: exec.error,
+ outputLength: output.length,
+ },
+ null,
+ 2,
+ ),
+ );
+
+ if (exec.error) {
+ return res.status(200).json({
+ success: true,
+ result: output,
+ error: `${exec.error.name}: ${exec.error.value}`,
+ });
+ }
+
+ return res.status(200).json({
+ success: true,
+ result: output,
+ });
+}
+
+export async function browserDeleteController(
+ req: RequestWithAuth<{}, BrowserDeleteResponse, BrowserDeleteRequest>,
+ res: Response<BrowserDeleteResponse>,
+) {
+ if (!req.acuc?.flags?.browserBeta) {
+ return res.status(403).json({
+ success: false,
+ error:
+ "Browser is currently in beta. Please contact [email protected] to request access.",
+ });
+ }
+
+ req.body = browserDeleteRequestSchema.parse(req.body);
+
+ const { browserId } = req.body;
+
+ const logger = _logger.child({
+ browserId,
+ teamId: req.auth.team_id,
+ module: "api/v2",
+ method: "browserDeleteController",
+ });
+
+ const session = sessions.get(browserId);
+
+ if (!session) {
+ return res.status(404).json({
+ success: false,
+ error: "Browser session not found.",
+ });
+ }
+
+ if (session.teamId !== req.auth.team_id) {
+ return res.status(403).json({
+ success: false,
+ error: "Forbidden.",
+ });
+ }
+
+ logger.info("Deleting browser session");
+
+ await destroySession(session);
+
+ return res.status(200).json({
+ success: true,
+ });
+}
diff --git a/apps/api/src/lib/sandbox-client.ts b/apps/api/src/lib/sandbox-client.ts
new file mode 100644
index 000000000..bbb6b2bb5
--- /dev/null
+++ b/apps/api/src/lib/sandbox-client.ts
@@ -0,0 +1,357 @@
+/**
+ * Standalone client for the Sandbox API.
+ * Ported from the sandbox service's own client code.
+ */
+
+interface TraceHeaders {
+ [key: string]: string;
+}
+
+interface SandboxClientConfig {
+ baseUrl: string;
+ /** Request timeout in ms (default: 120000 for browser operations) */
+ timeout?: number;
+ /**
+ * Headless service base for direct pod routing (StatefulSet).
+ * Format: "sandbox-headless.namespace.svc.cluster.local:3001"
+ */
+ headlessService?: string;
+ /**
+ * URL template for direct pod routing with custom hostname patterns.
+ * Placeholder: {pod} = full pod name from composite ID (e.g., "sandbox-0")
+ * Takes precedence over headlessService if both are set.
+ */
+ podUrlTemplate?: string;
+ /**
+ * Optional callback to get trace headers for distributed tracing.
+ */
+ getTraceHeaders?: () => TraceHeaders | undefined;
+}
+
+interface ExecutionError {
+ name: string;
+ value: string;
+ traceback?: string;
+}
+
+export interface Execution {
+ text?: string;
+ results: Array<{ text?: string; isMainResult?: boolean }>;
+ logs: { stdout: string[]; stderr: string[] };
+ error?: ExecutionError;
+}
+
+interface ExecResult {
+ exitCode: number;
+ stdout: string;
+ stderr: string;
+}
+
+export class SandboxClient {
+ readonly baseUrl: string;
+ private timeout: number;
+ private headlessService?: string;
+ private podUrlTemplate?: string;
+ private getTraceHeaders?: () => TraceHeaders | undefined;
+
+ constructor(config: SandboxClientConfig) {
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
+ this.timeout = config.timeout ?? 120000;
+ this.headlessService = config.headlessService;
+ this.podUrlTemplate = config.podUrlTemplate;
+ this.getTraceHeaders = config.getTraceHeaders;
+ }
+
+ /**
+ * Parse composite workspace ID (pod:uuid) and return the pod-specific URL.
+ * Returns baseUrl if no routing config or ID is legacy format.
+ */
+ getUrlForWorkspace(compositeId: string): string {
+ const colonIndex = compositeId.indexOf(":");
+ if (colonIndex === -1) {
+ return this.baseUrl;
+ }
+ const pod = compositeId.slice(0, colonIndex);
+
+ if (this.podUrlTemplate) {
+ return this.podUrlTemplate.replace("{pod}", pod);
+ }
+
+ if (this.headlessService) {
+ return `http://${pod}.${this.headlessService}`;
+ }
+
+ return this.baseUrl;
+ }
+
+ /** @internal */
+ async request<T>(
+ method: string,
+ path: string,
+ body?: unknown,
+ compositeWorkspaceId?: string,
+ ): Promise<T> {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
+
+ try {
+ const headers: Record<string, string> = {};
+ if (body) headers["Content-Type"] = "application/json";
+
+ const url = compositeWorkspaceId
+ ? this.getUrlForWorkspace(compositeWorkspaceId)
+ : this.baseUrl;
+
+ if (compositeWorkspaceId) {
+ headers["X-Workspace-ID"] = compositeWorkspaceId;
+ }
+
+ const traceHeaders = this.getTraceHeaders?.();
+ if (traceHeaders) {
+ Object.assign(headers, traceHeaders);
+ }
+
+ const res = await fetch(`${url}${path}`, {
+ method,
+ headers,
+ body: body ? JSON.stringify(body) : undefined,
+ signal: controller.signal,
+ });
+
+ if (!res.ok) {
+ const error = await res.json().catch(() => ({ error: res.statusText }));
+ throw new Error(
+ (error as { error?: string }).error || `HTTP ${res.status}`,
+ );
+ }
+
+ if (res.status === 204) {
+ return undefined as T;
+ }
+
+ return res.json();
+ } finally {
+ clearTimeout(timeoutId);
+ }
+ }
+
+ async health(): Promise<{ status: string; workspaces: number }> {
+ return this.request("GET", "/health");
+ }
+
+ /**
+ * Get the current trace headers for manual fetch calls.
+ * @internal
+ */
+ getTracingHeaders(): TraceHeaders {
+ const headers: TraceHeaders = {};
+ const traceHeaders = this.getTraceHeaders?.();
+ if (traceHeaders) {
+ Object.assign(headers, traceHeaders);
+ }
+ return headers;
+ }
+
+ async createWorkspace(opts?: {
+ id?: string;
+ ttlSeconds?: number;
+ }): Promise<Workspace> {
+ const id = opts?.id ?? crypto.randomUUID();
+ const { id: compositeId } = await this.request<{ id: string }>(
+ "POST",
+ "/workspaces",
+ { ...opts, id },
+ id,
+ );
+ return new Workspace(this, compositeId);
+ }
+
+ async listWorkspaces(): Promise<string[]> {
+ const { workspaces } = await this.request<{ workspaces: string[] }>(
+ "GET",
+ "/workspaces",
+ );
+ return workspaces;
+ }
+
+ async getWorkspace(id: string): Promise<Workspace> {
+ await this.request("GET", `/workspaces/${id}`, undefined, id);
+ return new Workspace(this, id);
+ }
+}
+
+export class CodeContext {
+ constructor(
+ private client: SandboxClient,
+ private workspaceId: string,
+ readonly id: string,
+ ) {}
+
+ async runCode(code: string, opts?: { timeout?: number }): Promise<Execution> {
+ return this.client.request(
+ "POST",
+ `/workspaces/${this.workspaceId}/contexts/${this.id}/execute`,
+ { code, ...opts },
+ this.workspaceId,
+ );
+ }
+
+ async enableBrowser(cdpPath: string): Promise<void> {
+ await this.client.request(
+ "POST",
+ `/workspaces/${this.workspaceId}/contexts/${this.id}/enable-browser`,
+ { cdpPath },
+ this.workspaceId,
+ );
+ }
+
+ async runBash(
+ command: string,
+ opts?: { timeout?: number },
+ ): Promise<ExecResult> {
+ return this.client.request(
+ "POST",
+ `/workspaces/${this.workspaceId}/contexts/${this.id}/bash`,
+ { command, ...opts },
+ this.workspaceId,
+ );
+ }
+
+ async delete(): Promise<void> {
+ await this.client.request(
+ "DELETE",
+ `/workspaces/${this.workspaceId}/contexts/${this.id}`,
+ undefined,
+ this.workspaceId,
+ );
+ }
+}
+
+export class Workspace {
+ private contexts = new Map<string, CodeContext>();
+
+ constructor(
+ private client: SandboxClient,
+ readonly id: string,
+ ) {}
+
+ async createContext(): Promise<CodeContext> {
+ const { id } = await this.client.request<{ id: string }>(
+ "POST",
+ `/workspaces/${this.id}/contexts`,
+ undefined,
+ this.id,
+ );
+ const ctx = new CodeContext(this.client, this.id, id);
+ this.contexts.set(id, ctx);
+ return ctx;
+ }
+
+ getContext(contextId: string): CodeContext | undefined {
+ return this.contexts.get(contextId);
+ }
+
+ listContexts(): CodeContext[] {
+ return Array.from(this.contexts.values());
+ }
+
+ async destroy(): Promise<void> {
+ await this.client.request(
+ "DELETE",
+ `/workspaces/${this.id}`,
+ undefined,
+ this.id,
+ );
+ this.contexts.clear();
+ }
+
+ async runBash(
+ command: string,
+ opts?: { cwd?: string; timeout?: number },
+ ): Promise<ExecResult> {
+ return this.client.request(
+ "POST",
+ `/workspaces/${this.id}/bash`,
+ { command, ...opts },
+ this.id,
+ );
+ }
+
+ readonly fs = {
+ read: async (filePath: string): Promise<string> => {
+ const url = this.client.getUrlForWorkspace(this.id);
+ const res = await fetch(
+ `${url}/workspaces/${this.id}/files/${filePath}`,
+ {
+ headers: {
+ "X-Workspace-ID": this.id,
+ ...this.client.getTracingHeaders(),
+ },
+ },
+ );
+ if (!res.ok) throw new Error(`File not found: ${filePath}`);
+ return res.text();
+ },
+
+ write: async (filePath: string, content: string): Promise<void> => {
+ await this.client.request(
+ "PUT",
+ `/workspaces/${this.id}/files/${filePath}`,
+ { content },
+ this.id,
+ );
+ },
+
+ exists: async (filePath: string): Promise<boolean> => {
+ const url = this.client.getUrlForWorkspace(this.id);
+ const res = await fetch(
+ `${url}/workspaces/${this.id}/files/${filePath}`,
+ {
+ method: "HEAD",
+ headers: {
+ "X-Workspace-ID": this.id,
+ ...this.client.getTracingHeaders(),
+ },
+ },
+ );
+ return res.ok;
+ },
+
+ mkdir: async (dirPath: string): Promise<void> => {
+ await this.client.request(
+ "POST",
+ `/workspaces/${this.id}/mkdir/${dirPath}`,
+ undefined,
+ this.id,
+ );
+ },
+
+ remove: async (filePath: string): Promise<void> => {
+ await this.client.request(
+ "DELETE",
+ `/workspaces/${this.id}/files/${filePath}`,
+ undefined,
+ this.id,
+ );
+ },
+
+ list: async (dirPath: string = ""): Promise<string[]> => {
+ const { files } = await this.client.request<{ files: string[] }>(
+ "GET",
+ `/workspaces/${this.id}/ls/${dirPath}`,
+ undefined,
+ this.id,
+ );
+ return files;
+ },
+ };
+}
+
+export function createSandboxClient(
+ config: SandboxClientConfig | string = "http://localhost:3001",
+): SandboxClient {
+ if (typeof config === "string") {
+ return new SandboxClient({ baseUrl: config });
+ }
+ return new SandboxClient(config);
+}
diff --git a/apps/api/src/routes/v2.ts b/apps/api/src/routes/v2.ts
index 3807034c2..ff58228d2 100644
--- a/apps/api/src/routes/v2.ts
+++ b/apps/api/src/routes/v2.ts
@@ -43,6 +43,11 @@ import {
import { agentController } from "../controllers/v2/agent";
import { agentStatusController } from "../controllers/v2/agent-status";
import { agentCancelController } from "../controllers/v2/agent-cancel";
+import {
+ browserCreateController,
+ browserExecuteController,
+ browserDeleteController,
+} from "../controllers/v2/browser";
expressWs(express());
@@ -365,6 +370,26 @@ v2Router.get(
wrap(queueStatusController),
);
+v2Router.post(
+ "/browser",
+ authMiddleware(RateLimiterMode.Browser),
+ countryCheck,
+ checkCreditsMiddleware(5),
+ wrap(browserCreateController),
+);
+
+v2Router.post(
+ "/browser/execute",
+ authMiddleware(RateLimiterMode.Browser),
+ wrap(browserExecuteController),
+);
+
+v2Router.delete(
+ "/browser",
+ authMiddleware(RateLimiterMode.Browser),
+ wrap(browserDeleteController),
+);
+
// Only register x402 routes if X402_PAY_TO_ADDRESS is configured
if (isX402Enabled()) {
v2Router.post(
diff --git a/apps/api/src/services/rate-limiter.ts b/apps/api/src/services/rate-limiter.ts
index 2f0eb199c..95d422a11 100644
--- a/apps/api/src/services/rate-limiter.ts
+++ b/apps/api/src/services/rate-limiter.ts
@@ -27,6 +27,7 @@ const fallbackRateLimits: AuthCreditUsageChunk["rate_limits"] = {
crawlStatus: 25000,
extractAgentPreview: 10,
scrapeAgentPreview: 10,
+ browser: 5,
};
export function getRateLimiter(
diff --git a/apps/api/src/types.ts b/apps/api/src/types.ts
index 1acfb5a6a..b61792198 100644
--- a/apps/api/src/types.ts
+++ b/apps/api/src/types.ts
@@ -141,6 +141,7 @@ export enum RateLimiterMode {
Extract = "extract",
ExtractStatus = "extractStatus",
ExtractAgentPreview = "extractAgentPreview",
+ Browser = "browser",
}
export type AuthResponse =