## Embed it

`uv add fastbrowse` first, then:

```python
import asyncio

from pydantic import BaseModel

from fastbrowse import run_task
from fastbrowse.models import Limits


class Release(BaseModel):
    package: str
    version: str


async def main() -> None:
    result = await run_task(
        "Find the httpx package and report its name and latest released version.",
        start="https://pypi.org/",
        output_schema=Release,
        limits=Limits(max_dollars=0.10),
    )
    print(result.status, result.data, f"${result.cost.known_dollars:.4f}")
    for evidence in result.evidence:
        print(f'  "{evidence.quote}" from {evidence.url}')


asyncio.run(main())
```

**Choosing the browser.** With no browser argument, `run_task` starts a Browser Use Cloud browser with
`BROWSER_USE_API_KEY`, or the key in `browser_api_key=`. The CLI defaults to your own Chrome through the extension.
`chrome=LocalChrome()` runs local Chrome instead, and
`cloud_extensions=[...]` loads up to three of your account's Browser Use Cloud extensions into a cloud browser. `cdp_url=` or `cdp_port=` drives a browser already running: the run opens and closes its own tab and leaves
the rest, though cookies the task sets can persist. `attach=True`, `target_match=` and `foreground=True` work as
the matching flags do. Passing a cloud key and a CDP address together is an error.

**Recipes and recordings.** `save_recipe=Path("recipe.json")` stores the actions of a completed run. A write failure is logged without changing the task status; check the file before replay.
Pass `recipe=Path("recipe.json")` with the same task to reuse values when Jev selects a matching live action.
A changed page or control falls back to the agent. Reading and completion are always checked live.
Naming the same file for both arguments saves the healed sequence after another completed run.
Recipes can contain personal information from ordinary fields; stored secrets are kept only by name.
`fastbrowse.recipes.validate_recipe()` checks recipe JSON with the same Rust parser as the file loader;
`recipe_schema()` exports its JSON Schema for client validation.
`record=Path("run.mp4")` writes captioned and plain videos, and needs ffmpeg. The action cursor also needs ffprobe; if frame dimensions cannot be read, the cursor is omitted with a warning.

**A cloud browser that outlives a run.** `open_cloud_browser(browser_api_key=...)` starts a Browser Use Cloud
browser no run owns and returns a `CloudBrowser` with its `id`, `cdp_url` and `live_url`. It takes `run_task`'s
cloud options without the `cloud_` prefix (`profile=`, `extensions=`, `timeout_minutes=` and the rest). Runs given
its `cdp_url` with `attach=True` leave it running, and `stop_cloud_browser(browser, browser_api_key=...)` stops
it; until then it bills, up to its timeout. A start that fails or is cancelled stops the browser it created.

```python
from fastbrowse import open_cloud_browser, run_task, stop_cloud_browser


async def main() -> None:
    browser = await open_cloud_browser(browser_api_key=KEY, profile=PROFILE_ID, timeout_minutes=60)
    print("watch at", browser.live_url)
    try:
        await run_task("Open my inbox.", cdp_url=browser.cdp_url, attach=True)
    finally:
        await stop_cloud_browser(browser, browser_api_key=KEY)
```

**Your own script on the page.** `connect_cdp()` hands you the attached page without the agent:

```python
from fastbrowse import connect_cdp


async def main() -> None:
    async with connect_cdp(9222, target_match="my-project") as page:
        print(await page.observe())
```

**Moving from 0.8.** The Python modules that 0.9 removed with the Python core have these replacements:

| 0.8 import | Now |
|---|---|
| `fastbrowse.adapters.browser_use_cloud.BrowserUseCloudBrowser` | `open_cloud_browser` to start one and `stop_cloud_browser` to stop it, without the `http=` and `allow_resizing=` arguments |
| `fastbrowse.models.BrowserConnection` | `fastbrowse.CloudBrowser`, holding `id`, `cdp_url` and `live_url` |
| `fastbrowse.clients.environment.Settings` | `run_task(settings={...})`, keyed by the environment variable names |
| `fastbrowse.adapters.totp` (`TotpError`, `one_time_code`) | `fastbrowse.totp` |

**Access controls:**

- `allowed_origins=["https://app.example.com"]` limits the documents a run may read and control to those exact
  origins. Navigations, redirects, frames and popups elsewhere are refused before they are sent, so a sign-in
  that redirects through another origin needs it listed too. It scopes documents, not the network, and a scoped
  run sends no live frames or screenshots and cannot record. The JavaScript, Go, Java and .NET clients take it as
  `allowedOrigins` or `AllowedOrigins`.
