Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ This plugin includes the following skills (see `skills/` for details):
| Skill | Description |
|-------|-------------|
| [browser](skills/browser/SKILL.md) | Automate web browser interactions via CLI commands — supports remote Browserbase sessions with Browserbase Identity, Verified browsers, CAPTCHA solving, and residential proxies |
| [browserbase-agents](skills/browserbase-agents/SKILL.md) | Create, run, and integrate Browserbase Agents via the Agents API — reusable agents with system prompts and result schemas, runs with variables, polling, downloads, and prompt/schema best practices |
| [functions](skills/functions/SKILL.md) | Deploy serverless browser automation to Browserbase cloud using the `browse` CLI |
| [browser-trace](skills/browser-trace/SKILL.md) | Capture a full DevTools-protocol trace (CDP firehose, screenshots, DOM dumps) alongside any browser automation, then bisect the stream into per-page searchable buckets |
| [browser-to-api](skills/browser-to-api/SKILL.md) | Turn a website's observable HTTP traffic into a best-effort OpenAPI 3.1 spec by analyzing a `browser-trace` capture |
Expand Down
21 changes: 21 additions & 0 deletions skills/browserbase-agents/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Browserbase, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
89 changes: 89 additions & 0 deletions skills/browserbase-agents/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
---
name: browserbase-agents
description: Create, run, and integrate Browserbase Agents — autonomous cloud browser agents driven by one API call. Covers the Agents API (create reusable agents with system prompts and result schemas, trigger runs with variables, poll to completion, retrieve structured results and downloads) plus field-tested best practices for prompts, schemas, and anti-bot settings. Use when the user wants to create a Browserbase agent, call the Agents API, run an autonomous browser agent, or automate a web task ("search X and return JSON", "check availability on Y") without writing Playwright or Stagehand code.
license: MIT
compatibility: "Requires Python 3.8+ (stdlib only) and BROWSERBASE_API_KEY."
allowed-tools: Bash, Read, Write
---

# Browserbase Agents

Browserbase Agents are the highest abstraction of the Browserbase platform: describe a web task in natural language, and Browserbase runs an autonomous agent (browser + web search + files + shell, Stagehand-driven) that completes it and returns structured JSON. No Playwright scripts, no model orchestration, no infrastructure.

**Mental model:** an *Agent* is a reusable configuration (`name` + `systemPrompt` + `resultSchema`); a *run* is one asynchronous execution of a `task` against it, on a dedicated browser session. Create the agent once, then fan runs out across queries, dates, or hundreds of portals by changing only `variables`.

## Prerequisites

- A Browserbase API key (dashboard → Settings), exported as `BROWSERBASE_API_KEY`.
- No SDK required — the API is plain REST; the bundled script is stdlib-only Python.

## Core workflow

### 1. Design the agent

Write the `systemPrompt` in four blocks — role/scope, inputs (every `%variable%` documented), numbered procedure, guardrails — and pair it with a strict `resultSchema`. **Read `references/prompt_patterns.md` before writing either**; it contains the patterns that separate reliable agents from flaky ones (echo-back `appliedFilters`, outcome enums, null-over-invented-data, read-only guardrails, SSR-blob extraction, variable-drift mitigations).

A ready-to-adapt example payload lives at `assets/example_agent.json`.

### 2. Create the agent

```bash
python3 scripts/bb_agents.py create --file my_agent.json
# → returns agentId
```

Equivalent raw call: `POST https://api.browserbase.com/v1/agents` with header `x-bb-api-key` and body `{name, systemPrompt, resultSchema}`. Only `name` is required.

### 3. Trigger a run

```bash
python3 scripts/bb_agents.py run --agent-id <agentId> \
--task "Search for %query% and return structured JSON." \
--var query="wireless earbuds" --var max_pages=1 \
--proxies --wait
```

- `--var key=value` becomes the `variables` object; reference values as `%key%` in prompts. Use variables for anything per-run or sensitive (queries, dates, credentials) — values are not persisted.
- `--proxies` / `--verified` set `browserSettings` for anti-bot-protected sites.
- `--context-id` reuses a Browserbase context (cookies/auth) across runs.
- Omitting `--agent-id` creates a new agent and its first run in one call.
- `--wait` polls to completion inline; otherwise poll separately.

### 4. Poll to completion

