docs: mdx, light/dark mode, ask (#400)

This commit is contained in:
Chris Tate
2026-02-09 11:16:21 -06:00
committed by GitHub
parent 4d8097a56f
commit e8ceafcbe1
36 changed files with 4221 additions and 1258 deletions
+83
View File
@@ -0,0 +1,83 @@
import type { MDXComponents } from "mdx/types";
import Link from "next/link";
import { CodeBlock } from "@/components/code-block";
function slugify(text: string): string {
return text
.toLowerCase()
.replace(/[^\w\s-]/g, "")
.replace(/\s+/g, "-")
.trim();
}
function extractText(children: React.ReactNode): string {
if (typeof children === "string") return children;
if (typeof children === "number") return String(children);
if (Array.isArray(children)) return children.map(extractText).join("");
if (children && typeof children === "object") {
const obj = children as unknown as Record<string, unknown>;
if ("props" in obj) {
const props = obj.props as { children?: React.ReactNode } | undefined;
return extractText(props?.children);
}
}
return "";
}
export function useMDXComponents(components: MDXComponents): MDXComponents {
return {
...components,
h2: ({ children }: { children?: React.ReactNode }) => {
const id = slugify(extractText(children));
return <h2 id={id}>{children}</h2>;
},
h3: ({ children }: { children?: React.ReactNode }) => {
const id = slugify(extractText(children));
return <h3 id={id}>{children}</h3>;
},
a: ({
href,
children,
}: {
href?: string;
children?: React.ReactNode;
}) => {
if (href?.startsWith("/")) {
return <Link href={href}>{children}</Link>;
}
return (
<a href={href} target="_blank" rel="noopener noreferrer">
{children}
</a>
);
},
code: ({
children,
className,
}: {
children?: React.ReactNode;
className?: string;
}) => {
if (className) {
return <code className={className}>{children}</code>;
}
return <code>{children}</code>;
},
pre: async ({ children }: { children?: React.ReactNode }) => {
const codeElement = children as React.ReactElement<{
className?: string;
children?: string;
}>;
const className = codeElement?.props?.className || "";
const lang = className.replace("language-", "") || "bash";
const code = codeElement?.props?.children || "";
return (
<CodeBlock
code={typeof code === "string" ? code : String(code)}
lang={lang}
/>
);
},
};
}
+10
View File
@@ -0,0 +1,10 @@
import createMDX from "@next/mdx";
/** @type {import('next').NextConfig} */
const nextConfig = {
pageExtensions: ["js", "jsx", "ts", "tsx", "md", "mdx"],
};
const withMDX = createMDX({});
export default withMDX(nextConfig);
-7
View File
@@ -1,7 +0,0 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;
+14 -1
View File
@@ -9,13 +9,26 @@
"lint": "eslint"
},
"dependencies": {
"@ai-sdk/react": "^3.0.80",
"@mdx-js/loader": "^3.1.1",
"@mdx-js/mdx": "^3.1.1",
"@mdx-js/react": "^3.1.1",
"@next/mdx": "^16.1.6",
"@upstash/ratelimit": "^2.0.8",
"@upstash/redis": "^1.36.2",
"ai": "^6.0.78",
"bash-tool": "^1.3.14",
"just-bash": "^2.9.6",
"next": "16.1.1",
"next-themes": "^0.4.6",
"react": "19.2.3",
"react-dom": "19.2.3",
"shiki": "^3.21.0"
"shiki": "^3.21.0",
"streamdown": "^2.1.0"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/mdx": "^2.0.13",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
+2047 -2
View File
File diff suppressed because it is too large Load Diff
+115
View File
@@ -0,0 +1,115 @@
import { readFile } from "fs/promises";
import { join } from "path";
import { convertToModelMessages, stepCountIs, streamText } from "ai";
import type { ModelMessage, UIMessage } from "ai";
import { createBashTool } from "bash-tool";
import { headers } from "next/headers";
import { allDocsPages } from "@/lib/docs-navigation";
import { mdxToCleanMarkdown } from "@/lib/mdx-to-markdown";
import { minuteRateLimit, dailyRateLimit } from "@/lib/rate-limit";
export const maxDuration = 60;
const DEFAULT_MODEL = "anthropic/claude-haiku-4.5";
const SYSTEM_PROMPT = `You are a helpful documentation assistant for agent-browser, a headless browser automation CLI designed for AI agents.
GitHub repository: https://github.com/vercel-labs/agent-browser
Documentation: https://agent-browser.dev
npm package: agent-browser
You have access to the full agent-browser documentation via the bash and readFile tools. The docs are available as markdown files in the /workspace/ directory.
When answering questions:
- Use the bash tool to list files (ls /workspace/) or search for content (grep -r "keyword" /workspace/)
- Use the readFile tool to read specific documentation pages (e.g. readFile with path "/workspace/index.md")
- Always base your answers on the actual documentation content
- Be concise and accurate
- If the docs don't cover a topic, say so honestly
- Do NOT include source references or file paths in your response`;
async function loadDocsFiles(): Promise<Record<string, string>> {
const files: Record<string, string> = {};
const results = await Promise.allSettled(
allDocsPages.map(async (page) => {
const slug = page.href === "/" ? "" : page.href.replace(/^\//, "");
const filePath = slug
? join(process.cwd(), "src", "app", slug, "page.mdx")
: join(process.cwd(), "src", "app", "page.mdx");
const raw = await readFile(filePath, "utf-8");
const md = mdxToCleanMarkdown(raw);
const fileName = slug ? `/${slug}.md` : "/index.md";
return { fileName, md };
}),
);
for (const result of results) {
if (result.status === "fulfilled") {
files[result.value.fileName] = result.value.md;
}
}
return files;
}
function addCacheControl(messages: ModelMessage[]): ModelMessage[] {
if (messages.length === 0) return messages;
return messages.map((message, index) => {
if (index === messages.length - 1) {
return {
...message,
providerOptions: {
...message.providerOptions,
anthropic: { cacheControl: { type: "ephemeral" } },
},
};
}
return message;
});
}
export async function POST(req: Request) {
const headersList = await headers();
const ip = headersList.get("x-forwarded-for")?.split(",")[0] ?? "anonymous";
const [minuteResult, dailyResult] = await Promise.all([
minuteRateLimit.limit(ip),
dailyRateLimit.limit(ip),
]);
if (!minuteResult.success || !dailyResult.success) {
const isMinuteLimit = !minuteResult.success;
return new Response(
JSON.stringify({
error: "Rate limit exceeded",
message: isMinuteLimit
? "Too many requests. Please wait a moment before trying again."
: "Daily limit reached. Please try again tomorrow.",
}),
{
status: 429,
headers: { "Content-Type": "application/json" },
},
);
}
const { messages }: { messages: UIMessage[] } = await req.json();
const docsFiles = await loadDocsFiles();
const { tools } = await createBashTool({ files: docsFiles });
const result = streamText({
model: DEFAULT_MODEL,
system: SYSTEM_PROMPT,
messages: await convertToModelMessages(messages),
stopWhen: stepCountIs(5),
tools,
prepareStep: ({ messages: stepMessages }) => ({
messages: addCacheControl(stepMessages),
}),
});
return result.toUIMessageStreamResponse();
}
+87
View File
@@ -0,0 +1,87 @@
export const metadata = { title: "CDP Mode" }
# CDP Mode
Connect to an existing browser via Chrome DevTools Protocol:
```bash
# Start Chrome with: google-chrome --remote-debugging-port=9222
# Connect once, then run commands without --cdp
agent-browser connect 9222
agent-browser snapshot
agent-browser tab
agent-browser close
# Or pass --cdp on each command
agent-browser --cdp 9222 snapshot
```
## Remote WebSocket URLs
Connect to remote browser services via WebSocket URL:
```bash
# Connect to remote browser service
agent-browser --cdp "wss://browser-service.com/cdp?token=..." snapshot
# Works with any CDP-compatible service
agent-browser --cdp "ws://localhost:9222/devtools/browser/abc123" open example.com
```
The `--cdp` flag accepts either:
- A port number (e.g., `9222`) for local connections via `http://localhost:{port}`
- A full WebSocket URL (e.g., `wss://...` or `ws://...`) for remote browser services
## Use cases
This enables control of:
- Electron apps
- Chrome/Chromium with remote debugging
- WebView2 applications
- Remote browser services (via WebSocket URL)
- Any browser exposing a CDP endpoint
## Global options
| Option | Description |
| --- | --- |
| `--session <name>` | Use isolated session |
| `--profile <path>` | Persistent browser profile directory |
| `-p <provider>` | Cloud browser provider (`browserbase`, `browseruse`) |
| `--headers <json>` | HTTP headers scoped to origin |
| `--executable-path` | Custom browser executable |
| `--args <args>` | Browser launch args (comma-separated) |
| `--user-agent <ua>` | Custom User-Agent string |
| `--proxy <url>` | Proxy server URL |
| `--proxy-bypass <hosts>` | Hosts to bypass proxy |
| `--json` | JSON output for scripts |
| `--full, -f` | Full page screenshot |
| `--name, -n` | Locator name filter |
| `--exact` | Exact text match |
| `--headed` | Show browser window |
| `--cdp <port\|url>` | CDP connection (port or WebSocket URL) |
| `--debug` | Debug output |
## Cloud providers
Use cloud browser infrastructure when local browsers aren't available:
```bash
# Browserbase
export BROWSERBASE_API_KEY="your-api-key"
export BROWSERBASE_PROJECT_ID="your-project-id"
agent-browser -p browserbase open https://example.com
# Browser Use
export BROWSER_USE_API_KEY="your-api-key"
agent-browser -p browseruse open https://example.com
# Or via environment variable
export AGENT_BROWSER_PROVIDER=browserbase
agent-browser open https://example.com
```
The `-p` flag takes precedence over `AGENT_BROWSER_PROVIDER`.
-137
View File
@@ -1,137 +0,0 @@
import { CodeBlock } from "@/components/code-block";
export default function CDPMode() {
return (
<div className="max-w-2xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
<div className="prose">
<h1>CDP Mode</h1>
<p>Connect to an existing browser via Chrome DevTools Protocol:</p>
<CodeBlock code={`# Start Chrome with: google-chrome --remote-debugging-port=9222
# Connect once, then run commands without --cdp
agent-browser connect 9222
agent-browser snapshot
agent-browser tab
agent-browser close
# Or pass --cdp on each command
agent-browser --cdp 9222 snapshot`} />
<h2>Remote WebSocket URLs</h2>
<p>Connect to remote browser services via WebSocket URL:</p>
<CodeBlock code={`# Connect to remote browser service
agent-browser --cdp "wss://browser-service.com/cdp?token=..." snapshot
# Works with any CDP-compatible service
agent-browser --cdp "ws://localhost:9222/devtools/browser/abc123" open example.com`} />
<p>The <code>--cdp</code> flag accepts either:</p>
<ul>
<li>A port number (e.g., <code>9222</code>) for local connections via <code>http://localhost:&#123;port&#125;</code></li>
<li>A full WebSocket URL (e.g., <code>wss://...</code> or <code>ws://...</code>) for remote browser services</li>
</ul>
<h2>Use cases</h2>
<p>This enables control of:</p>
<ul>
<li>Electron apps</li>
<li>Chrome/Chromium with remote debugging</li>
<li>WebView2 applications</li>
<li>Remote browser services (via WebSocket URL)</li>
<li>Any browser exposing a CDP endpoint</li>
</ul>
<h2>Global options</h2>
<table>
<thead>
<tr>
<th>Option</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>--session &lt;name&gt;</code></td>
<td>Use isolated session</td>
</tr>
<tr>
<td><code>--profile &lt;path&gt;</code></td>
<td>Persistent browser profile directory</td>
</tr>
<tr>
<td><code>-p &lt;provider&gt;</code></td>
<td>Cloud browser provider (<code>browserbase</code>, <code>browseruse</code>)</td>
</tr>
<tr>
<td><code>--headers &lt;json&gt;</code></td>
<td>HTTP headers scoped to origin</td>
</tr>
<tr>
<td><code>--executable-path</code></td>
<td>Custom browser executable</td>
</tr>
<tr>
<td><code>--args &lt;args&gt;</code></td>
<td>Browser launch args (comma-separated)</td>
</tr>
<tr>
<td><code>--user-agent &lt;ua&gt;</code></td>
<td>Custom User-Agent string</td>
</tr>
<tr>
<td><code>--proxy &lt;url&gt;</code></td>
<td>Proxy server URL</td>
</tr>
<tr>
<td><code>--proxy-bypass &lt;hosts&gt;</code></td>
<td>Hosts to bypass proxy</td>
</tr>
<tr>
<td><code>--json</code></td>
<td>JSON output for scripts</td>
</tr>
<tr>
<td><code>--full, -f</code></td>
<td>Full page screenshot</td>
</tr>
<tr>
<td><code>--name, -n</code></td>
<td>Locator name filter</td>
</tr>
<tr>
<td><code>--exact</code></td>
<td>Exact text match</td>
</tr>
<tr>
<td><code>--headed</code></td>
<td>Show browser window</td>
</tr>
<tr>
<td><code>--cdp &lt;port|url&gt;</code></td>
<td>CDP connection (port or WebSocket URL)</td>
</tr>
<tr>
<td><code>--debug</code></td>
<td>Debug output</td>
</tr>
</tbody>
</table>
<h2>Cloud providers</h2>
<p>Use cloud browser infrastructure when local browsers aren&apos;t available:</p>
<CodeBlock code={`# Browserbase
export BROWSERBASE_API_KEY="your-api-key"
export BROWSERBASE_PROJECT_ID="your-project-id"
agent-browser -p browserbase open https://example.com
# Browser Use
export BROWSER_USE_API_KEY="your-api-key"
agent-browser -p browseruse open https://example.com
# Or via environment variable
export AGENT_BROWSER_PROVIDER=browserbase
agent-browser open https://example.com`} />
<p>The <code>-p</code> flag takes precedence over <code>AGENT_BROWSER_PROVIDER</code>.</p>
</div>
</div>
);
}
+193
View File
@@ -0,0 +1,193 @@
export const metadata = { title: "Changelog" }
# Changelog
## v0.8.0
<p className="text-[#888] text-sm">January 2026</p>
### New Features
- **Kernel cloud browser provider** - Connect to Kernel (kernel.sh) for remote browser infrastructure with stealth mode and persistent profiles
```bash
# Via -p flag
agent-browser -p kernel open https://example.com
# Via environment variable
export AGENT_BROWSER_PROVIDER=kernel
export KERNEL_API_KEY=your-api-key
agent-browser open https://example.com
# With persistent profile
export KERNEL_PROFILE_NAME=my-profile
agent-browser open https://example.com
```
- **Ignore HTTPS certificate errors** - New flag for working with self-signed certificates and development environments
```bash
agent-browser --ignore-https-errors open https://localhost:3000
```
- **Enhanced cookie management** - Extended `cookies set` command with additional flags for setting cookies before page load
```bash
agent-browser cookies set session_id "abc123" --url https://app.example.com --httpOnly --secure
agent-browser cookies set token "xyz" --domain .example.com --path /api --expires 1735689600
```
### Bug Fixes
- Fixed tab list command not recognizing new pages opened via clicks or `target="_blank"` links
- Fixed `check` command hanging indefinitely
- Fixed `set device` not applying deviceScaleFactor - HiDPI screenshots now work correctly
- Fixed state load and profile persistence not working in v0.7.6
- Screenshots now save to temp directory when no path is provided
### Security
- Daemon and stream server now reject cross-origin connections
---
## v0.7.1
<p className="text-[#888] text-sm">January 2026</p>
### Bug Fixes
- **Fix native binary distribution** - Native binaries for all platforms (Linux x64/arm64, macOS x64/arm64, Windows x64) are now included in the npm package. Previously, the release workflow published to npm before building binaries, causing "No binary found" errors on installation.
---
## v0.7.0
<p className="text-[#888] text-sm">January 2026</p>
### New Features
- **Cloud browser providers** - Connect to Browserbase or Browser Use for remote browser infrastructure
```bash
# Via -p flag (recommended)
agent-browser -p browserbase open https://example.com
agent-browser -p browseruse open https://example.com
# Via environment variable
export AGENT_BROWSER_PROVIDER=browserbase
agent-browser open https://example.com
```
- **Persistent browser profiles** - Store cookies, localStorage, and login sessions across browser restarts
```bash
agent-browser --profile ~/.myapp-profile open myapp.com
# Login persists across restarts
```
- **Remote CDP WebSocket URLs** - Connect to remote browser services via WebSocket
```bash
agent-browser --cdp "wss://browser-service.com/cdp?token=..." snapshot
```
- **`download` command** - Trigger downloads and wait for completion
```bash
agent-browser download @e1 ./file.pdf
agent-browser wait --download ./output.zip --timeout 30000
```
- **Browser launch configuration** - Fine-grained control over browser startup
```bash
agent-browser --args "--disable-gpu,--no-sandbox" open example.com
agent-browser --user-agent "Custom UA" open example.com
agent-browser --proxy-bypass "localhost,*.internal" open example.com
```
- **Enhanced skills** - Hierarchical structure with references and templates for Claude Code
### Bug Fixes
- Screenshot command now supports refs and has improved error messages
- WebSocket URLs work in `connect` command
- Fixed socket file location (uses `~/.agent-browser` instead of TMPDIR)
- Windows binary path fix (.exe extension)
- State load and path-based actions now show correct output messages
### Documentation
- Added Claude Code marketplace plugin installation instructions
- Updated skill documentation with references and templates
- Improved error documentation
---
## v0.6.0
<p className="text-[#888] text-sm">January 2026</p>
### New Features
- **Video recording** - Record browser sessions to WebM using Playwright's native recording
```bash
agent-browser record start ./demo.webm
agent-browser click @e1
agent-browser record stop
```
- **`connect` command** - Connect to a browser via CDP and persist the connection for subsequent commands
```bash
agent-browser connect 9222
agent-browser snapshot # No --cdp needed after connect
```
- **`--proxy` flag** - Configure browser proxy with optional authentication
```bash
agent-browser --proxy http://user:pass@proxy.com:8080 open example.com
```
- **`get styles` command** - Extract computed styles from elements
```bash
agent-browser get styles "button"
```
- **Claude marketplace plugin** - Added `.claude-plugin/marketplace.json` for Claude Code integration
- **Enhanced network output** - `network requests` now shows method, URL, and resource type
- **`--version` flag** - Display CLI version
### Bug Fixes
- Fix Windows daemon startup and port calculation
- Support `libasound2t64` on newer Ubuntu versions (24.04+)
- Prevent CDP timeout on empty URL tabs
- Output screenshot as base64 when no path provided
- Resolve refs in `get value` command
- Support URL parameter in `tab new` command
- Allow `about:`, `data:`, and `file:` URL schemes
- Detect stale unix socket by attempting connection
- Respect `AGENT_BROWSER_HEADED` environment variable
- Handle SIGPIPE to prevent panic when piping to `head`/`tail`
- Fix null path validation in screenshot command
### Protocol Alignment
These changes align the CLI with the daemon protocol for consistency:
- `select` command now uses `values` field (supports multiple selections)
- `frame main` uses `mainframe` action
- `mouse wheel` uses `wheel` action
- `set media` uses `emulatemedia` action
- Console output uses `messages` field
### Documentation
- Expanded SKILL.md with comprehensive command reference
- Updated README with new commands and options
- Updated CDP mode documentation with `connect` workflow
-195
View File
@@ -1,195 +0,0 @@
import { CodeBlock } from "@/components/code-block";
export default function Changelog() {
return (
<div className="max-w-2xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
<div className="prose">
<h1>Changelog</h1>
<h2 id="v0.8.0">v0.8.0</h2>
<p className="text-[#888] text-sm">January 2026</p>
<h3>New Features</h3>
<ul>
<li>
<strong>Kernel cloud browser provider</strong> - Connect to Kernel (kernel.sh) for remote browser infrastructure with stealth mode and persistent profiles
<CodeBlock code={`# Via -p flag
agent-browser -p kernel open https://example.com
# Via environment variable
export AGENT_BROWSER_PROVIDER=kernel
export KERNEL_API_KEY=your-api-key
agent-browser open https://example.com
# With persistent profile
export KERNEL_PROFILE_NAME=my-profile
agent-browser open https://example.com`} />
</li>
<li>
<strong>Ignore HTTPS certificate errors</strong> - New flag for working with self-signed certificates and development environments
<CodeBlock code={`agent-browser --ignore-https-errors open https://localhost:3000`} />
</li>
<li>
<strong>Enhanced cookie management</strong> - Extended <code>cookies set</code> command with additional flags for setting cookies before page load
<CodeBlock code={`agent-browser cookies set session_id "abc123" --url https://app.example.com --httpOnly --secure
agent-browser cookies set token "xyz" --domain .example.com --path /api --expires 1735689600`} />
</li>
</ul>
<h3>Bug Fixes</h3>
<ul>
<li>Fixed tab list command not recognizing new pages opened via clicks or <code>target=&quot;_blank&quot;</code> links</li>
<li>Fixed <code>check</code> command hanging indefinitely</li>
<li>Fixed <code>set device</code> not applying deviceScaleFactor - HiDPI screenshots now work correctly</li>
<li>Fixed state load and profile persistence not working in v0.7.6</li>
<li>Screenshots now save to temp directory when no path is provided</li>
</ul>
<h3>Security</h3>
<ul>
<li>Daemon and stream server now reject cross-origin connections</li>
</ul>
<hr className="my-8 border-[#333]" />
<h2 id="v0.7.1">v0.7.1</h2>
<p className="text-[#888] text-sm">January 2026</p>
<h3>Bug Fixes</h3>
<ul>
<li>
<strong>Fix native binary distribution</strong> - Native binaries for all platforms (Linux x64/arm64, macOS x64/arm64, Windows x64) are now included in the npm package. Previously, the release workflow published to npm before building binaries, causing &quot;No binary found&quot; errors on installation.
</li>
</ul>
<hr className="my-8 border-[#333]" />
<h2 id="v0.7.0">v0.7.0</h2>
<p className="text-[#888] text-sm">January 2026</p>
<h3>New Features</h3>
<ul>
<li>
<strong>Cloud browser providers</strong> - Connect to Browserbase or Browser Use for remote browser infrastructure
<CodeBlock code={`# Via -p flag (recommended)
agent-browser -p browserbase open https://example.com
agent-browser -p browseruse open https://example.com
# Via environment variable
export AGENT_BROWSER_PROVIDER=browserbase
agent-browser open https://example.com`} />
</li>
<li>
<strong>Persistent browser profiles</strong> - Store cookies, localStorage, and login sessions across browser restarts
<CodeBlock code={`agent-browser --profile ~/.myapp-profile open myapp.com
# Login persists across restarts`} />
</li>
<li>
<strong>Remote CDP WebSocket URLs</strong> - Connect to remote browser services via WebSocket
<CodeBlock code={`agent-browser --cdp "wss://browser-service.com/cdp?token=..." snapshot`} />
</li>
<li>
<strong><code>download</code> command</strong> - Trigger downloads and wait for completion
<CodeBlock code={`agent-browser download @e1 ./file.pdf
agent-browser wait --download ./output.zip --timeout 30000`} />
</li>
<li>
<strong>Browser launch configuration</strong> - Fine-grained control over browser startup
<CodeBlock code={`agent-browser --args "--disable-gpu,--no-sandbox" open example.com
agent-browser --user-agent "Custom UA" open example.com
agent-browser --proxy-bypass "localhost,*.internal" open example.com`} />
</li>
<li>
<strong>Enhanced skills</strong> - Hierarchical structure with references and templates for Claude Code
</li>
</ul>
<h3>Bug Fixes</h3>
<ul>
<li>Screenshot command now supports refs and has improved error messages</li>
<li>WebSocket URLs work in <code>connect</code> command</li>
<li>Fixed socket file location (uses <code>~/.agent-browser</code> instead of TMPDIR)</li>
<li>Windows binary path fix (.exe extension)</li>
<li>State load and path-based actions now show correct output messages</li>
</ul>
<h3>Documentation</h3>
<ul>
<li>Added Claude Code marketplace plugin installation instructions</li>
<li>Updated skill documentation with references and templates</li>
<li>Improved error documentation</li>
</ul>
<hr className="my-8 border-[#333]" />
<h2 id="v0.6.0">v0.6.0</h2>
<p className="text-[#888] text-sm">January 2026</p>
<h3>New Features</h3>
<ul>
<li>
<strong>Video recording</strong> - Record browser sessions to WebM using Playwright&apos;s native recording
<CodeBlock code={`agent-browser record start ./demo.webm
agent-browser click @e1
agent-browser record stop`} />
</li>
<li>
<strong><code>connect</code> command</strong> - Connect to a browser via CDP and persist the connection for subsequent commands
<CodeBlock code={`agent-browser connect 9222
agent-browser snapshot # No --cdp needed after connect`} />
</li>
<li>
<strong><code>--proxy</code> flag</strong> - Configure browser proxy with optional authentication
<CodeBlock code="agent-browser --proxy http://user:pass@proxy.com:8080 open example.com" />
</li>
<li>
<strong><code>get styles</code> command</strong> - Extract computed styles from elements
<CodeBlock code={`agent-browser get styles "button"`} />
</li>
<li>
<strong>Claude marketplace plugin</strong> - Added <code>.claude-plugin/marketplace.json</code> for Claude Code integration
</li>
<li>
<strong>Enhanced network output</strong> - <code>network requests</code> now shows method, URL, and resource type
</li>
<li>
<strong><code>--version</code> flag</strong> - Display CLI version
</li>
</ul>
<h3>Bug Fixes</h3>
<ul>
<li>Fix Windows daemon startup and port calculation</li>
<li>Support <code>libasound2t64</code> on newer Ubuntu versions (24.04+)</li>
<li>Prevent CDP timeout on empty URL tabs</li>
<li>Output screenshot as base64 when no path provided</li>
<li>Resolve refs in <code>get value</code> command</li>
<li>Support URL parameter in <code>tab new</code> command</li>
<li>Allow <code>about:</code>, <code>data:</code>, and <code>file:</code> URL schemes</li>
<li>Detect stale unix socket by attempting connection</li>
<li>Respect <code>AGENT_BROWSER_HEADED</code> environment variable</li>
<li>Handle SIGPIPE to prevent panic when piping to <code>head</code>/<code>tail</code></li>
<li>Fix null path validation in screenshot command</li>
</ul>
<h3>Protocol Alignment</h3>
<p>These changes align the CLI with the daemon protocol for consistency:</p>
<ul>
<li><code>select</code> command now uses <code>values</code> field (supports multiple selections)</li>
<li><code>frame main</code> uses <code>mainframe</code> action</li>
<li><code>mouse wheel</code> uses <code>wheel</code> action</li>
<li><code>set media</code> uses <code>emulatemedia</code> action</li>
<li>Console output uses <code>messages</code> field</li>
</ul>
<h3>Documentation</h3>
<ul>
<li>Expanded SKILL.md with comprehensive command reference</li>
<li>Updated README with new commands and options</li>
<li>Updated CDP mode documentation with <code>connect</code> workflow</li>
</ul>
</div>
</div>
);
}
@@ -1,13 +1,11 @@
import { CodeBlock } from "@/components/code-block";
export const metadata = { title: "Commands" }
export default function Commands() {
return (
<div className="max-w-2xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
<div className="prose">
<h1>Commands</h1>
# Commands
<h2>Core</h2>
<CodeBlock code={`agent-browser open <url> # Navigate (aliases: goto, navigate)
## Core
```bash
agent-browser open <url> # Navigate (aliases: goto, navigate)
agent-browser click <sel> # Click element
agent-browser dblclick <sel> # Double-click
agent-browser fill <sel> <text> # Clear and fill
@@ -21,67 +19,96 @@ agent-browser scroll <dir> [px] # Scroll (up/down/left/right)
agent-browser screenshot [path] # Screenshot (--full for full page)
agent-browser snapshot # Accessibility tree with refs
agent-browser eval <js> # Run JavaScript
agent-browser close # Close browser`} />
agent-browser close # Close browser
```
<h2>Get info</h2>
<CodeBlock code={`agent-browser get text <sel> # Get text content
## Get info
```bash
agent-browser get text <sel> # Get text content
agent-browser get html <sel> # Get innerHTML
agent-browser get value <sel> # Get input value
agent-browser get attr <sel> <attr> # Get attribute
agent-browser get title # Get page title
agent-browser get url # Get current URL
agent-browser get count <sel> # Count matching elements
agent-browser get box <sel> # Get bounding box`} />
agent-browser get box <sel> # Get bounding box
```
<h2>Check state</h2>
<CodeBlock code={`agent-browser is visible <sel> # Check if visible
## Check state
```bash
agent-browser is visible <sel> # Check if visible
agent-browser is enabled <sel> # Check if enabled
agent-browser is checked <sel> # Check if checked`} />
agent-browser is checked <sel> # Check if checked
```
<h2>Find elements</h2>
<p>Semantic locators with actions (<code>click</code>, <code>fill</code>, <code>check</code>, <code>hover</code>, <code>text</code>):</p>
<CodeBlock code={`agent-browser find role <role> <action> [value]
## Find elements
Semantic locators with actions (`click`, `fill`, `check`, `hover`, `text`):
```bash
agent-browser find role <role> <action> [value]
agent-browser find text <text> <action>
agent-browser find label <label> <action> [value]
agent-browser find placeholder <ph> <action> [value]
agent-browser find testid <id> <action> [value]
agent-browser find first <sel> <action> [value]
agent-browser find nth <n> <sel> <action> [value]`} />
<p>Examples:</p>
<CodeBlock code={`agent-browser find role button click --name "Submit"
agent-browser find label "Email" fill "test@test.com"
agent-browser find first ".item" click`} />
agent-browser find nth <n> <sel> <action> [value]
```
<h2>Wait</h2>
<CodeBlock code={`agent-browser wait <selector> # Wait for element
Examples:
```bash
agent-browser find role button click --name "Submit"
agent-browser find label "Email" fill "test@test.com"
agent-browser find first ".item" click
```
## Wait
```bash
agent-browser wait <selector> # Wait for element
agent-browser wait <ms> # Wait for time
agent-browser wait --text "Welcome" # Wait for text
agent-browser wait --url "**/dash" # Wait for URL pattern
agent-browser wait --load networkidle # Wait for load state
agent-browser wait --fn "condition" # Wait for JS condition
agent-browser wait --download [path] # Wait for download`} />
agent-browser wait --download [path] # Wait for download
```
<h2>Downloads</h2>
<CodeBlock code={`agent-browser download <sel> <path> # Click element to trigger download
agent-browser wait --download [path] # Wait for any download to complete`} />
## Downloads
<h2>Mouse</h2>
<CodeBlock code={`agent-browser mouse move <x> <y> # Move mouse
```bash
agent-browser download <sel> <path> # Click element to trigger download
agent-browser wait --download [path] # Wait for any download to complete
```
## Mouse
```bash
agent-browser mouse move <x> <y> # Move mouse
agent-browser mouse down [button] # Press button
agent-browser mouse up [button] # Release button
agent-browser mouse wheel <dy> [dx] # Scroll wheel`} />
agent-browser mouse wheel <dy> [dx] # Scroll wheel
```
<h2>Settings</h2>
<CodeBlock code={`agent-browser set viewport <w> <h> # Set viewport size
## Settings
```bash
agent-browser set viewport <w> <h> # Set viewport size
agent-browser set device <name> # Emulate device ("iPhone 14")
agent-browser set geo <lat> <lng> # Set geolocation
agent-browser set offline [on|off] # Toggle offline mode
agent-browser set headers <json> # Extra HTTP headers
agent-browser set credentials <u> <p> # HTTP basic auth
agent-browser set media [dark|light] # Emulate color scheme`} />
agent-browser set media [dark|light] # Emulate color scheme
```
<h2>Cookies & storage</h2>
<CodeBlock code={`agent-browser cookies # Get all cookies
## Cookies & storage
```bash
agent-browser cookies # Get all cookies
agent-browser cookies set <name> <val> # Set cookie
agent-browser cookies clear # Clear cookies
@@ -90,39 +117,54 @@ agent-browser storage local <key> # Get specific key
agent-browser storage local set <k> <v> # Set value
agent-browser storage local clear # Clear all
agent-browser storage session # Same for sessionStorage`} />
agent-browser storage session # Same for sessionStorage
```
<h2>Network</h2>
<CodeBlock code={`agent-browser network route <url> # Intercept requests
## Network
```bash
agent-browser network route <url> # Intercept requests
agent-browser network route <url> --abort # Block requests
agent-browser network route <url> --body <json> # Mock response
agent-browser network unroute [url] # Remove routes
agent-browser network requests # View tracked requests`} />
agent-browser network requests # View tracked requests
```
<h2>Tabs & frames</h2>
<CodeBlock code={`agent-browser tab # List tabs
## Tabs & frames
```bash
agent-browser tab # List tabs
agent-browser tab new [url] # New tab
agent-browser tab <n> # Switch to tab
agent-browser tab close [n] # Close tab
agent-browser frame <sel> # Switch to iframe
agent-browser frame main # Back to main frame`} />
agent-browser frame main # Back to main frame
```
<h2>Debug</h2>
<CodeBlock code={`agent-browser trace start [path] # Start trace
## Debug
```bash
agent-browser trace start [path] # Start trace
agent-browser trace stop [path] # Stop and save trace
agent-browser console # View console messages
agent-browser errors # View page errors
agent-browser highlight <sel> # Highlight element
agent-browser state save <path> # Save auth state
agent-browser state load <path> # Load auth state`} />
agent-browser state load <path> # Load auth state
```
<h2>Navigation</h2>
<CodeBlock code={`agent-browser back # Go back
## Navigation
```bash
agent-browser back # Go back
agent-browser forward # Go forward
agent-browser reload # Reload page`} />
agent-browser reload # Reload page
```
<h2>Global options</h2>
<CodeBlock code={`--session <name> # Isolated browser session
## Global options
```bash
--session <name> # Isolated browser session
--profile <path> # Persistent browser profile directory
--headed # Show browser window (not headless)
--cdp <port> # Connect via Chrome DevTools Protocol
@@ -134,17 +176,17 @@ agent-browser reload # Reload page`} />
--ignore-https-errors # Ignore HTTPS certificate errors
--allow-file-access # Allow file:// URLs to access local files (Chromium only)
--json # JSON output (for scripts)
--debug # Debug output`} />
--debug # Debug output
```
<h2>Local files</h2>
<p>Open local files (PDFs, HTML) using <code>file://</code> URLs:</p>
<CodeBlock code={`agent-browser --allow-file-access open file:///path/to/document.pdf
## Local files
Open local files (PDFs, HTML) using `file://` URLs:
```bash
agent-browser --allow-file-access open file:///path/to/document.pdf
agent-browser --allow-file-access open file:///path/to/page.html
agent-browser screenshot output.png`} />
<p>
The <code>--allow-file-access</code> flag enables JavaScript to access other local files. Chromium only.
</p>
</div>
</div>
);
}
agent-browser screenshot output.png
```
The `--allow-file-access` flag enables JavaScript to access other local files. Chromium only.
+126 -19
View File
@@ -1,19 +1,79 @@
@import "tailwindcss";
:root {
--background: #000000;
--foreground: #ededed;
--muted: #888888;
--border: #222222;
--accent: #ededed;
--radius: 0.5rem;
--background: oklch(1.0 0 0);
--foreground: oklch(0.1 0 0);
--card: oklch(0.98 0 0);
--card-foreground: oklch(0.1 0 0);
--popover: oklch(0.98 0 0);
--popover-foreground: oklch(0.1 0 0);
--primary: oklch(0.1 0 0);
--primary-foreground: oklch(1.0 0 0);
--secondary: oklch(0.92 0 0);
--secondary-foreground: oklch(0.1 0 0);
--muted: oklch(0.92 0 0);
--muted-foreground: oklch(0.45 0 0);
--accent: oklch(0.92 0 0);
--accent-foreground: oklch(0.1 0 0);
--destructive: oklch(0.55 0.2 25);
--destructive-foreground: oklch(1.0 0 0);
--border: oklch(0.85 0 0);
--input: oklch(0.85 0 0);
--ring: oklch(0.6 0 0);
--chat-bg: oklch(0.95 0 0);
}
.dark {
--background: oklch(0.0 0 0);
--foreground: oklch(0.98 0 0);
--card: oklch(0.08 0 0);
--card-foreground: oklch(0.98 0 0);
--popover: oklch(0.08 0 0);
--popover-foreground: oklch(0.98 0 0);
--primary: oklch(0.98 0 0);
--primary-foreground: oklch(0.0 0 0);
--secondary: oklch(0.15 0 0);
--secondary-foreground: oklch(0.98 0 0);
--muted: oklch(0.15 0 0);
--muted-foreground: oklch(0.6 0 0);
--accent: oklch(0.15 0 0);
--accent-foreground: oklch(0.1 0 0);
--destructive: oklch(0.65 0.2 25);
--destructive-foreground: oklch(0.98 0 0);
--border: oklch(0.25 0 0);
--input: oklch(0.25 0 0);
--ring: oklch(0.4 0 0);
--chat-bg: oklch(0.25 0 0);
}
@custom-variant dark (&:is(.dark *));
@theme inline {
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--radius-2xl: calc(var(--radius) + 8px);
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-border: var(--border);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--font-sans: var(--font-geist);
--font-mono: var(--font-geist-mono);
}
@@ -35,17 +95,17 @@ body {
}
::-webkit-scrollbar-thumb {
background: #333;
background: var(--border);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: #444;
background: var(--muted-foreground);
}
/* Code blocks */
pre {
background: #111 !important;
background: var(--card) !important;
border: 1px solid var(--border);
border-radius: 4px;
padding: 0.875rem;
@@ -75,7 +135,7 @@ code {
}
:not(pre) > code {
background: #1a1a1a;
background: var(--card);
padding: 0.125rem 0.375rem;
border-radius: 3px;
font-size: 0.875em;
@@ -91,7 +151,7 @@ code {
font-weight: 500;
letter-spacing: -0.02em;
margin-bottom: 0.5rem;
color: #fff;
color: var(--foreground);
}
@media (min-width: 640px) {
@@ -105,7 +165,7 @@ code {
font-weight: 500;
letter-spacing: 0;
text-transform: uppercase;
color: var(--muted);
color: var(--muted-foreground);
margin-top: 3rem;
margin-bottom: 1rem;
}
@@ -115,13 +175,14 @@ code {
font-weight: 500;
margin-top: 2rem;
margin-bottom: 0.75rem;
color: #ccc;
color: var(--foreground);
opacity: 0.85;
}
.prose p {
margin-bottom: 1.25rem;
line-height: 1.7;
color: var(--muted);
color: var(--muted-foreground);
font-size: 0.9375rem;
}
@@ -132,13 +193,14 @@ code {
.prose li {
margin-bottom: 0.5rem;
color: var(--muted);
color: var(--muted-foreground);
font-size: 0.9375rem;
line-height: 1.6;
}
.prose li strong {
color: #ccc;
color: var(--foreground);
opacity: 0.85;
font-weight: 500;
}
@@ -149,7 +211,7 @@ code {
}
.prose a:hover {
color: #fff;
color: var(--foreground);
}
.prose table {
@@ -167,16 +229,61 @@ code {
.prose th {
font-weight: 500;
color: var(--muted);
color: var(--muted-foreground);
text-transform: uppercase;
font-size: 0.75rem;
letter-spacing: 0.025em;
}
.prose td {
color: var(--muted);
color: var(--muted-foreground);
}
.prose td code {
color: var(--foreground);
}
/* Tool call shimmer animation */
@keyframes tool-shimmer {
0% { opacity: 0.5; }
50% { opacity: 1; }
100% { opacity: 0.5; }
}
.animate-tool-shimmer {
animation: tool-shimmer 1.5s ease-in-out infinite;
}
/* Dark mode: use page bg color for borders in chat message content */
.dark .docs-chat-content * {
border-color: var(--background);
}
/* Override prose text color inside chat content so agent responses appear brighter */
.docs-chat-content p,
.docs-chat-content li,
.docs-chat-content td {
color: var(--foreground);
opacity: 0.9;
}
/* Fix list rendering in chat content */
.docs-chat-content ul,
.docs-chat-content ol {
list-style-position: outside;
padding-left: 1.25em;
}
.docs-chat-content li > p {
display: inline;
margin: 0;
}
.docs-chat-content li {
margin-top: 0.5em;
margin-bottom: 0.5em;
}
button {
cursor: pointer;
}
+104
View File
@@ -0,0 +1,104 @@
export const metadata = { title: "Installation" }
# Installation
## npm (recommended)
```bash
npm install -g agent-browser
agent-browser install # Download Chromium
```
## Homebrew (macOS)
```bash
brew install agent-browser
agent-browser install # Download Chromium
```
## From source
```bash
git clone https://github.com/vercel-labs/agent-browser
cd agent-browser
pnpm install
pnpm build
pnpm build:native
./bin/agent-browser install
pnpm link --global
```
## Linux dependencies
On Linux, install system dependencies:
```bash
agent-browser install --with-deps
# or manually: npx playwright install-deps chromium
```
## Custom browser
Use a custom browser executable instead of bundled Chromium:
- **Serverless** - Use `@sparticuz/chromium` (~50MB vs ~684MB)
- **System browser** - Use existing Chrome installation
- **Custom builds** - Use modified browser builds
```bash
# Via flag
agent-browser --executable-path /path/to/chromium open example.com
# Via environment variable
AGENT_BROWSER_EXECUTABLE_PATH=/path/to/chromium agent-browser open example.com
```
### Serverless example
```typescript
import chromium from '@sparticuz/chromium';
import { BrowserManager } from 'agent-browser';
export async function handler() {
const browser = new BrowserManager();
await browser.launch({
executablePath: await chromium.executablePath(),
headless: true,
});
// ... use browser
}
```
## AI agent setup
agent-browser works with any AI agent out of the box. For richer context:
### AGENTS.md / CLAUDE.md
Add to your instructions file:
```markdown
## Browser Automation
Use `agent-browser` for web automation. Run `agent-browser --help` for all commands.
Core workflow:
1. `agent-browser open <url>` - Navigate to page
2. `agent-browser snapshot -i` - Get interactive elements with refs (@e1, @e2)
3. `agent-browser click @e1` / `fill @e2 "text"` - Interact using refs
4. Re-snapshot after page changes
```
### Claude Code skill
```bash
cp -r node_modules/agent-browser/skills/agent-browser .claude/skills/
```
Or download:
```bash
mkdir -p .claude/skills/agent-browser
curl -o .claude/skills/agent-browser/SKILL.md \
https://raw.githubusercontent.com/vercel-labs/agent-browser/main/skills/agent-browser/SKILL.md
```
-86
View File
@@ -1,86 +0,0 @@
import { CodeBlock } from "@/components/code-block";
export default function Installation() {
return (
<div className="max-w-2xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
<div className="prose">
<h1>Installation</h1>
<h2>npm (recommended)</h2>
<CodeBlock code={`npm install -g agent-browser
agent-browser install # Download Chromium`} />
<h2>Homebrew (macOS)</h2>
<CodeBlock
code={`brew install agent-browser
agent-browser install # Download Chromium`}
/>
<h2>From source</h2>
<CodeBlock code={`git clone https://github.com/vercel-labs/agent-browser
cd agent-browser
pnpm install
pnpm build
pnpm build:native
./bin/agent-browser install
pnpm link --global`} />
<h2>Linux dependencies</h2>
<p>On Linux, install system dependencies:</p>
<CodeBlock code={`agent-browser install --with-deps
# or manually: npx playwright install-deps chromium`} />
<h2>Custom browser</h2>
<p>
Use a custom browser executable instead of bundled Chromium:
</p>
<ul>
<li><strong>Serverless</strong> - Use <code>@sparticuz/chromium</code> (~50MB vs ~684MB)</li>
<li><strong>System browser</strong> - Use existing Chrome installation</li>
<li><strong>Custom builds</strong> - Use modified browser builds</li>
</ul>
<CodeBlock code={`# Via flag
agent-browser --executable-path /path/to/chromium open example.com
# Via environment variable
AGENT_BROWSER_EXECUTABLE_PATH=/path/to/chromium agent-browser open example.com`} />
<h3>Serverless example</h3>
<CodeBlock lang="typescript" code={`import chromium from '@sparticuz/chromium';
import { BrowserManager } from 'agent-browser';
export async function handler() {
const browser = new BrowserManager();
await browser.launch({
executablePath: await chromium.executablePath(),
headless: true,
});
// ... use browser
}`} />
<h2>AI agent setup</h2>
<p>agent-browser works with any AI agent out of the box. For richer context:</p>
<h3>AGENTS.md / CLAUDE.md</h3>
<p>Add to your instructions file:</p>
<CodeBlock lang="markdown" code={`## Browser Automation
Use \`agent-browser\` for web automation. Run \`agent-browser --help\` for all commands.
Core workflow:
1. \`agent-browser open <url>\` - Navigate to page
2. \`agent-browser snapshot -i\` - Get interactive elements with refs (@e1, @e2)
3. \`agent-browser click @e1\` / \`fill @e2 "text"\` - Interact using refs
4. Re-snapshot after page changes`} />
<h3>Claude Code skill</h3>
<CodeBlock code="cp -r node_modules/agent-browser/skills/agent-browser .claude/skills/" />
<p>Or download:</p>
<CodeBlock code={`mkdir -p .claude/skills/agent-browser
curl -o .claude/skills/agent-browser/SKILL.md \\
https://raw.githubusercontent.com/vercel-labs/agent-browser/main/skills/agent-browser/SKILL.md`} />
</div>
</div>
);
}
+199
View File
@@ -0,0 +1,199 @@
export const metadata = { title: "iOS Simulator" }
# iOS Simulator
Control real Mobile Safari in the iOS Simulator for authentic mobile
web testing. Uses Appium with XCUITest for native automation.
## Requirements
- macOS with Xcode installed
- iOS Simulator runtimes (download via Xcode)
- Appium with XCUITest driver
## Setup
```bash
# Install Appium globally
npm install -g appium
# Install the XCUITest driver for iOS
appium driver install xcuitest
```
## List available devices
See all iOS simulators available on your system:
```bash
agent-browser device list
# Output:
# Available iOS Simulators:
#
# ○ iPhone 16 Pro (iOS 18.0)
# F21EEC0D-7618-419F-811B-33AF27A8B2FD
# ○ iPhone 16 Pro Max (iOS 18.0)
# 50402807-C9B8-4D37-9F13-2E00E782C744
# ○ iPad Pro 13-inch (M4) (iOS 18.0)
# 3A6C6436-B909-4593-866D-91D1062BB070
# ...
```
## Basic usage
Use the `-p ios` flag to enable iOS mode. The workflow is
identical to desktop:
```bash
# Launch Safari on iPhone 16 Pro
agent-browser -p ios --device "iPhone 16 Pro" open https://example.com
# Get snapshot with refs (same as desktop)
agent-browser -p ios snapshot -i
# Interact using refs
agent-browser -p ios tap @e1
agent-browser -p ios fill @e2 "text"
# Take screenshot
agent-browser -p ios screenshot mobile.png
# Close session (shuts down simulator)
agent-browser -p ios close
```
## Mobile-specific commands
```bash
# Swipe gestures
agent-browser -p ios swipe up
agent-browser -p ios swipe down
agent-browser -p ios swipe left
agent-browser -p ios swipe right
# Swipe with distance (pixels)
agent-browser -p ios swipe up 500
# Tap (alias for click, semantically clearer for touch)
agent-browser -p ios tap @e1
```
## Environment variables
Configure iOS mode via environment variables:
```bash
export AGENT_BROWSER_PROVIDER=ios
export AGENT_BROWSER_IOS_DEVICE="iPhone 16 Pro"
# Now all commands use iOS
agent-browser open https://example.com
agent-browser snapshot -i
agent-browser tap @e1
```
| Variable | Description |
| --- | --- |
| `AGENT_BROWSER_PROVIDER` | Set to `ios` to enable iOS mode |
| `AGENT_BROWSER_IOS_DEVICE` | Device name (e.g., "iPhone 16 Pro") |
| `AGENT_BROWSER_IOS_UDID` | Device UDID (alternative to device name) |
## Supported devices
All iOS Simulators available in Xcode are supported, including:
- All iPhone models (iPhone 15, 16, 17, SE, etc.)
- All iPad models (iPad Pro, iPad Air, iPad mini, etc.)
- Multiple iOS versions (17.x, 18.x, etc.)
**Real devices** are also supported via USB connection (see below).
## Real device support
Appium can control Safari on real iOS devices connected via USB. This
requires additional one-time setup.
### 1. Get your device UDID
```bash
# List connected devices
xcrun xctrace list devices
# Or via system profiler
system_profiler SPUSBDataType | grep -A 5 "iPhone\|iPad"
```
### 2. Sign WebDriverAgent (one-time)
WebDriverAgent needs to be signed with your Apple Developer
certificate to run on real devices.
```bash
# Open the WebDriverAgent Xcode project
cd ~/.appium/node_modules/appium-xcuitest-driver/node_modules/appium-webdriveragent
open WebDriverAgent.xcodeproj
```
In Xcode:
1. Select the `WebDriverAgentRunner` target
2. Go to Signing & Capabilities
3. Select your Team (requires Apple Developer account, free tier works)
4. Let Xcode manage signing automatically
### 3. Use with agent-browser
```bash
# Connect device via USB, then use the UDID
agent-browser -p ios --device "<DEVICE_UDID>" open https://example.com
# Or use the device name if unique
agent-browser -p ios --device "John's iPhone" open https://example.com
```
### Real device notes
- First run installs WebDriverAgent to the device (may require Trust prompt on device)
- Device must be unlocked and connected via USB
- Slightly slower initial connection than simulator
- Tests against real Safari performance and behavior
- On first install, go to Settings → General → VPN & Device Management to trust the developer certificate
## Performance notes
- **First launch:** Takes 30-60 seconds to boot the simulator and start Appium
- **Subsequent commands:** Fast (simulator stays running)
- **Close command:** Shuts down simulator and Appium server
## Differences from desktop
| Feature | Desktop | iOS |
| --- | --- | --- |
| Browser | Chromium/Firefox/WebKit | Safari only |
| Tabs | Supported | Single tab only |
| PDF export | Supported | Not supported |
| Screencast | Supported | Not supported |
| Swipe gestures | Not native | Native support |
## Troubleshooting
### Appium not found
```bash
# Make sure Appium is installed globally
npm install -g appium
appium driver install xcuitest
# Verify installation
appium --version
```
### No simulators available
Open Xcode and download iOS Simulator runtimes from **Settings → Platforms**.
### Simulator won't boot
Try booting the simulator manually from Xcode or the Simulator app to
ensure it works, then retry with agent-browser.
-280
View File
@@ -1,280 +0,0 @@
import { CodeBlock } from "@/components/code-block";
export default function iOS() {
return (
<div className="max-w-2xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
<div className="prose">
<h1>iOS Simulator</h1>
<p>
Control real Mobile Safari in the iOS Simulator for authentic mobile
web testing. Uses Appium with XCUITest for native automation.
</p>
<h2>Requirements</h2>
<ul>
<li>macOS with Xcode installed</li>
<li>iOS Simulator runtimes (download via Xcode)</li>
<li>Appium with XCUITest driver</li>
</ul>
<h2>Setup</h2>
<CodeBlock
code={`# Install Appium globally
npm install -g appium
# Install the XCUITest driver for iOS
appium driver install xcuitest`}
/>
<h2>List available devices</h2>
<p>See all iOS simulators available on your system:</p>
<CodeBlock
code={`agent-browser device list
# Output:
# Available iOS Simulators:
#
# iPhone 16 Pro (iOS 18.0)
# F21EEC0D-7618-419F-811B-33AF27A8B2FD
# iPhone 16 Pro Max (iOS 18.0)
# 50402807-C9B8-4D37-9F13-2E00E782C744
# iPad Pro 13-inch (M4) (iOS 18.0)
# 3A6C6436-B909-4593-866D-91D1062BB070
# ...`}
/>
<h2>Basic usage</h2>
<p>
Use the <code>-p ios</code> flag to enable iOS mode. The workflow is
identical to desktop:
</p>
<CodeBlock
code={`# Launch Safari on iPhone 16 Pro
agent-browser -p ios --device "iPhone 16 Pro" open https://example.com
# Get snapshot with refs (same as desktop)
agent-browser -p ios snapshot -i
# Interact using refs
agent-browser -p ios tap @e1
agent-browser -p ios fill @e2 "text"
# Take screenshot
agent-browser -p ios screenshot mobile.png
# Close session (shuts down simulator)
agent-browser -p ios close`}
/>
<h2>Mobile-specific commands</h2>
<CodeBlock
code={`# Swipe gestures
agent-browser -p ios swipe up
agent-browser -p ios swipe down
agent-browser -p ios swipe left
agent-browser -p ios swipe right
# Swipe with distance (pixels)
agent-browser -p ios swipe up 500
# Tap (alias for click, semantically clearer for touch)
agent-browser -p ios tap @e1`}
/>
<h2>Environment variables</h2>
<p>Configure iOS mode via environment variables:</p>
<CodeBlock
code={`export AGENT_BROWSER_PROVIDER=ios
export AGENT_BROWSER_IOS_DEVICE="iPhone 16 Pro"
# Now all commands use iOS
agent-browser open https://example.com
agent-browser snapshot -i
agent-browser tap @e1`}
/>
<table>
<thead>
<tr>
<th>Variable</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code>AGENT_BROWSER_PROVIDER</code>
</td>
<td>
Set to <code>ios</code> to enable iOS mode
</td>
</tr>
<tr>
<td>
<code>AGENT_BROWSER_IOS_DEVICE</code>
</td>
<td>Device name (e.g., &quot;iPhone 16 Pro&quot;)</td>
</tr>
<tr>
<td>
<code>AGENT_BROWSER_IOS_UDID</code>
</td>
<td>Device UDID (alternative to device name)</td>
</tr>
</tbody>
</table>
<h2>Supported devices</h2>
<p>
All iOS Simulators available in Xcode are supported, including:
</p>
<ul>
<li>All iPhone models (iPhone 15, 16, 17, SE, etc.)</li>
<li>All iPad models (iPad Pro, iPad Air, iPad mini, etc.)</li>
<li>Multiple iOS versions (17.x, 18.x, etc.)</li>
</ul>
<p>
<strong>Real devices</strong> are also supported via USB connection
(see below).
</p>
<h2>Real device support</h2>
<p>
Appium can control Safari on real iOS devices connected via USB. This
requires additional one-time setup.
</p>
<h3>1. Get your device UDID</h3>
<CodeBlock
code={`# List connected devices
xcrun xctrace list devices
# Or via system profiler
system_profiler SPUSBDataType | grep -A 5 "iPhone\\|iPad"`}
/>
<h3>2. Sign WebDriverAgent (one-time)</h3>
<p>
WebDriverAgent needs to be signed with your Apple Developer
certificate to run on real devices.
</p>
<CodeBlock
code={`# Open the WebDriverAgent Xcode project
cd ~/.appium/node_modules/appium-xcuitest-driver/node_modules/appium-webdriveragent
open WebDriverAgent.xcodeproj`}
/>
<p>In Xcode:</p>
<ol>
<li>
Select the <code>WebDriverAgentRunner</code> target
</li>
<li>Go to Signing &amp; Capabilities</li>
<li>
Select your Team (requires Apple Developer account, free tier works)
</li>
<li>Let Xcode manage signing automatically</li>
</ol>
<h3>3. Use with agent-browser</h3>
<CodeBlock
code={`# Connect device via USB, then use the UDID
agent-browser -p ios --device "<DEVICE_UDID>" open https://example.com
# Or use the device name if unique
agent-browser -p ios --device "John's iPhone" open https://example.com`}
/>
<h3>Real device notes</h3>
<ul>
<li>
First run installs WebDriverAgent to the device (may require Trust
prompt on device)
</li>
<li>Device must be unlocked and connected via USB</li>
<li>Slightly slower initial connection than simulator</li>
<li>Tests against real Safari performance and behavior</li>
<li>
On first install, go to Settings &rarr; General &rarr; VPN &amp;
Device Management to trust the developer certificate
</li>
</ul>
<h2>Performance notes</h2>
<ul>
<li>
<strong>First launch:</strong> Takes 30-60 seconds to boot the
simulator and start Appium
</li>
<li>
<strong>Subsequent commands:</strong> Fast (simulator stays running)
</li>
<li>
<strong>Close command:</strong> Shuts down simulator and Appium
server
</li>
</ul>
<h2>Differences from desktop</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Desktop</th>
<th>iOS</th>
</tr>
</thead>
<tbody>
<tr>
<td>Browser</td>
<td>Chromium/Firefox/WebKit</td>
<td>Safari only</td>
</tr>
<tr>
<td>Tabs</td>
<td>Supported</td>
<td>Single tab only</td>
</tr>
<tr>
<td>PDF export</td>
<td>Supported</td>
<td>Not supported</td>
</tr>
<tr>
<td>Screencast</td>
<td>Supported</td>
<td>Not supported</td>
</tr>
<tr>
<td>Swipe gestures</td>
<td>Not native</td>
<td>Native support</td>
</tr>
</tbody>
</table>
<h2>Troubleshooting</h2>
<h3>Appium not found</h3>
<CodeBlock
code={`# Make sure Appium is installed globally
npm install -g appium
appium driver install xcuitest
# Verify installation
appium --version`}
/>
<h3>No simulators available</h3>
<p>
Open Xcode and download iOS Simulator runtimes from{" "}
<strong>Settings &rarr; Platforms</strong>.
</p>
<h3>Simulator won&apos;t boot</h3>
<p>
Try booting the simulator manually from Xcode or the Simulator app to
ensure it works, then retry with agent-browser.
</p>
</div>
</div>
);
}
+20 -11
View File
@@ -1,9 +1,11 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { ThemeProvider } from "@/components/theme-provider";
import { MobileNavProvider } from "@/components/mobile-nav-context";
import { Header } from "@/components/header";
import { Sidebar } from "@/components/sidebar";
import { DocsChat } from "@/components/docs-chat";
const geist = Geist({
variable: "--font-geist",
@@ -26,19 +28,26 @@ export default function RootLayout({
children: React.ReactNode;
}>) {
return (
<html lang="en" className="dark">
<html lang="en" suppressHydrationWarning>
<body
className={`${geist.variable} ${geistMono.variable} antialiased bg-zinc-950 text-zinc-100`}
className={`${geist.variable} ${geistMono.variable} antialiased bg-background text-foreground`}
>
<MobileNavProvider>
<Header />
<div className="flex min-h-[calc(100vh-3.5rem)]">
<Sidebar />
<main className="flex-1 overflow-auto">
{children}
</main>
</div>
</MobileNavProvider>
<ThemeProvider>
<MobileNavProvider>
<Header />
<div className="flex min-h-[calc(100vh-3.5rem)]">
<Sidebar />
<main className="flex-1 overflow-auto">
<div className="max-w-2xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
<div className="prose">
{children}
</div>
</div>
</main>
</div>
<DocsChat />
</MobileNavProvider>
</ThemeProvider>
</body>
</html>
);
+63
View File
@@ -0,0 +1,63 @@
export const metadata = { title: "agent-browser" }
# agent-browser
Browser automation CLI designed for AI agents. Compact text output minimizes context usage. Fast Rust CLI with Node.js fallback.
```bash
npm install -g agent-browser # all platforms
brew install agent-browser # macOS
```
## Features
- **Agent-first** - Compact text output uses fewer tokens than JSON, designed for AI context efficiency
- **Ref-based** - Snapshot returns accessibility tree with refs for deterministic element selection
- **Fast** - Native Rust CLI for instant command parsing
- **Complete** - 50+ commands for navigation, forms, screenshots, network, storage
- **Sessions** - Multiple isolated browser instances with separate auth
- **Cross-platform** - macOS, Linux, Windows with native binaries
## Works with
Claude Code, Cursor, GitHub Copilot, OpenAI Codex, Google Gemini, opencode, and any agent that can run shell commands.
## Example
```bash
# Navigate and get snapshot
agent-browser open example.com
agent-browser snapshot -i
# Output:
# - heading "Example Domain" [ref=e1]
# - link "More information..." [ref=e2]
# Interact using refs
agent-browser click @e2
agent-browser screenshot page.png
agent-browser close
```
## Why refs?
The `snapshot` command returns a compact accessibility tree where each element
has a unique ref like `@e1`, `@e2`. This provides:
- **Context-efficient** - Text output uses ~200-400 tokens vs ~3000-5000 for full DOM
- **Deterministic** - Ref points to exact element from snapshot
- **Fast** - No DOM re-query needed
- **AI-friendly** - LLMs parse text output naturally
## Architecture
Client-daemon architecture for optimal performance:
1. **Rust CLI** - Parses commands, communicates with daemon
2. **Node.js Daemon** - Manages Playwright browser instance
Daemon starts automatically and persists between commands.
## Platforms
Native Rust binaries for macOS (ARM64, x64), Linux (ARM64, x64), and Windows (x64).
-78
View File
@@ -1,78 +0,0 @@
import { CodeBlock } from "@/components/code-block";
export default function Home() {
return (
<div className="max-w-2xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
<div className="prose">
<h1>agent-browser</h1>
<p>
Browser automation CLI designed for AI agents. Compact text output minimizes context usage. Fast Rust CLI with Node.js fallback.
</p>
<CodeBlock
code={`
npm install -g agent-browser # all platforms
brew install agent-browser # macOS`}
/>
<h2>Features</h2>
<ul>
<li><strong>Agent-first</strong> - Compact text output uses fewer tokens than JSON, designed for AI context efficiency</li>
<li><strong>Ref-based</strong> - Snapshot returns accessibility tree with refs for deterministic element selection</li>
<li><strong>Fast</strong> - Native Rust CLI for instant command parsing</li>
<li><strong>Complete</strong> - 50+ commands for navigation, forms, screenshots, network, storage</li>
<li><strong>Sessions</strong> - Multiple isolated browser instances with separate auth</li>
<li><strong>Cross-platform</strong> - macOS, Linux, Windows with native binaries</li>
</ul>
<h2>Works with</h2>
<p>
Claude Code, Cursor, GitHub Copilot, OpenAI Codex, Google Gemini, opencode, and any agent that can run shell commands.
</p>
<h2>Example</h2>
<CodeBlock code={`# Navigate and get snapshot
agent-browser open example.com
agent-browser snapshot -i
# Output:
# - heading "Example Domain" [ref=e1]
# - link "More information..." [ref=e2]
# Interact using refs
agent-browser click @e2
agent-browser screenshot page.png
agent-browser close`} />
<h2>Why refs?</h2>
<p>
The <code>snapshot</code> command returns a compact accessibility tree where each element
has a unique ref like <code>@e1</code>, <code>@e2</code>. This provides:
</p>
<ul>
<li><strong>Context-efficient</strong> - Text output uses ~200-400 tokens vs ~3000-5000 for full DOM</li>
<li><strong>Deterministic</strong> - Ref points to exact element from snapshot</li>
<li><strong>Fast</strong> - No DOM re-query needed</li>
<li><strong>AI-friendly</strong> - LLMs parse text output naturally</li>
</ul>
<h2>Architecture</h2>
<p>
Client-daemon architecture for optimal performance:
</p>
<ol>
<li><strong>Rust CLI</strong> - Parses commands, communicates with daemon</li>
<li><strong>Node.js Daemon</strong> - Manages Playwright browser instance</li>
</ol>
<p>
Daemon starts automatically and persists between commands.
</p>
<h2>Platforms</h2>
<p>
Native Rust binaries for macOS (ARM64, x64), Linux (ARM64, x64), and Windows (x64).
</p>
</div>
</div>
);
}
+75
View File
@@ -0,0 +1,75 @@
export const metadata = { title: "Quick Start" }
# Quick Start
## Core workflow
Every browser automation follows this pattern:
```bash
# 1. Navigate
agent-browser open example.com
# 2. Snapshot to get element refs
agent-browser snapshot -i
# Output:
# @e1 [heading] "Example Domain"
# @e2 [link] "More information..."
# 3. Interact using refs
agent-browser click @e2
# 4. Re-snapshot after page changes
agent-browser snapshot -i
```
## Common commands
```bash
agent-browser open example.com
agent-browser snapshot -i # Get interactive elements with refs
agent-browser click @e2 # Click by ref
agent-browser fill @e3 "test@example.com" # Fill input by ref
agent-browser get text @e1 # Get text content
agent-browser screenshot # Save to temp directory
agent-browser screenshot page.png # Save to specific path
agent-browser close
```
## Traditional selectors
CSS selectors and semantic locators also supported:
```bash
agent-browser click "#submit"
agent-browser fill "#email" "test@example.com"
agent-browser find role button click --name "Submit"
```
## Headed mode
Show browser window for debugging:
```bash
agent-browser open example.com --headed
```
## Wait for content
```bash
agent-browser wait @e1 # Wait for element
agent-browser wait --load networkidle # Wait for network idle
agent-browser wait --url "**/dashboard" # Wait for URL pattern
agent-browser wait 2000 # Wait milliseconds
```
## JSON output
For programmatic parsing in scripts:
```bash
agent-browser snapshot --json
agent-browser get text @e1 --json
```
Note: The default text output is more compact and preferred for AI agents.
-62
View File
@@ -1,62 +0,0 @@
import { CodeBlock } from "@/components/code-block";
export default function QuickStart() {
return (
<div className="max-w-2xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
<div className="prose">
<h1>Quick Start</h1>
<h2>Core workflow</h2>
<p>Every browser automation follows this pattern:</p>
<CodeBlock code={`# 1. Navigate
agent-browser open example.com
# 2. Snapshot to get element refs
agent-browser snapshot -i
# Output:
# @e1 [heading] "Example Domain"
# @e2 [link] "More information..."
# 3. Interact using refs
agent-browser click @e2
# 4. Re-snapshot after page changes
agent-browser snapshot -i`} />
<h2>Common commands</h2>
<CodeBlock code={`agent-browser open example.com
agent-browser snapshot -i # Get interactive elements with refs
agent-browser click @e2 # Click by ref
agent-browser fill @e3 "test@example.com" # Fill input by ref
agent-browser get text @e1 # Get text content
agent-browser screenshot # Save to temp directory
agent-browser screenshot page.png # Save to specific path
agent-browser close`} />
<h2>Traditional selectors</h2>
<p>CSS selectors and semantic locators also supported:</p>
<CodeBlock code={`agent-browser click "#submit"
agent-browser fill "#email" "test@example.com"
agent-browser find role button click --name "Submit"`} />
<h2>Headed mode</h2>
<p>Show browser window for debugging:</p>
<CodeBlock code="agent-browser open example.com --headed" />
<h2>Wait for content</h2>
<CodeBlock code={`agent-browser wait @e1 # Wait for element
agent-browser wait --load networkidle # Wait for network idle
agent-browser wait --url "**/dashboard" # Wait for URL pattern
agent-browser wait 2000 # Wait milliseconds`} />
<h2>JSON output</h2>
<p>For programmatic parsing in scripts:</p>
<CodeBlock code={`agent-browser snapshot --json
agent-browser get text @e1 --json`} />
<p>
Note: The default text output is more compact and preferred for AI agents.
</p>
</div>
</div>
);
}
+56
View File
@@ -0,0 +1,56 @@
export const metadata = { title: "Selectors" }
# Selectors
## Refs (recommended)
Refs provide deterministic element selection from snapshots. Best for AI agents.
```bash
# 1. Get snapshot with refs
agent-browser snapshot
# Output:
# - heading "Example Domain" [ref=e1] [level=1]
# - button "Submit" [ref=e2]
# - textbox "Email" [ref=e3]
# - link "Learn more" [ref=e4]
# 2. Use refs to interact
agent-browser click @e2 # Click the button
agent-browser fill @e3 "test@example.com" # Fill the textbox
agent-browser get text @e1 # Get heading text
agent-browser hover @e4 # Hover the link
```
### Why refs?
- **Deterministic** - Ref points to exact element from snapshot
- **Fast** - No DOM re-query needed
- **AI-friendly** - LLMs can reliably parse and use refs
## CSS selectors
```bash
agent-browser click "#id"
agent-browser click ".class"
agent-browser click "div > button"
agent-browser click "[data-testid='submit']"
```
## Text & XPath
```bash
agent-browser click "text=Submit"
agent-browser click "xpath=//button[@type='submit']"
```
## Semantic locators
Find elements by role, label, or other semantic properties:
```bash
agent-browser find role button click --name "Submit"
agent-browser find label "Email" fill "test@test.com"
agent-browser find placeholder "Search..." fill "query"
agent-browser find testid "submit-btn" click
```
-53
View File
@@ -1,53 +0,0 @@
import { CodeBlock } from "@/components/code-block";
export default function Selectors() {
return (
<div className="max-w-2xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
<div className="prose">
<h1>Selectors</h1>
<h2>Refs (recommended)</h2>
<p>
Refs provide deterministic element selection from snapshots. Best for AI agents.
</p>
<CodeBlock code={`# 1. Get snapshot with refs
agent-browser snapshot
# Output:
# - heading "Example Domain" [ref=e1] [level=1]
# - button "Submit" [ref=e2]
# - textbox "Email" [ref=e3]
# - link "Learn more" [ref=e4]
# 2. Use refs to interact
agent-browser click @e2 # Click the button
agent-browser fill @e3 "test@example.com" # Fill the textbox
agent-browser get text @e1 # Get heading text
agent-browser hover @e4 # Hover the link`} />
<h3>Why refs?</h3>
<ul>
<li><strong>Deterministic</strong> - Ref points to exact element from snapshot</li>
<li><strong>Fast</strong> - No DOM re-query needed</li>
<li><strong>AI-friendly</strong> - LLMs can reliably parse and use refs</li>
</ul>
<h2>CSS selectors</h2>
<CodeBlock code={`agent-browser click "#id"
agent-browser click ".class"
agent-browser click "div > button"
agent-browser click "[data-testid='submit']"`} />
<h2>Text & XPath</h2>
<CodeBlock code={`agent-browser click "text=Submit"
agent-browser click "xpath=//button[@type='submit']"`} />
<h2>Semantic locators</h2>
<p>Find elements by role, label, or other semantic properties:</p>
<CodeBlock code={`agent-browser find role button click --name "Submit"
agent-browser find label "Email" fill "test@test.com"
agent-browser find placeholder "Search..." fill "query"
agent-browser find testid "submit-btn" click`} />
</div>
</div>
);
}
+94
View File
@@ -0,0 +1,94 @@
export const metadata = { title: "Sessions" }
# Sessions
Run multiple isolated browser instances:
```bash
# Different sessions
agent-browser --session agent1 open site-a.com
agent-browser --session agent2 open site-b.com
# Or via environment variable
AGENT_BROWSER_SESSION=agent1 agent-browser click "#btn"
# List active sessions
agent-browser session list
# Output:
# Active sessions:
# -> default
# agent1
# Show current session
agent-browser session
```
## Session isolation
Each session has its own:
- Browser instance
- Cookies and storage
- Navigation history
- Authentication state
## Persistent profiles
By default, browser state is lost when the browser closes. Use `--profile` to persist state across restarts:
```bash
# Use a persistent profile directory
agent-browser --profile ~/.myapp-profile open myapp.com
# Login once, then reuse the authenticated session
agent-browser --profile ~/.myapp-profile open myapp.com/dashboard
# Or via environment variable
AGENT_BROWSER_PROFILE=~/.myapp-profile agent-browser open myapp.com
```
The profile directory stores:
- Cookies and localStorage
- IndexedDB data
- Service workers
- Browser cache
- Login sessions
## Authenticated sessions
Use `--headers` to set HTTP headers for a specific origin:
```bash
# Headers scoped to api.example.com only
agent-browser open api.example.com --headers '{"Authorization": "Bearer <token>"}'
# Requests to api.example.com include the auth header
agent-browser snapshot -i --json
agent-browser click @e2
# Navigate to another domain - headers NOT sent
agent-browser open other-site.com
```
Useful for:
- **Skipping login flows** - Authenticate via headers
- **Switching users** - Different auth tokens per session
- **API testing** - Access protected endpoints
- **Security** - Headers scoped to origin, not leaked
## Multiple origins
```bash
agent-browser open api.example.com --headers '{"Authorization": "Bearer token1"}'
agent-browser open api.acme.com --headers '{"Authorization": "Bearer token2"}'
```
## Global headers
For headers on all domains:
```bash
agent-browser set headers '{"X-Custom-Header": "value"}'
```
-85
View File
@@ -1,85 +0,0 @@
import { CodeBlock } from "@/components/code-block";
export default function Sessions() {
return (
<div className="max-w-2xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
<div className="prose">
<h1>Sessions</h1>
<p>Run multiple isolated browser instances:</p>
<CodeBlock code={`# Different sessions
agent-browser --session agent1 open site-a.com
agent-browser --session agent2 open site-b.com
# Or via environment variable
AGENT_BROWSER_SESSION=agent1 agent-browser click "#btn"
# List active sessions
agent-browser session list
# Output:
# Active sessions:
# -> default
# agent1
# Show current session
agent-browser session`} />
<h2>Session isolation</h2>
<p>Each session has its own:</p>
<ul>
<li>Browser instance</li>
<li>Cookies and storage</li>
<li>Navigation history</li>
<li>Authentication state</li>
</ul>
<h2>Persistent profiles</h2>
<p>By default, browser state is lost when the browser closes. Use <code>--profile</code> to persist state across restarts:</p>
<CodeBlock code={`# Use a persistent profile directory
agent-browser --profile ~/.myapp-profile open myapp.com
# Login once, then reuse the authenticated session
agent-browser --profile ~/.myapp-profile open myapp.com/dashboard
# Or via environment variable
AGENT_BROWSER_PROFILE=~/.myapp-profile agent-browser open myapp.com`} />
<p>The profile directory stores:</p>
<ul>
<li>Cookies and localStorage</li>
<li>IndexedDB data</li>
<li>Service workers</li>
<li>Browser cache</li>
<li>Login sessions</li>
</ul>
<h2>Authenticated sessions</h2>
<p>
Use <code>--headers</code> to set HTTP headers for a specific origin:
</p>
<CodeBlock code={`# Headers scoped to api.example.com only
agent-browser open api.example.com --headers '{"Authorization": "Bearer <token>"}'
# Requests to api.example.com include the auth header
agent-browser snapshot -i --json
agent-browser click @e2
# Navigate to another domain - headers NOT sent
agent-browser open other-site.com`} />
<p>Useful for:</p>
<ul>
<li><strong>Skipping login flows</strong> - Authenticate via headers</li>
<li><strong>Switching users</strong> - Different auth tokens per session</li>
<li><strong>API testing</strong> - Access protected endpoints</li>
<li><strong>Security</strong> - Headers scoped to origin, not leaked</li>
</ul>
<h2>Multiple origins</h2>
<CodeBlock code={`agent-browser open api.example.com --headers '{"Authorization": "Bearer token1"}'
agent-browser open api.acme.com --headers '{"Authorization": "Bearer token2"}'`} />
<h2>Global headers</h2>
<p>For headers on all domains:</p>
<CodeBlock code={`agent-browser set headers '{"X-Custom-Header": "value"}'`} />
</div>
</div>
);
}
+97
View File
@@ -0,0 +1,97 @@
export const metadata = { title: "Snapshots" }
# Snapshots
The `snapshot` command returns a compact accessibility tree with refs for element interaction.
## Options
Filter output to reduce size:
```bash
agent-browser snapshot # Full accessibility tree
agent-browser snapshot -i # Interactive elements only (recommended)
agent-browser snapshot -i -C # Include cursor-interactive elements
agent-browser snapshot -c # Compact (remove empty elements)
agent-browser snapshot -d 3 # Limit depth to 3 levels
agent-browser snapshot -s "#main" # Scope to CSS selector
agent-browser snapshot -i -c -d 5 # Combine options
```
| Option | Description |
| --- | --- |
| `-i, --interactive` | Only interactive elements (buttons, links, inputs) |
| `-C, --cursor` | Include cursor-interactive elements (cursor:pointer, onclick, tabindex) |
| `-c, --compact` | Remove empty structural elements |
| `-d, --depth` | Limit tree depth |
| `-s, --selector` | Scope to CSS selector |
## Cursor-interactive elements
Many modern web apps use custom clickable elements (divs, spans) instead of standard buttons or links.
The `-C` flag detects these by looking for:
- `cursor: pointer` CSS style
- `onclick` attribute or handler
- `tabindex` attribute (keyboard focusable)
```bash
agent-browser snapshot -i -C
# Output includes:
# @e1 [button] "Submit"
# @e2 [link] "Learn more"
# Cursor-interactive elements:
# @e3 [clickable] "Menu Item" [cursor:pointer, onclick]
# @e4 [clickable] "Card" [cursor:pointer]
```
## Output format
The default text output is compact and AI-friendly:
```bash
agent-browser snapshot -i
# Output:
# @e1 [heading] "Example Domain" [level=1]
# @e2 [button] "Submit"
# @e3 [input type="email"] placeholder="Email"
# @e4 [link] "Learn more"
```
## Using refs
Refs from the snapshot map directly to commands:
```bash
agent-browser click @e2 # Click the Submit button
agent-browser fill @e3 "a@b.com" # Fill the email input
agent-browser get text @e1 # Get heading text
```
## Ref lifecycle
Refs are invalidated when the page changes. Always re-snapshot after navigation or DOM updates:
```bash
agent-browser click @e4 # Navigates to new page
agent-browser snapshot -i # Get fresh refs
agent-browser click @e1 # Use new refs
```
## Best practices
1. Use `-i` to reduce output to actionable elements
2. Re-snapshot after page changes to get updated refs
3. Scope with `-s` for specific page sections
4. Use `-d` to limit depth on complex pages
## JSON output
For programmatic parsing in scripts:
```bash
agent-browser snapshot --json
# {"success":true,"data":{"snapshot":"...","refs":{"e1":{"role":"heading","name":"Title"},...}}}
```
Note: JSON uses more tokens than text output. The default text format is preferred for AI agents.
-112
View File
@@ -1,112 +0,0 @@
import { CodeBlock } from "@/components/code-block";
export default function Snapshots() {
return (
<div className="max-w-2xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
<div className="prose">
<h1>Snapshots</h1>
<p>
The <code>snapshot</code> command returns a compact accessibility tree with refs for element interaction.
</p>
<h2>Options</h2>
<p>Filter output to reduce size:</p>
<CodeBlock code={`agent-browser snapshot # Full accessibility tree
agent-browser snapshot -i # Interactive elements only (recommended)
agent-browser snapshot -i -C # Include cursor-interactive elements
agent-browser snapshot -c # Compact (remove empty elements)
agent-browser snapshot -d 3 # Limit depth to 3 levels
agent-browser snapshot -s "#main" # Scope to CSS selector
agent-browser snapshot -i -c -d 5 # Combine options`} />
<table>
<thead>
<tr>
<th>Option</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>-i, --interactive</code></td>
<td>Only interactive elements (buttons, links, inputs)</td>
</tr>
<tr>
<td><code>-C, --cursor</code></td>
<td>Include cursor-interactive elements (cursor:pointer, onclick, tabindex)</td>
</tr>
<tr>
<td><code>-c, --compact</code></td>
<td>Remove empty structural elements</td>
</tr>
<tr>
<td><code>-d, --depth</code></td>
<td>Limit tree depth</td>
</tr>
<tr>
<td><code>-s, --selector</code></td>
<td>Scope to CSS selector</td>
</tr>
</tbody>
</table>
<h2>Cursor-interactive elements</h2>
<p>
Many modern web apps use custom clickable elements (divs, spans) instead of standard buttons or links.
The <code>-C</code> flag detects these by looking for:
</p>
<ul>
<li><code>cursor: pointer</code> CSS style</li>
<li><code>onclick</code> attribute or handler</li>
<li><code>tabindex</code> attribute (keyboard focusable)</li>
</ul>
<CodeBlock code={`agent-browser snapshot -i -C
# Output includes:
# @e1 [button] "Submit"
# @e2 [link] "Learn more"
# Cursor-interactive elements:
# @e3 [clickable] "Menu Item" [cursor:pointer, onclick]
# @e4 [clickable] "Card" [cursor:pointer]`} />
<h2>Output format</h2>
<p>The default text output is compact and AI-friendly:</p>
<CodeBlock code={`agent-browser snapshot -i
# Output:
# @e1 [heading] "Example Domain" [level=1]
# @e2 [button] "Submit"
# @e3 [input type="email"] placeholder="Email"
# @e4 [link] "Learn more"`} />
<h2>Using refs</h2>
<p>Refs from the snapshot map directly to commands:</p>
<CodeBlock code={`agent-browser click @e2 # Click the Submit button
agent-browser fill @e3 "a@b.com" # Fill the email input
agent-browser get text @e1 # Get heading text`} />
<h2>Ref lifecycle</h2>
<p>
Refs are invalidated when the page changes. Always re-snapshot after navigation or DOM updates:
</p>
<CodeBlock code={`agent-browser click @e4 # Navigates to new page
agent-browser snapshot -i # Get fresh refs
agent-browser click @e1 # Use new refs`} />
<h2>Best practices</h2>
<ol>
<li>Use <code>-i</code> to reduce output to actionable elements</li>
<li>Re-snapshot after page changes to get updated refs</li>
<li>Scope with <code>-s</code> for specific page sections</li>
<li>Use <code>-d</code> to limit depth on complex pages</li>
</ol>
<h2>JSON output</h2>
<p>For programmatic parsing in scripts:</p>
<CodeBlock code={`agent-browser snapshot --json
# {"success":true,"data":{"snapshot":"...","refs":{"e1":{"role":"heading","name":"Title"},...}}}`} />
<p>
Note: JSON uses more tokens than text output. The default text format is preferred for AI agents.
</p>
</div>
</div>
);
}
@@ -1,32 +1,31 @@
import { CodeBlock } from "@/components/code-block";
export const metadata = { title: "Streaming" }
export default function Streaming() {
return (
<div className="max-w-2xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
<div className="prose">
<h1>Streaming</h1>
<p>
Stream the browser viewport via WebSocket for live preview or &quot;pair browsing&quot;
where a human can watch and interact alongside an AI agent.
</p>
# Streaming
<h2>Enable streaming</h2>
<p>
Set the <code>AGENT_BROWSER_STREAM_PORT</code> environment variable to start
a WebSocket server:
</p>
<CodeBlock code={`AGENT_BROWSER_STREAM_PORT=9223 agent-browser open example.com`} />
Stream the browser viewport via WebSocket for live preview or "pair browsing"
where a human can watch and interact alongside an AI agent.
<p>
The server streams viewport frames and accepts input events (mouse, keyboard, touch).
</p>
## Enable streaming
<h2>WebSocket protocol</h2>
<p>Connect to <code>ws://localhost:9223</code> to receive frames and send input.</p>
Set the `AGENT_BROWSER_STREAM_PORT` environment variable to start
a WebSocket server:
<h3>Frame messages</h3>
<p>The server sends frame messages with base64-encoded images:</p>
<CodeBlock code={`{
```bash
AGENT_BROWSER_STREAM_PORT=9223 agent-browser open example.com
```
The server streams viewport frames and accepts input events (mouse, keyboard, touch).
## WebSocket protocol
Connect to `ws://localhost:9223` to receive frames and send input.
### Frame messages
The server sends frame messages with base64-encoded images:
```json
{
"type": "frame",
"data": "<base64-encoded-jpeg>",
"metadata": {
@@ -37,23 +36,31 @@ export default function Streaming() {
"scrollOffsetX": 0,
"scrollOffsetY": 0
}
}`} />
}
```
<h3>Status messages</h3>
<p>Connection and screencast status:</p>
<CodeBlock code={`{
### Status messages
Connection and screencast status:
```json
{
"type": "status",
"connected": true,
"screencasting": true,
"viewportWidth": 1280,
"viewportHeight": 720
}`} />
}
```
<h2>Input injection</h2>
<p>Send input events to control the browser remotely.</p>
## Input injection
<h3>Mouse events</h3>
<CodeBlock code={`// Click
Send input events to control the browser remotely.
### Mouse events
```json
// Click
{
"type": "input_mouse",
"eventType": "mousePressed",
@@ -88,10 +95,13 @@ export default function Streaming() {
"y": 200,
"deltaX": 0,
"deltaY": 100
}`} />
}
```
<h3>Keyboard events</h3>
<CodeBlock code={`// Key down
### Keyboard events
```json
// Key down
{
"type": "input_keyboard",
"eventType": "keyDown",
@@ -121,10 +131,13 @@ export default function Streaming() {
"key": "c",
"code": "KeyC",
"modifiers": 2
}`} />
}
```
<h3>Touch events</h3>
<CodeBlock code={`// Touch start
### Touch events
```json
// Touch start
{
"type": "input_touch",
"eventType": "touchStart",
@@ -153,11 +166,15 @@ export default function Streaming() {
{ "x": 100, "y": 200, "id": 0 },
{ "x": 200, "y": 200, "id": 1 }
]
}`} />
}
```
<h2>Programmatic API</h2>
<p>For advanced use, control streaming directly via the TypeScript API:</p>
<CodeBlock code={`import { BrowserManager } from 'agent-browser';
## Programmatic API
For advanced use, control streaming directly via the TypeScript API:
```typescript
import { BrowserManager } from 'agent-browser';
const browser = new BrowserManager();
await browser.launch({ headless: true });
@@ -201,17 +218,13 @@ await browser.injectTouchEvent({
console.log('Active:', browser.isScreencasting());
// Stop screencast
await browser.stopScreencast();`} />
await browser.stopScreencast();
```
<h2>Use cases</h2>
<ul>
<li><strong>Pair browsing</strong> - Human watches and assists AI agent in real-time</li>
<li><strong>Remote preview</strong> - View browser output in a separate UI</li>
<li><strong>Recording</strong> - Capture frames for video generation</li>
<li><strong>Mobile testing</strong> - Inject touch events for mobile emulation</li>
<li><strong>Accessibility testing</strong> - Manual interaction during automated tests</li>
</ul>
</div>
</div>
);
}
## Use cases
- **Pair browsing** - Human watches and assists AI agent in real-time
- **Remote preview** - View browser output in a separate UI
- **Recording** - Capture frames for video generation
- **Mobile testing** - Inject touch events for mobile emulation
- **Accessibility testing** - Manual interaction during automated tests
+437
View File
@@ -0,0 +1,437 @@
"use client";
import { useRef, useEffect, useState } from "react";
import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport } from "ai";
import { Streamdown } from "streamdown";
import Link from "next/link";
const STORAGE_KEY = "docs-chat-messages";
const transport = new DefaultChatTransport({ api: "/api/docs-chat" });
const TOOL_LABELS: Record<
string,
{ label: string; pastLabel: string; argKey?: string }
> = {
readFile: { label: "Reading", pastLabel: "Read", argKey: "path" },
bash: { label: "Running", pastLabel: "Ran", argKey: "command" },
};
function isToolPart(part: { type: string }): part is {
type: string;
toolCallId: string;
toolName?: string;
state: string;
input?: Record<string, unknown>;
output?: unknown;
errorText?: string;
} {
return part.type.startsWith("tool-") || part.type === "dynamic-tool";
}
function getToolName(part: { type: string; toolName?: string }): string {
if (part.type === "dynamic-tool") return part.toolName ?? "tool";
return part.type.replace(/^tool-/, "");
}
function ToolCallDisplay({
part,
}: {
part: {
type: string;
toolCallId: string;
toolName?: string;
state: string;
input?: Record<string, unknown>;
output?: unknown;
errorText?: string;
};
}) {
const toolName = getToolName(part);
const config = TOOL_LABELS[toolName] ?? {
label: toolName,
pastLabel: toolName,
};
const isDone = part.state === "output-available";
const isError = part.state === "output-error";
const isRunning = !isDone && !isError;
const displayLabel = isRunning ? config.label : config.pastLabel;
const args = (part.input ?? {}) as Record<string, unknown>;
const argValue = config.argKey ? args[config.argKey] : undefined;
const argPreview =
argValue != null
? String(argValue)
.replace(/^\/workspace\//, "/")
.replace(/\.md$/, "")
.replace(/\/index$/, "") || "/"
: "";
// Link to the docs page if it's a readFile path
const docsLink =
toolName === "readFile" && argPreview.startsWith("/") ? argPreview : null;
const argEl = argPreview ? (
docsLink ? (
<Link href={docsLink} className="truncate underline underline-offset-2">
{argPreview}
</Link>
) : (
<span className="truncate">{argPreview}</span>
)
) : null;
return (
<div className="text-xs py-0.5 min-w-0">
{isRunning ? (
<span className="inline-flex items-center gap-1 font-mono text-muted-foreground animate-tool-shimmer min-w-0">
<span className="shrink-0">{displayLabel}</span>
{argEl}
</span>
) : (
<span className="inline-flex items-center gap-1 font-mono text-muted-foreground/60 min-w-0">
<span className="shrink-0">{displayLabel}</span>
{argEl}
{isError && <span className="text-destructive">failed</span>}
</span>
)}
</div>
);
}
const SUGGESTIONS = [
"What is agent-browser?",
"How do I install it?",
"What commands are available?",
"How do snapshots work?",
"How do I use CDP mode?",
];
export function DocsChat() {
const [open, setOpen] = useState(false);
const [input, setInput] = useState("");
const [focused, setFocused] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const restoredRef = useRef(false);
const { messages, sendMessage, status, setMessages, error } = useChat({
transport,
});
const isLoading = status === "streaming" || status === "submitted";
// Restore messages from sessionStorage on mount
useEffect(() => {
if (restoredRef.current) return;
restoredRef.current = true;
try {
const stored = sessionStorage.getItem(STORAGE_KEY);
if (stored) {
const parsed = JSON.parse(stored);
if (Array.isArray(parsed) && parsed.length > 0) {
setMessages(parsed);
}
}
} catch {
// ignore parse errors
}
}, [setMessages]);
// Save completed messages to sessionStorage
useEffect(() => {
if (!restoredRef.current) return;
if (isLoading) return;
if (messages.length === 0) {
sessionStorage.removeItem(STORAGE_KEY);
return;
}
try {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(messages));
} catch {
// ignore quota errors
}
}, [messages, isLoading]);
// Auto-open when new messages arrive (but not on initial restore)
const prevMessageCount = useRef<number | null>(null);
const initializedRef = useRef(false);
useEffect(() => {
// Skip until after the first sessionStorage restore cycle
if (!initializedRef.current) {
// Wait one tick after mount to let restore settle
const id = requestAnimationFrame(() => {
prevMessageCount.current = messages.length;
initializedRef.current = true;
});
return () => cancelAnimationFrame(id);
}
if (
prevMessageCount.current !== null &&
messages.length > prevMessageCount.current
) {
setOpen(true);
}
prevMessageCount.current = messages.length;
}, [messages.length]);
// Scroll to bottom when messages change or error occurs
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages, error]);
// Cmd+K to focus prompt, Esc to close
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "k" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
inputRef.current?.focus();
}
if (e.key === "Escape" && open) {
setOpen(false);
inputRef.current?.blur();
}
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [open]);
// Close message area when clicking outside
useEffect(() => {
if (!open) return;
const handleClickOutside = (e: MouseEvent) => {
if (
containerRef.current &&
!containerRef.current.contains(e.target as Node)
) {
setOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, [open]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!input.trim() || isLoading) return;
sendMessage({ text: input });
setInput("");
};
const handleClear = () => {
setMessages([]);
sessionStorage.removeItem(STORAGE_KEY);
setOpen(false);
inputRef.current?.focus();
};
const hasVisibleContent = (
parts: (typeof messages)[number]["parts"],
): boolean => {
return parts.some(
(p) => (p.type === "text" && p.text.length > 0) || isToolPart(p),
);
};
// Auto-open when error occurs
useEffect(() => {
if (error) setOpen(true);
}, [error]);
const showMessages = open && (messages.length > 0 || !!error);
const showSuggestions = focused && messages.length === 0 && !isLoading;
return (
<div className="fixed bottom-0 left-0 right-0 z-50 pointer-events-none">
<div
ref={containerRef}
className={`mx-auto px-4 pb-4 *:pointer-events-auto transition-all duration-300 ${focused || showMessages ? "max-w-xl" : "max-w-56"}`}
>
<div
className={`border rounded-lg overflow-hidden ${focused || showMessages ? "border-background" : "border-[var(--chat-bg)]"}`}
style={{ backgroundColor: "var(--chat-bg)" }}
>
{/* Suggestions panel */}
{showSuggestions && (
<div>
<div className="flex items-center px-4 py-2 border-b border-background shrink-0">
<span className="text-xs font-medium text-muted-foreground">
agent-browser Docs
</span>
</div>
<div className="flex flex-wrap gap-2 p-3">
{SUGGESTIONS.map((s) => (
<button
key={s}
type="button"
onMouseDown={(e) => {
e.preventDefault();
setOpen(true);
sendMessage({ text: s });
}}
className="text-xs px-3 py-1.5 rounded-full border border-background bg-background font-medium text-muted-foreground hover:text-foreground transition-colors"
>
{s}
</button>
))}
</div>
</div>
)}
{/* Messages panel */}
{showMessages && (
<div className="max-h-[60vh] flex flex-col">
<div className="flex items-center justify-between px-4 py-2 border-b border-background shrink-0">
<span className="text-xs font-medium text-muted-foreground">
agent-browser Docs
</span>
<button
onClick={handleClear}
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
aria-label="Clear conversation"
>
Clear
</button>
</div>
<div
className="p-4 space-y-4 overflow-y-auto"
onClick={(e) => {
if ((e.target as HTMLElement).closest("a")) {
setOpen(false);
}
}}
>
{messages.map((message) => {
if (!hasVisibleContent(message.parts)) return null;
return (
<div key={message.id}>
{message.role === "user" ? (
<div className="text-sm text-muted-foreground whitespace-pre-wrap leading-relaxed">
{message.parts
.filter(
(p): p is Extract<typeof p, { type: "text" }> =>
p.type === "text",
)
.map((p) => p.text)
.join("")}
</div>
) : (
<div className="space-y-2">
{message.parts.map((part, i) => {
if (part.type === "text" && part.text) {
return (
<div
key={i}
className="docs-chat-content text-sm text-foreground/90 leading-relaxed prose prose-sm dark:prose-invert max-w-none"
>
<Streamdown>{part.text}</Streamdown>
</div>
);
}
if (isToolPart(part)) {
return (
<ToolCallDisplay
key={part.toolCallId}
part={part}
/>
);
}
return null;
})}
</div>
)}
</div>
);
})}
{error && (
<div className="text-sm text-destructive/80 bg-destructive/10 rounded-md px-3 py-2">
{(() => {
try {
const parsed = JSON.parse(error.message);
return parsed.message || parsed.error || error.message;
} catch {
return (
error.message ||
"Something went wrong. Please try again."
);
}
})()}
</div>
)}
<div ref={messagesEndRef} />
</div>
</div>
)}
{/* Input bar */}
<form
onSubmit={handleSubmit}
onClick={() => inputRef.current?.focus()}
className={`relative flex items-end gap-2 px-3 py-2 cursor-text${showMessages ? " border-t border-background" : ""}`}
>
{!input && (
<div className="absolute inset-0 flex items-center px-3 pointer-events-none">
<span className="text-sm text-muted-foreground truncate flex-1">
Ask a question...
</span>
{!focused && !showMessages && (
<span className="text-muted-foreground/40 font-mono text-xs shrink-0">
&#8984;K
</span>
)}
</div>
)}
<textarea
ref={inputRef}
value={input}
onChange={(e) => {
setInput(e.target.value);
e.target.style.height = "auto";
e.target.style.height = `${e.target.scrollHeight}px`;
}}
rows={1}
onFocus={() => {
setFocused(true);
if (messages.length > 0) setOpen(true);
}}
onBlur={() => {
setFocused(false);
}}
onKeyDown={(e) => {
if (e.key === "Escape") {
setOpen(false);
inputRef.current?.blur();
}
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSubmit(e);
}
}}
className="flex-1 bg-transparent text-base sm:text-sm text-foreground outline-none disabled:opacity-50 resize-none max-h-32 leading-relaxed relative z-10"
/>
<button
type="submit"
disabled={isLoading || !input.trim()}
className={`bg-primary text-primary-foreground rounded-md p-1 hover:bg-primary/90 transition-colors disabled:opacity-30${!focused && !showMessages ? " hidden" : ""}`}
aria-label="Send message"
>
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<line x1="12" y1="19" x2="12" y2="5" />
<polyline points="5 12 12 5 19 12" />
</svg>
</button>
</form>
</div>
</div>
</div>
);
}
+16 -6
View File
@@ -2,12 +2,13 @@
import Link from "next/link";
import { useMobileNav } from "./mobile-nav-context";
import { ThemeToggle } from "./theme-toggle";
export function Header() {
const { isOpen, toggle } = useMobileNav();
return (
<header className="sticky top-0 z-50 bg-black/90 backdrop-blur-sm">
<header className="sticky top-0 z-50 bg-background/90 backdrop-blur-sm">
<div className="flex h-14 items-center justify-between px-4 gap-6">
<div className="flex items-center gap-2">
<Link href="https://vercel.com" title="Made with love by Vercel">
@@ -27,7 +28,7 @@ export function Header() {
></path>
</svg>
</Link>
<span className="text-[#333]">
<span className="text-border">
<svg
data-testid="geist-icon"
height="16"
@@ -55,21 +56,30 @@ export function Header() {
href="https://github.com/vercel-labs/agent-browser"
target="_blank"
rel="noopener noreferrer"
className="hidden sm:block text-sm text-[#666] hover:text-[#999] transition-colors"
className="hidden sm:flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
GitHub
<svg
viewBox="0 0 16 16"
className="h-4 w-4"
fill="currentColor"
aria-hidden="true"
>
<path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z" />
</svg>
<span>13.4k</span>
</a>
<a
href="https://www.npmjs.com/package/agent-browser"
target="_blank"
rel="noopener noreferrer"
className="hidden sm:block text-sm text-[#666] hover:text-[#999] transition-colors"
className="hidden sm:block text-sm text-muted-foreground hover:text-foreground transition-colors"
>
npm
</a>
<ThemeToggle />
<button
onClick={toggle}
className="lg:hidden p-2 -mr-2 text-[#888] hover:text-white transition-colors"
className="lg:hidden p-2 -mr-2 text-muted-foreground hover:text-foreground transition-colors"
aria-label="Toggle menu"
>
{isOpen ? (
+4 -4
View File
@@ -27,7 +27,7 @@ export function Sidebar() {
{/* Mobile overlay */}
{isOpen && (
<div
className="lg:hidden fixed inset-0 z-40 bg-black/80"
className="lg:hidden fixed inset-0 z-40 bg-background/80"
onClick={() => setIsOpen(false)}
/>
)}
@@ -37,7 +37,7 @@ export function Sidebar() {
className={`
fixed lg:sticky top-14 left-0 z-50 lg:z-auto
w-56 lg:w-48 h-[calc(100vh-3.5rem)]
bg-black
bg-background
transform transition-transform duration-150 ease-out
${isOpen ? "translate-x-0" : "-translate-x-full lg:translate-x-0"}
`}
@@ -53,8 +53,8 @@ export function Sidebar() {
href={item.href}
className={`block px-2 py-1.5 text-sm transition-colors ${
isActive
? "text-white"
: "text-[#666] hover:text-[#999]"
? "text-foreground"
: "text-muted-foreground hover:text-foreground"
}`}
>
{item.name}
+16
View File
@@ -0,0 +1,16 @@
"use client";
import { ThemeProvider as NextThemesProvider } from "next-themes";
export function ThemeProvider({ children }: { children: React.ReactNode }) {
return (
<NextThemesProvider
attribute="class"
defaultTheme="dark"
enableSystem
disableTransitionOnChange
>
{children}
</NextThemesProvider>
);
}
+61
View File
@@ -0,0 +1,61 @@
"use client";
import { useTheme } from "next-themes";
import { useEffect, useState } from "react";
export function ThemeToggle() {
const { theme, setTheme } = useTheme();
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
return <div className="w-8 h-8" />;
}
return (
<button
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
className="w-8 h-8 flex items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
aria-label="Toggle theme"
>
{theme === "dark" ? (
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2" />
<path d="M12 20v2" />
<path d="m4.93 4.93 1.41 1.41" />
<path d="m17.66 17.66 1.41 1.41" />
<path d="M2 12h2" />
<path d="M20 12h2" />
<path d="m6.34 17.66-1.41 1.41" />
<path d="m19.07 4.93-1.41 1.41" />
</svg>
) : (
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" />
</svg>
)}
</button>
);
}
+18
View File
@@ -0,0 +1,18 @@
export type NavItem = {
name: string;
href: string;
};
export const allDocsPages: NavItem[] = [
{ name: "Introduction", href: "/" },
{ name: "Installation", href: "/installation" },
{ name: "Quick Start", href: "/quick-start" },
{ name: "Commands", href: "/commands" },
{ name: "Selectors", href: "/selectors" },
{ name: "Sessions", href: "/sessions" },
{ name: "Snapshots", href: "/snapshots" },
{ name: "Streaming", href: "/streaming" },
{ name: "CDP Mode", href: "/cdp-mode" },
{ name: "iOS Simulator", href: "/ios" },
{ name: "Changelog", href: "/changelog" },
];
+54
View File
@@ -0,0 +1,54 @@
/**
* Converts raw MDX content to clean Markdown suitable for AI agents.
*
* Transformations:
* - Remove `export` statements (metadata, etc.)
* - Remove `import` statements
* - Strip standalone JSX divs with className attributes
* - Pass everything else through as-is (already valid Markdown)
*/
export function mdxToCleanMarkdown(raw: string): string {
const lines = raw.split("\n");
const out: string[] = [];
let inJsxBlock = false;
let jsxDepth = 0;
for (const line of lines) {
const trimmed = line.trim();
// Skip export and import statements
if (trimmed.startsWith("export ") || trimmed.startsWith("import ")) {
continue;
}
// Track JSX blocks (like callout divs) and skip them
if (
!inJsxBlock &&
trimmed.startsWith("<div ") &&
trimmed.includes("className=")
) {
inJsxBlock = true;
jsxDepth = 1;
continue;
}
if (inJsxBlock) {
// Count opening/closing div tags to handle nesting
const opens = (line.match(/<div[\s>]/g) || []).length;
const closes = (line.match(/<\/div>/g) || []).length;
jsxDepth += opens - closes;
if (jsxDepth <= 0) {
inJsxBlock = false;
jsxDepth = 0;
}
continue;
}
out.push(line);
}
// Clean up leading blank lines
let result = out.join("\n");
result = result.replace(/^\n+/, "\n").trim();
return result;
}
+57
View File
@@ -0,0 +1,57 @@
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
// Lazy initialization to avoid errors when Redis env vars are not configured
let _minuteRateLimit: Ratelimit | null = null;
let _dailyRateLimit: Ratelimit | null = null;
function getRedis(): Redis | null {
const url = process.env.KV_REST_API_URL;
const token = process.env.KV_REST_API_TOKEN;
if (!url || !token) {
return null;
}
return new Redis({ url, token });
}
// No-op rate limiter for when Redis is not configured
const noopRateLimiter = {
limit: async () => ({ success: true, limit: 0, remaining: 0, reset: 0 }),
};
const MINUTE_LIMIT = Number(process.env.RATE_LIMIT_PER_MINUTE) || 10;
const DAILY_LIMIT = Number(process.env.RATE_LIMIT_PER_DAY) || 100;
// Requests per minute (sliding window)
export const minuteRateLimit = {
limit: async (identifier: string) => {
if (!_minuteRateLimit) {
const redis = getRedis();
if (!redis) return noopRateLimiter.limit();
_minuteRateLimit = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(MINUTE_LIMIT, "1 m"),
prefix: "ratelimit:minute",
});
}
return _minuteRateLimit.limit(identifier);
},
};
// Requests per day (fixed window)
export const dailyRateLimit = {
limit: async (identifier: string) => {
if (!_dailyRateLimit) {
const redis = getRedis();
if (!redis) return noopRateLimiter.limit();
_dailyRateLimit = new Ratelimit({
redis,
limiter: Ratelimit.fixedWindow(DAILY_LIMIT, "1 d"),
prefix: "ratelimit:daily",
});
}
return _dailyRateLimit.limit(identifier);
},
};