- `check_access=`, which only the Python API offers, is an async callback awaited before the browser starts and
  before every read, navigation and action. If it raises, the run ends with status `error` (`connect_cdp` raises `BrowserError`), naming only the
  exception's type.

**Citations.** `result.citations` holds a `Citation` per numbered link in `result.answer`: `id`, `text`,
`url`, `quote` and `deep_link`. Each claim cites the notes it states. A count, total, cheapest or largest
value is worked out in code from every note read and cites each record it rests on. A `quote` is the page's text, a table row as its cells separated by spaces. A `deep_link` is a [text fragment](https://wicg.github.io/scroll-to-text-fragment/#syntax) URL that
scrolls to the quote; it may not resolve on a page that changes or needs a session. Each page a quote was read from
is kept as a `capture` artifact in `result.artifacts`, holding the masked page text, and the quote's `Evidence`
names it in `capture_artifact`; `start` and `end` index into that text. Its `links` lists each link inside the
quote: the link's `text`, where that text sits as `start` and `end`, and the `href` it leads to. Captures go where downloads go, so pass
`downloads` or `artifact_sink` to keep them past the run. A page fetched over HTTP keeps none.

**Watching a run.**

- `on_event=` gets a `BrowserEvent` with a cloud browser's live-view URL, then a `StepEvent` per step, carrying the
  facts that step added. `Config(step_frames=True)` adds a PNG of each step's page.
- A task requesting a final screenshot receives a safe PNG in `result.final_frame` without enabling step frames.
  JSON clients receive a `screenshot` artifact with a base64 data URI. A missing requested image leaves a
  completed task `unverified`.
- `Config(step_choices=True)` adds `choices` to each step Jev decided: the controls it was offered, each with its
  `id`, `role`, masked `label` and `context` (the card or row that tells twins apart) and `operations`, and the one
  it picked marked `chosen` (a drag marks its destination too). It shows whether the element
  a run should have used was there to pick. Off, a step has no `choices` key.
- `on_frame=` gets JPEG frames of the active tab as they render. The handler runs on your event loop, so it
  must honour cancellation: one that swallows `CancelledError` keeps `asyncio.run` waiting at shutdown.

  A cancelled `run_task` raises `fastbrowse.models.RunCancelled`, an `asyncio.CancelledError` with a `receipt`
  of reported steps, known cost lines and finished recordings once the browser closes. A cancellation before
  the core starts may have no receipt. The receipt has no status or answer; unpriced charges stay `unknown`.
  `ConfigurationError` and `RecordingError` also carry a `receipt` when they stop a run after work or charges
  have accrued; otherwise their `receipt` is `None`. JSON-RPC preserves this receipt in error data, or in the
  error result for recording failures. MCP keeps it in `_meta["fastbrowse.ai/receipt"]` beside the tool error.
  A callback failure raises the original exception with a `receipt` attribute when the core retains one,
  including when the callback fails as the run completes.
- `with traced() as events:` collects the run's trace in-process, as `--trace` writes it.

No frame or screenshot is sent while a resolved secret may show on the page.

`run_task(jev=...)` and `run_task(llm=...)` take your own decision model or LLM client; a `jev` client is asked at
Jev's limits and thresholds. See [Jev routing](https://github.com/agent-labs-dev/fastbrowse/blob/633121ade207c7e3e415bdf4fd26f7a0f2608c58/docs/jev.md#provider-failover) and `fastbrowse.llm`.

**Choosing the model backend without the environment.** New in 0.9.1.
`run_task(settings={...})` takes the same names as the
environment variables (`OPENROUTER_API_KEY`, `AI_GATEWAY_API_KEY`, `TYPESAFE_API_KEY`, `FASTBROWSE_DECISION_SOURCE`,
`FASTBROWSE_LLM_PROVIDER`, `FASTBROWSE_LLM_MODEL` and the rest) and reads them instead of the environment and
`.env`, so a service that keeps its credentials elsewhere hands the run exactly the keys it means to:

```python
result = await run_task("Find the latest httpx release", settings={"OPENROUTER_API_KEY": my_key})
```

**The same rules outside a run.** New in 0.9.1. `fastbrowse.origins` (`origin_of`, `parse_origin`) parses `allowed_origins` as the
run does; `fastbrowse.safety` (`secret_allowed`, `origin_of`, `ScopedSecrets`) answers where a secret may be typed,
`*.` patterns included; `fastbrowse.totp.one_time_code(key)` makes the codes an authenticator key gives. Each wraps
the core's own rule, so the answer before a run is the one the run gives.