Runs are asynchronous: `PENDING → RUNNING → COMPLETED | FAILED | TIMED_OUT | STOPPED`.

```bash
python3 scripts/bb_agents.py poll <runId> # blocks until terminal, prints run
python3 scripts/bb_agents.py messages <runId> # step-by-step transcript while running
```

The structured output is at `result.output` in the run object and conforms to the `resultSchema`. The run's `sessionId` is a normal Browserbase session — use it for Live View, Session Replay, and logs in the dashboard, and for retrieving downloaded files:

```bash
python3 scripts/bb_agents.py downloads <sessionId>
```

### 5. Verify and iterate

- Compare echoed fields (`appliedFilters`, `date`) against the variables sent — this catches the two most common first-run failures: filters not applied and date drift.
- Thin results on protected sites (PerimeterX, DataDome, Akamai)? Re-run with `--proxies --verified`.
- Use the dashboard **Optimize** tool on any run to get a proposed `systemPrompt` diff, then `scripts/bb_agents.py update <agentId> --file changes.json`.
- Track `completionRate` / `failRate` / `timeoutRate` / `averageDuration` on the Agent page — optimize against numbers, not impressions.

## Bundled resources

| Resource | Use |
|---|---|
| `scripts/bb_agents.py` | Zero-dependency CLI for the full lifecycle: create, update, run (with variables/browserSettings), get, poll, messages, list-agents, list-runs, downloads, delete. Run with `--help` for all flags. |
| `references/api_reference.md` | Condensed endpoint reference: payloads, response shapes, run lifecycle, pagination, downloads, built-in tools, quality metrics. Load when constructing raw API calls. |
| `references/prompt_patterns.md` | System-prompt and schema design patterns with field-tested pitfalls (variable drift, silent filter failures, anti-bot settings). Load before designing any agent. |
| `assets/example_agent.json` | Complete working agent payload (e-commerce search with full filter surface) to copy and adapt. |

## Key facts worth remembering

