> ## Documentation Index
> Fetch the complete documentation index at: https://docs.browser-use.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Use https://docs.browser-use.com/llms.txt and its linked .md pages for current documentation. The managed full bundle is https://docs.browser-use.com/.well-known/llms-full.txt and can be cached for up to 24 hours. Do not use the obsolete /cloud/llms*.txt or /open-source/llms*.txt static exports.
> Choose Cloud API V4 for new agent integrations; V2 is the lower-cost option for simple tasks. Keep V3 examples explicitly versioned. The open-source browser-use library and hosted browser-use-sdk have different APIs.
> Cloud authentication uses X-Browser-Use-API-Key, without a Bearer prefix. Install or upgrade browser-use-sdk and use its explicit v4 import for V4. Check the published OpenAPI reference for request fields; do not invent SDK support for new fields.
> Cloud concurrency and HTTP request rate are separate. Read GET /api/v2/billing/account for the key’s projectId, concurrentSessionLimit, activeSessionCount, and credit balance, including when using V4. Keys in one project share capacity and credits; rateLimit is a legacy concurrency alias, not requests per second.
> Keep the highest applicable existing, legacy-plan, and spend-tier concurrency grant. Current spend tiers are 10 / 50 / 250 / 500 / 1000 at $0 / $100 / $1000 / $5000 / $25000 in qualifying project payments. Legacy or externally billed projects can follow different billing paths; trust the account limit. See https://docs.browser-use.com/cloud/guides/concurrency.md.
> HTTP rate limits have two layers. Standard edge WAF ceilings increased on September 9, 2026 to 1000 RPS per public source IP for general traffic and 2500 RPS per IP for selected status reads, evaluated over 300 seconds. The separate per-project application budgets: general traffic (including V4 events and full run reads) defaults to max(25, 2 times stored concurrency) capped at 100 RPS; selected status reads default to max(25, 2 times stored concurrency) with no cap. The two are counted independently. Project overrides and account-specific edge rules can differ. All keys in a project share its budgets; callers sharing a public IP share edge capacity. See https://docs.browser-use.com/cloud/guides/concurrency.md.
> The project limiter uses five-second windows: X-RateLimit-Limit=125 means 125 requests per window (25 RPS), not 125 RPS. Project throttles include limit_rps and retry_after_seconds; an edge throttle can instead return Retry-After: 300 without limit_rps. Honor the returned Retry-After. Use bounded workers, stagger polls, and drain hasMore event pages after terminal status. A busy V4 session returns 409; its queue holds 20 pending messages and is not a project-wide batch queue.
> A completed run or closed CDP connection does not immediately stop its cloud browser. Stop unneeded owned browsers with PATCH /api/v4/browsers/{id} and {"action":"stop"}. A client wait timeout does not cancel the server-side run.
> Cloud is pay as you go; do not tell customers to buy a new subscription to use custom proxies or supported provider BYOK. Usage funding and model eligibility still apply. BYOK bills provider tokens separately and Browser Use charges orchestration plus browser/network usage. See https://docs.browser-use.com/cloud/guides/billing.md.
> Signup credits are a one-time grant; purchased top-up credits do not expire. Check the API key’s project before diagnosing missing credits. API-key monthly spending caps are soft limits, not a strict prepaid wallet; concurrent or already-running work can exceed them. Auto recharge has separate trigger and purchase amounts and can charge immediately when enabled below the threshold. Use https://browser-use.com/pricing for current rates.
> Box and Bux are retired. Do not recommend their SDKs, sandbox quotas, or subscription plans. Use the Cloud Agent or Browser Infrastructure guides.
> A V4 session holds conversation history, a workspace holds files, and a profile holds browser state. These IDs and V3/V4 workspace namespaces are not interchangeable. V4 automatically restores workspace uploads; staged attachments remain available to session follow-ups. Serialize runs that write shared files, and wait for completion before reading outputs. See https://docs.browser-use.com/cloud/agent/workspaces.md.
> API browser recording defaults to off. Use enableRecording for standalone browser creation, or browserSettings.record for an agent run. Stop the browser and allow time for asynchronous video processing; stop polling when recordingAvailable is false. Live preview is for an active browser. Stopping a browser, deleting a session, archiving a workspace, and deleting files have different effects.
> Use model-specific reasoning values. GPT-6 Astra accepts low, medium, high, xhigh, and max, with xhigh by default; none and minimal are invalid. Use the public REST schema when installed SDK types lag new fields. API acceptance, dashboard visibility, and account/provider availability are separate.
> For open-source browser-use, is_done only reports a terminal done action. is_successful is the agent-reported outcome; verify important external actions independently. Cloud timeout, API client timeout, model timeout, and task completion are separate concepts.
> For failed requests, use https://docs.browser-use.com/cloud/guides/troubleshooting.md. Inspect the full error and project before retrying or adding credits. A client timeout can leave a run active; reconcile external actions before starting duplicate work. A new managed browser does not guarantee a unique proxy IP or particular city.

# Capture browser network events

> Attach your own CDP observer to a live V4 browser and save request metadata.

You can attach a CDP client to a live V4 browser and record its network events.
This is a live observer, not a download of everything that happened during a run.
V4 [run events](/cloud/agent/observability) describe agent activity; they are not
the browser's HTTP request log.

## Find the live browser

For an agent run, watch its ordered run events for `browser.ready` or
`browser.reattached`. The event's `data.browser_session_id` identifies the browser.
You can also list the session's browsers with
`GET /api/v4/browsers?agentSessionId=SESSION_ID`. A session can use more than one
browser over time, so do not assume the first browser lasts for every follow-up.