- Agents choose their own path (may skip the browser entirely if search/fetch suffices); custom tools can't be added yet — extra capability goes in the `systemPrompt`.
- Integration is poll-based today (webhooks planned). Poll every ~5–10 s; typical runs take 2–10 minutes.
- Each run is a separate browser session, so parallel fan-out works up to the account concurrency limit.
- Per-run `resultSchema` overrides the agent's default; per-run `variables` keep secrets out of task text.
- Files: agents can download and produce files (retrieve via Downloads API with the `sessionId`), but files cannot be uploaded to an agent yet; >1 MB data should flow through downloads, not inline extraction.
61 changes: 61 additions & 0 deletions skills/browserbase-agents/assets/example_agent.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"name": "Amazon Product Search (Full Filter Surface)",
"systemPrompt": "You are an Amazon product search agent. Search www.amazon.com for products matching the query and apply the full filter surface, then return structured JSON for every organic result on the scanned pages.\n\nInputs (variables):\n- %query% — the search query (required)\n- %department% — Amazon department/category to scope the search to (optional; skip if empty or 'any')\n- %brands% — comma-separated brand names to filter by (optional)\n- %min_rating% — minimum star rating, e.g. 4 for '4 Stars & Up' (optional)\n- %price_min% / %price_max% — price bounds in USD (optional)\n- %deals_only% — 'true' to filter to Today's Deals (optional)\n- %condition% — 'new', 'used', or 'renewed' (optional)\n- %sort% — one of: featured, price-asc, price-desc, avg-review, newest, best-sellers (optional; default featured)\n- %max_pages% — number of result pages to scan (default 1, max 3)\n\nProcedure:\n1. Go to https://www.amazon.com and search for %query%. If a CAPTCHA or 'continue shopping' interstitial appears, resolve it and retry.\n2. Apply filters using the left-rail refinements AND/OR URL parameters (rh=, p_36 for price, p_72 for rating, s= for sort) — prefer URL params when reliable: department, brands, min rating, price range, deals, condition.\n3. Apply the requested sort order via the sort dropdown or s= URL param.\n4. Scan up to %max_pages% pages of results using pagination.\n5. For EVERY organic (non-sponsored) result, extract: ASIN (from data-asin attribute or the /dp/ URL), full title, price (display string plus numeric value and currency; null if unavailable), star rating and review count, badges (e.g. \"Best Seller\", \"Amazon's Choice\", \"Overall Pick\", \"Prime\", coupon/deal badges), main image URL, and the canonical product URL in the form https://www.amazon.com/dp/<ASIN>.\n6. Skip sponsored placements, ad carousels, and editorial widgets. Deduplicate by ASIN.\n7. Record which filters you actually managed to apply in appliedFilters. If a filter option does not exist for this query, note it as null and continue rather than failing.\n\nReturn the result conforming to the result schema. Never invent ASINs, prices, or ratings — use null when a field is not present on the page.",
"resultSchema": {
"type": "object",
"additionalProperties": false,
"required": ["query", "appliedFilters", "results"],
"properties": {
"query": { "type": "string" },
"appliedFilters": {
"type": "object",
"additionalProperties": false,
"properties": {
"department": { "type": ["string", "null"] },
"brands": { "type": "array", "items": { "type": "string" } },
"minRating": { "type": ["number", "null"] },
"priceMin": { "type": ["number", "null"] },
"priceMax": { "type": ["number", "null"] },
"dealsOnly": { "type": "boolean" },
"condition": { "type": ["string", "null"] },
"sort": { "type": ["string", "null"] },
"pagesScanned": { "type": "integer" }
}
},
"totalResultsText": { "type": ["string", "null"] },
"results": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["asin", "title", "url"],
"properties": {
"asin": { "type": "string" },
"title": { "type": "string" },
"price": {
"type": "object",
"additionalProperties": false,
"properties": {
"display": { "type": ["string", "null"] },
"value": { "type": ["number", "null"] },
"currency": { "type": ["string", "null"] },
"listPrice": { "type": ["number", "null"] }
}
},
"rating": {
"type": "object",
"additionalProperties": false,
"properties": {
"stars": { "type": ["number", "null"] },
"reviewCount": { "type": ["integer", "null"] }
}
},
"badges": { "type": "array", "items": { "type": "string" } },
"imageUrl": { "type": ["string", "null"] },
"url": { "type": "string" }
}
}
}
}
}
}
18 changes: 18 additions & 0 deletions skills/browserbase-agents/evals/evals.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[
{
"prompt": "Create a Browserbase agent that searches Hacker News for stories matching a query and returns title, points, and URL as structured JSON, then run it once for 'browser automation' and show me the result.",
"expected_behavior": "Writes an agent payload with a systemPrompt documenting %variables% and a strict resultSchema, creates it via POST /v1/agents (scripts/bb_agents.py create), triggers a run with variables, polls to a terminal state, and reports result.output — without inventing data or fields."
},
{
"prompt": "My Browserbase agent run came back with only 1 result on Walmart. What should I change?",
"expected_behavior": "Diagnoses anti-bot protection (PerimeterX) and recommends re-running with browserSettings proxies/verified, plus checking appliedFilters echo-back and the session replay via sessionId."
},
{
"prompt": "How do I pass a confirmation code to a Browserbase agent run without putting it in the task text?",
"expected_behavior": "Uses the variables object on POST /v1/agents/runs with a %placeholder% reference in the prompt, noting values are not persisted."
},
{
"prompt": "Poll my Browserbase agent run wf-123 until it finishes and get any files it downloaded.",
"expected_behavior": "Polls GET /v1/agents/runs/{runId} until a terminal state, reads sessionId from the run, then lists files via GET /v1/downloads?sessionId=."
}
]
127 changes: 127 additions & 0 deletions skills/browserbase-agents/references/api_reference.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# Browserbase Agents API Reference

Base URL: `https://api.browserbase.com/v1`
Auth header on every request: `x-bb-api-key: $BROWSERBASE_API_KEY`
Full docs: https://docs.browserbase.com/platform/agents/overview

## Endpoints at a glance

| Method & path | Purpose |
|---|---|
| `POST /agents` | Create a reusable agent |
| `GET /agents` | List agents (cursor pagination) |
| `GET /agents/{agentId}` | Get one agent |
| `POST /agents/{agentId}` | Update an agent (partial body; omitted fields unchanged) |
| `DELETE /agents/{agentId}` | Delete an agent (past runs unaffected) |
| `POST /agents/runs` | Start a run (with or without `agentId`) |
| `GET /agents/runs` | List runs; filter by `agentId`, `status`, `startAt`/`endAt` |
| `GET /agents/runs/{runId}` | Get a run's status + result |
| `GET /agents/runs/{runId}/messages` | Step-by-step transcript (AI SDK UIMessage format) |
| `GET /downloads?sessionId={id}` | List files the agent downloaded during the run |

## Create an Agent — `POST /agents`

Only `name` is required. An agent with no `systemPrompt` behaves like an unconfigured run.

```json
{
"name": "Amazon Product Search", // required, 1-255 chars
"systemPrompt": "You are ... use %query% ...", // steers every run
"resultSchema": { "type": "object", "...": "..." } // JSON Schema for run output
}
```

Response (201) is the Agent object:

```json
{
"agentId": "uuid", "name": "...", "systemPrompt": "...",
"resultSchema": {}, "createdAt": "...", "updatedAt": "..."
}
```

## Run an Agent — `POST /agents/runs`

```json
{
"agentId": "uuid", // optional; omit for ad-hoc run
"task": "Search for %query% ...", // required, natural language
"resultSchema": {}, // optional per-run schema override
"variables": { // optional %placeholder% values
"query": { "value": "wireless earbuds", "description": "what to search" }
},
"browserSettings": { // optional session controls
"proxies": true, // route through Browserbase proxies
"verified": true, // enable Browserbase Verified
"context": { "id": "ctx_...", "persist": true } // reuse auth/cookies
}
}
```

Notes:
- A call with **no `agentId`** creates a new agent and its first run in one call — the response includes both `agentId` and `runId`.
- Variable values are strings. They are NOT persisted. Reference them as `%name%` in the task or system prompt.
- Contexts carry cookies/auth between runs; `persist: true` saves state back after the run.

## Run lifecycle

```
PENDING → RUNNING → COMPLETED | FAILED | TIMED_OUT | STOPPED
```

`PENDING`/`RUNNING` are active; the rest are terminal and never change again.
Integration is **poll-based** (webhooks planned): poll `GET /agents/runs/{runId}` every few seconds.

## Get a run — response shape

```json
{
"runId": "...", "agentId": "...", "status": "COMPLETED",
"task": "...", "sessionId": "...",
"result": { "output": { /* conforms to resultSchema */ } },
"createdAt": "...", "startedAt": "...", "endedAt": "..."
}
```

- The structured payload lives at `result.output` when a `resultSchema` was set.
- `sessionId` is a normal Browserbase session ID: use it for Live View, Session Replay in the dashboard, logs, and the Downloads API.

## Run messages — `GET /agents/runs/{runId}/messages`

Chronological transcript in [AI SDK UIMessage format](https://ai-sdk.dev/docs/reference/ai-sdk-core/ui-message): each message has `role` and `parts` (text, tool calls, reasoning, files). Pass the response's `nextSince` back as `?since=` to fetch only newer messages — poll this while a run is active to stream progress.

## Pagination

List endpoints return `nextCursor`; pass it back as `?cursor=` for the next page.
`GET /agents/runs` filters: `agentId`, `status`, `limit`, `startAt`, `endAt`.

## Files / downloads

Agents have a sandboxed file workspace (read/write, process PDFs, produce CSVs). Files the agent downloads are stored against the run's session:

```bash
curl "https://api.browserbase.com/v1/downloads?sessionId=$SESSION_ID" \
--header "x-bb-api-key: $BROWSERBASE_API_KEY"
```

Limits: no file *upload* to an agent yet; large (>1 MB) or paginated tabular data should flow through downloads, not inline extraction.

## Built-in tools (not configurable yet)

1. **Browser control** — Stagehand-driven; adapts to layout changes, no selectors.
2. **Web search** — Search/Fetch APIs to find the right starting URL.
3. **File system** — sandboxed workspace, downloads land in the session.
4. **Shell** — sandboxed runtime commands when scripting beats browsing.

Custom tools cannot be added and built-ins cannot be disabled in the current version. The agent may skip the browser entirely if search/fetch answers the task.

## Quality metrics (dashboard Agent page)

| Field | Meaning |
|---|---|
| `completionRate` | Fraction of runs that completed |
| `failRate` | Fraction of runs that failed |
| `timeoutRate` | Fraction of runs that timed out |
| `averageDuration` | Average run duration (seconds) |

Rising `timeoutRate`/`failRate` → revisit the prompt or use the dashboard Optimize tool.
Loading