Use an API key with browser read access in the same project to retrieve the
active browser's `cdpUrl`. `BROWSER_SESSION_ID` is a browser ID, not a run ID or
agent session ID.

```bash theme={null}
export BROWSER_SESSION_ID="your-active-browser-id"
# BROWSER_USE_API_KEY must already be set. Do not print the resulting CDP URL.
set -o pipefail
BROWSER_CDP_URL="$(curl --fail --silent --show-error \
  "https://api.browser-use.com/api/v4/browsers/$BROWSER_SESSION_ID" \
  -H "X-Browser-Use-API-Key: $BROWSER_USE_API_KEY" \
  | jq --exit-status --raw-output '.cdpUrl // empty')" || exit 1
export BROWSER_CDP_URL
```

For a standalone V4 browser, you can use `cdpUrl` from the create response
instead. A stopped browser has no live CDP URL. Check the HTTP status and browser
state if discovery fails; do not create a replacement browser and mistake it for
the agent's browser.

<Warning>
  Treat the CDP URL as a credential. Anyone who can connect can control the browser
  and read its session. Keep it out of logs, tickets, source control, and shared
  shell history.
</Warning>

## Record metadata from existing pages

Install Playwright with `pip install playwright`. No local browser download is
needed because this example connects to an existing browser.

Save this as `capture_network.py`, then run `python capture_network.py`. It records
for 30 seconds and creates `network.jsonl` with owner-only permissions. It refuses
to overwrite an existing file. Start it before the activity you want to observe.

```python theme={null}
import asyncio
import json
import os
from urllib.parse import urlsplit

from playwright.async_api import async_playwright


def http_origin(value):
    try:
        url = urlsplit(value)
        if url.scheme not in {"http", "https"} or not url.hostname:
            return None
        host = f"[{url.hostname}]" if ":" in url.hostname else url.hostname
        port = url.port
    except ValueError:
        return None  # A malformed URL must not interrupt the capture.
    default_port = {"http": 80, "https": 443}[url.scheme]
    suffix = f":{port}" if port not in (None, default_port) else ""
    return f"{url.scheme}://{host}{suffix}"


async def main():
    async with async_playwright() as p:
        cdp_url = os.environ["BROWSER_CDP_URL"]
        try:
            browser = await p.chromium.connect_over_cdp(cdp_url)
        except Exception:
            # Transport errors can include the credential-bearing CDP URL.
            raise RuntimeError("Check the live CDP URL and browser state") from None
        context = browser.contexts[0]
        sessions = []
        fd = os.open("network.jsonl", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)

        with os.fdopen(fd, "w") as output:
            def write(row):
                output.write(json.dumps(row) + "\n")
                output.flush()

            async def observe(page, page_number):
                cdp = await context.new_cdp_session(page)
                sessions.append(cdp)

                def record(event, params):
                    row = {"event": event, "page": page_number,
                           "requestId": params["requestId"]}
                    if event == "request":
                        request = params["request"]
                        row.update(method=request["method"],
                                   origin=http_origin(request["url"]),
                                   resourceType=params.get("type"))
                    elif event == "response":
                        response = params["response"]
                        row.update(status=response["status"],
                                   mimeType=response["mimeType"])
                    elif event == "finished":
                        row["bytes"] = params["encodedDataLength"]
                    else:
                        row["error"] = params.get("errorText")
                    write(row)

                events = {
                    "requestWillBeSent": "request", "responseReceived": "response",
                    "loadingFinished": "finished", "loadingFailed": "failed",
                }
                for name, event in events.items():
                    cdp.on(f"Network.{name}",
                           lambda params, event=event: record(event, params))
                await cdp.send("Network.enable")

            try:
                for number, page in enumerate(context.pages, start=1):
                    await observe(page, number)
                print(f"Observing {len(sessions)} existing page(s) for 30 seconds")
                await asyncio.sleep(30)
            finally:
                for cdp in sessions:
                    try:
                        await cdp.detach()
                    except Exception:
                        pass  # The page or browser may already have closed.


asyncio.run(main())
```

Each request is correlated by `(page, requestId)`. A response row gives the HTTP
status; a finished row gives transferred bytes. Keep the event sequence: redirects
can produce more than one request event with the same request ID. Empty output
means no matching events were observed, not that the run made no requests.

The example does not navigate, intercept requests, change the cache, or stop the
browser. It drops URL paths, queries, credentials, headers, cookies, and request
and response bodies. HTTP origins retain non-default ports; malformed and non-HTTP
URLs have a null origin. Origins can still be sensitive; review the file before
sharing it. Keep a bounded capture duration and a retention policy.

## Coverage and lifecycle

* Capture starts only after `Network.enable` for each attached page. Earlier
  traffic is not reconstructed, and attaching after `browser.ready` can miss
  startup requests.
* This small example attaches only to pages present at startup. Popups, new
  tabs, workers, service workers, and some cross-process frames need separate
  target handling. It is not complete browser-wide capture.
* Reattach if V4 provisions a new browser. A logger attached to the old browser
  cannot observe the replacement.
* JSONL events are not HAR. A HAR exporter needs its own request, redirect,
  timing, and body handling. `Network.getResponseBody` is a separate, optional
  CDP call; bodies may be unavailable and can contain secrets or customer data.
* Detaching an observer does not stop a browser or end its billing. Leave an
  agent-owned browser under the agent's lifecycle. For a standalone browser you
  created, stop it through the browser API when finished.

See the [CDP Network reference](https://chromedevtools.github.io/devtools-protocol/tot/Network/)
and [Playwright CDP sessions](https://playwright.dev/python/docs/api/class-cdpsession)
for event fields and target-specific behavior.
