# ibr - Intent Browser Runtime An AI-powered instruction parser that converts human-readable instructions into automated web interactions. Powered by Playwright for browser automation and Vercel AI SDK for multi-provider AI support. ## Features - **Multi-Provider AI Support**: OpenAI, Anthropic Claude, Google Gemini - **Natural Language Instructions**: Describe what you want in plain English - **Automatic Element Detection**: AI finds elements based on descriptions - **Data Extraction**: Extract structured data from web pages - **Conditional Logic**: If-then instructions for dynamic flows - **Loop Support**: Repeat actions until conditions are met - **Authenticated Sessions**: Inherit browser cookies via `--cookies` flag - **Snapshot Diffing**: 85% token reduction in loops via incremental DOM diffs - **Tool Runner**: `ibr tool` subcommand — YAML-defined reusable browser workflows with typed params - **DOM Inspector**: `ibr snap` subcommand for on-demand page inspection - **Daemon Mode**: Optional persistent browser server; warm invocations ~540ms vs ~3800ms cold - **Visual Debugging**: `--annotate` / `-a` flag captures annotated PNGs with labeled bounding boxes - **Failure Screenshots**: `ANNOTATED_SCREENSHOTS_ON_FAILURE=true` auto-captures on action failure - **Dialog Handling**: Auto-accepts browser dialogs; buffers history for inspection - **Comprehensive Logging**: Detailed execution logs for debugging - **NDJSON Streaming**: `NDJSON_STREAM=true` emits structured browser events for pipeline integration - **Augmentation Engine**: URL-aware DOM mutations (remove, isolate, addClass) and scripting to pre-process pages - **Self-Healing**: Autonomous bypass of obstructions (paywalls, modals) using `@hop-top/fit` SDK - **Run Recording**: Deterministic record/replay of AI interactions using `@hop-top/xrr` cassettes - **Contextual Learning**: Healing logic learns from previous successful bypasses on similar page structures - **Cloud Orchestration**: Multi-provider account pooling and rotation (browser-use, browserless, etc.) - **Proactive Infra Routing**: URL-aware infrastructure selection (e.g. force Cloud for Jira or high-entropy domains) - **Infra-Switching**: Autonomous migration from local to cloud browser during self-healing - **CDP Tab Reuse**: Connect to running browser via `BROWSER_CDP_URL` + reuse existing authenticated tabs with `BROWSER_REUSE_PAGE=true` - **Camoufox when installed**: fingerprint-spoofing Firefox; else bundled Chromium, silently - **Custom Launch Args**: `BROWSER_ARGS` env var for Chromium flags (`--user-data-dir`, `--profile-directory`) - **Popup Auto-Switch**: After click opens a popup window, ibr preemptively switches context for subsequent instructions; auto-returns on popup close - **Strict Mode Scoping**: When multiple identical elements match (e.g. 9 "delete" links), ibr extracts disambiguating text from the instruction prompt and scopes to the nearest ancestor row ## Setup ### Setup prompt Paste into Claude Code or Codex: ```text Set up https://github.com/hop-top/ibr for me. Follow the README.md to install dependencies and run the browser installation. Configure the environment by copying `.env.example` to `.env` and ask me for my preferred AI provider and its API key. After it is installed, verify the setup by running: ibr "url: https://github.com/hop-top/ibr instructions: - extract the repository description" If the interaction works and I am logged in to GitHub (check via `--cookies chrome`), ask me whether you should star the repository for me as a quick demo. ``` ### 1. Clone and Install ```bash npm install @hop/ibr npm run browser:install ``` `browser:install` fetches Playwright's bundled Chromium, the browser ibr runs on by default. **Optional: Camoufox.** Install it yourself and ibr uses it by default; without it ibr runs on Chromium and prints nothing about it. Needs Node >= 22.15. ```bash npm i -g camoufox camoufox fetch # or: ibr browser pull camoufox ibr browser which # channel: camoufox ``` Cost: 1.3 GB download, 2.7 GB on disk (incl. 213 MB fingerprint model). See [Camoufox](#camoufox--default-when-installed). ### 2. Configure Environment ```bash cp .env.example .env ``` Edit `.env` and configure your AI provider: #### OpenAI (Default) ```env AI_PROVIDER=openai OPENAI_API_KEY=your_api_key_here ``` #### Anthropic Claude ```env AI_PROVIDER=anthropic ANTHROPIC_API_KEY=your_api_key_here ``` #### Google Gemini ```env AI_PROVIDER=google GOOGLE_GENERATIVE_AI_API_KEY=your_api_key_here ``` ### 3. (Optional) Configure Browser & AI Behavior ```env # Browser display options BROWSER_HEADLESS=true # Run headless (true) or show browser window (false) BROWSER_SLOWMO=100 # Slow down actions in milliseconds (helps with debugging) # AI behavior AI_TEMPERATURE=0 # 0 for deterministic, higher for more creative AI_MODEL=gpt-4-mini # Override default model (optional) ``` ## Usage ### Basic Example ```bash ibr "url: https://example.com instructions: - click the 'submit' button - extract page title" ``` ### Authenticated Sessions (`--cookies`) Import real browser cookies so ibr can reach pages that require a logged-in session. Supports macOS, Linux, and Windows Chromium-based browsers. Reads directly from the browser's on-disk SQLite cookie database; no proxy, no extension, no manual export needed. **Requires:** `better-sqlite3` (native addon, already listed in `package.json`). On macOS, the first import also requires Keychain access for the target browser. On Windows, cookie decryption uses the browser's Local State master key via DPAPI. #### Syntax ``` ibr --cookies [:,,...] "" ``` | Part | Description | |------|-------------| | `` | Browser alias (see table below) | | `:,` | Optional domain filter — import only these host keys | #### Supported Browsers | Alias | Browser | Platforms | |-------|---------|-----------| | `chrome` | Google Chrome | macOS, Linux, Windows | | `brave` | Brave | macOS, Linux, Windows | | `edge` | Microsoft Edge | macOS, Linux, Windows | | `arc` | Arc | macOS | | `comet` | Comet (Perplexity) | macOS | | `chromium` | Chromium | Linux, Windows | #### Examples **All cookies from Chrome — access any auth-gated page:** ```bash ibr --cookies chrome "url: https://github.com instructions: - extract repository list" ``` **Comet cookies for a single domain:** ```bash ibr --cookies comet:reddit.com "url: https://www.reddit.com/r/programming instructions: - extract top 5 post titles" ``` **Arc cookies scoped to two domains:** ```bash ibr --cookies arc:github.com,linear.app "url: https://linear.app instructions: - list my open issues" ``` **Brave with no domain filter (all non-expired cookies):** ```bash ibr --cookies brave "url: https://app.example.com instructions: - click 'Dashboard'" ``` **Edge for a specific domain:** ```bash ibr --cookies edge:outlook.com "url: https://outlook.com instructions: - extract unread message subjects" ``` #### Domain Filtering - `--cookies arc:github.com,linear.app` — import only cookies whose `host_key` matches `github.com` or `linear.app`. - `--cookies chrome` (no filter) — import **all non-expired** cookies from Chrome's Default profile. - Expired cookies are always excluded regardless of filter. #### How It Works 1. Resolves the browser's cookie DB path under: - macOS: `~/Library/Application Support//Default/Cookies` - Linux: `${XDG_CONFIG_HOME:-~/.config}//Default/Cookies` - Windows: `%LOCALAPPDATA%//Default/Network/Cookies` (fallback: `.../Cookies`) 2. Retrieves the Safe Storage password: - macOS: `security find-generic-password` from Keychain — **a permission dialog appears on first run; click "Allow"** - Linux: fixed Chromium fallback password `peanuts` - Windows: decrypts Local State `os_crypt.encrypted_key` via DPAPI 3. Derives a 16-byte AES key via PBKDF2 (SHA-1, 1003 iterations, salt `saltysalt`) on macOS/Linux, or loads the Local State master key on Windows. 4. Decrypts cookie values using: - macOS/Linux: `v10` AES-128-CBC - Windows: legacy DPAPI blobs or `v10` AES-256-GCM 5. Injects resulting cookies into the Playwright browser context via `context.addCookies()` before any navigation. #### Limitations - Reads the **Default** profile only; named profiles not yet supported. - Windows app-bound Chromium `v20` cookie encryption is not yet supported. - The derived/master key is cached per-process; macOS subsequent calls for the same browser skip the dialog. #### Error Cases | Error code | Cause | Action | |------------|-------|--------| | `not_installed` | Browser cookie DB not found on disk | Install the browser or check the alias spelling | | `keychain_denied` | User clicked "Deny" in the macOS dialog | Re-run and click "Allow" | | `keychain_timeout` | macOS Keychain dialog not answered within 10 s | Re-run and respond to the dialog promptly | | `keychain_not_found` | No macOS Keychain entry for that browser | Browser may not be a Chromium build; check alias | | `windows_key_not_found` | Windows Local State key could not be read | Check the browser profile and Local State availability | | `windows_key_error` | Windows Local State key format is invalid | Check the browser profile integrity | | `windows_dpapi_error` | DPAPI decryption failed | Re-run under the same Windows user profile | | `windows_dpapi_timeout` | DPAPI helper timed out | Retry the command | | `windows_dpapi_unavailable` | PowerShell / DPAPI helper unavailable | Ensure PowerShell is installed and accessible | | `db_locked` | DB still locked after copy attempt | Close the browser and retry | | `db_corrupt` | SQLite DB is corrupt | Reinstall or reset the browser profile | If the **DB is locked** (browser is open), ibr automatically copies the DB and its WAL/SHM files to `/tmp` and reads from the copy — the original is never written to. The temp files are deleted when the import finishes. ### `--mode` Flag Control which page-representation mode the AI receives: | Flag | Mode | When to use | |------|------|-------------| | _(none)_ | `auto` | Default — quality-based selection; escalates aria → dom → visual (last resort) if text fails | | `--mode aria` | ARIA tree | Force ariaSnapshot (semantic, compact) | | `--mode dom` | DOM + XPath | Force DomSimplifier (raw structure) | | `--mode visual` | Screenshot + Set-of-Marks | Vision-based element detection; numbered overlays sent to the model | The visual path acts on a mark — an element or a grid cell picked out of the screenshot — so it performs `click`, `fill`, `type` and `press` only. Any other action type, notably `scroll`, is **refused rather than substituted**: a page-level scroll needs no element, so a `scroll` reaching this path has already claimed a missing element target, and scrolling to the model's guess would silently perform a different action than the one requested. Under explicit `--mode visual` the refusal is **always** an `UNSUPPORTED_VISUAL_ACTION` error on stderr with a non-zero exit — element mark and grid cell alike, and before any screenshot or vision call is spent. It is never a silent exit-0 skip, so the run aborts at that instruction and the later steps do not run; the message names the action type, the instruction index and the remedy. Run that instruction under `--mode auto`/`aria`/`dom` instead, where a page-level scroll needs no element and is performed directly. Under `--mode auto` such a step is skipped before the screenshot is taken, spending neither an escalation nor a vision call, and never raises the error. ### `--interactive` / `-i` Flag Run `ibr` in interactive mode. This forces `BROWSER_HEADLESS=false` (showing the browser window) and is recommended when using `wait for human` instructions for solving CAPTCHAs, MFA, or manual logins. ```bash # Run in interactive mode ibr --interactive "url: https://example.com\ninstructions:\n - wait for human: solve captcha" # Force ARIA mode ibr --mode aria "url: https://example.com\ninstructions:\n - click submit" # Force DOM mode — canvas apps, legacy table-soup, unlabelled SPAs ibr --mode dom "url: https://canvas-app.example.com\ninstructions:\n - click submit" ``` **Auto-selection logic** (default): after capturing the ARIA snapshot, ibr scores its quality and picks the best mode automatically: - `sparsityRatio > 0.4` → dom (too many unlabelled interactive elements) - snapshot > 50 000 chars → dom (too large) - snapshot empty or errored → dom - otherwise → aria **Sparsity** = ratio of unnamed interactive elements to all interactive elements. An unnamed interactive element looks like `- button ""` or `- link ""` in the ARIA tree — no accessible name, so the AI cannot reliably target it. When more than 40% of buttons/links have no name, the snapshot is too sparse to be useful. Logs report the chosen mode and reason, e.g.: ``` using aria mode falling back to dom mode: sparse (0.62) falling back to dom mode: size falling back to dom mode: empty ``` **Site-type guidance:** | Mode | Works best on | |------|---------------| | `aria` | Modern semantic SPAs, accessible sites, form-heavy UIs | | `dom` | Canvas-heavy apps, legacy table-soup HTML, Shadow DOM, `aria-hidden`-heavy pages | | `visual` | Canvas apps, custom widgets, unlabelled elements, overlays blocking text find/act | | `auto` | Unknown sites; safe default — quality-checked per page; escalates to visual as last resort when text fails | **Auto-escalation ladder** (`--mode auto`): when the aria + dom text-based attempt fails, ibr escalates to `--mode visual` (screenshot + Set-of-Marks). Two failure points trigger it: the model reports it could not find the element (`"outcome": "not_found"`), or the element is found but the action throws (click/type/etc.). An instruction that legitimately needs no element — a page-level scroll, an optional action the model marks `"no_element_needed"` — is skipped as before and never spends an escalation. The visual attempt is capped at `VISUAL_MAX_ESCALATIONS` (default 3 per run; explicit `--mode visual` ignores the cap). Each escalation is logged via progress feedback. On an action failure a visual-informed healing step follows if visual also fails. When the model itself reports `not_found` (no element at all), a visual attempt that resolves nothing leaves the instruction skipped. A descriptor the model *did* return but that matches nothing on the page (for example a control relabelled since the plan was made) is handled by [element relocation](#element-relocation). This allows recovery from obstructions (modals, paywalls) the text representation cannot describe. If the visual attempt itself errors — the vision call fails, or acting on the resolved mark throws — the error is **absorbed** so the instruction still falls through to healing, and the run frequently still succeeds. It is not silent: each absorbed error is emitted as a `visual.escalation_failed` NDJSON event and recorded on the run in `visualEscalationFailures` (empty on a clean run), so an automated consumer can tell a genuinely clean run from one that healed past a real fault. See [docs/cheatsheet-agent.md](docs/cheatsheet-agent.md#absorbed-escalation-failures-visualescalation_failed). **Cost note:** Visual mode uses vision tokens (typically ~1000–2000 per screenshot vs. 10–100 for text). Auto-escalation and explicit `--mode visual` are the two engagement points; prefer text modes when possible to minimize token usage. ### Visual Mode & `--annotate` Coexistence `--mode visual` and `--annotate` are complementary, not mutually exclusive — both run from the same overlay engine: ```bash ibr --mode visual --annotate "url: https://example.com instructions: - click the submit button" ``` | Flag | Sink | Purpose | |------|------|---------| | `--mode visual` | Model | Screenshot with numbered overlays sent to the LLM for resolution | | `--annotate` | Disk (`/tmp/…png`) | Same marked frame written to `/tmp/ibr-annotate-step--.png` for human inspection | | Both | Both sinks | The marked screenshot drives the model AND is preserved as a debug artifact | ### Visual Debugging (`--annotate`) Capture annotated screenshots that show exactly which elements the AI resolved — useful when a flow behaves unexpectedly and you want visual confirmation. #### `--annotate` / `-a` flag ```bash ibr --annotate "url: https://example.com\ninstructions:\n - click submit" ibr -a "url: https://example.com\ninstructions:\n - click submit" ``` After each element-resolution step that finds ≥1 element, ibr captures a full-page PNG with red bounding-box overlays labeled `@e1`, `@e2`, etc. (DOM elements) or `@c1`, `@c2`, etc. (pseudo-buttons / cursor-interactive elements). Output path: `/tmp/ibr-annotate-step--.png` #### `ANNOTATED_SCREENSHOTS_ON_FAILURE` ```bash ANNOTATED_SCREENSHOTS_ON_FAILURE=true ibr "url: https://example.com\n..." ``` When set to `true`, ibr automatically captures an annotated screenshot whenever an action fails — without requiring `--annotate` on every run. Output path: `/tmp/ibr-failure-step--.png` The screenshot is non-fatal: if capture fails (e.g. due to a Content Security Policy), execution continues and a warning is logged. #### Notes - Overlays are injected via `page.evaluate` (no image library dependency). - Off-screen / hidden elements are silently skipped (no overlay). - Overlay `
`s are always removed after screenshot (even on error). - Path validation: only `/tmp` and the current working directory are accepted. --- ### Prompt Format Instructions use a YAML-like format: ```yaml url: https://example.com/page instructions: - click 'button text' if found # Conditional action - fill 'email' with user@test.com # Fill form field - type 'search term' into search box # Type into focused element - press Enter # Press keyboard key - extract text: title, price, url # Extract data - repeatedly: # Loop until condition fails - click 'next page' if found ``` ### Instruction Types #### 1. Click/Fill/Type Actions ```yaml - click 'element description' - fill 'field description' with value - type 'text' into element - press KeyName (Enter, Space, Escape, etc.) ``` #### 2. Conditional (if found) ```yaml - click 'close banner' if found # Executes if element exists ``` #### 3. Loops (repeatedly) ```yaml - repeatedly: - click 'load more' if found # Continues until condition fails - extract items ``` A loop stops when its condition fails, after 100 iterations, or as soon as an iteration makes no progress: it ran no action or wait, the page URL did not change, and it extracted exactly the same data as the iteration before. #### 4. Data Extraction ```yaml - extract: title, price, rating # Extract text content - extract all product names # Extract list of items ``` #### 5. Human Intervention & Waits ```yaml - wait for human: solve the captcha # Pauses for terminal input (HITM) - wait 10 seconds # Wait for a specific duration ``` ### Real-World Example ```bash ibr "url: https://www.example.com/products instructions: - close 'cookie banner' if found - scroll to bottom of page - repeatedly: - click 'load more' if found - wait for new items to load - extract all products: name, price, rating - navigate to first product - extract product details: description, reviews" ``` ## Daemon Mode (opt-in, fast warm invocations) By default every `ibr` call spawns a new Chromium instance (~3800 ms cold-start). Daemon mode keeps a browser process alive in the background so subsequent calls connect to it instead (~540 ms warm). ### Enable ```bash # Per-session env var export IBR_DAEMON=true ibr "url: https://example.com\ninstructions:\n - extract title" # Per-invocation flag ibr --daemon "url: https://example.com\ninstructions:\n - extract title" # Start the server manually (optional — auto-started on first call) npm run server ``` ### How It Works 1. CLI checks `IBR_DAEMON=true` or `--daemon` flag. 2. Reads `~/.ibr/server.json` (pid, port, bearer token). 3. Validates process is alive + `/health` responds OK. 4. If stale/missing: spawns `src/server.js` detached and polls until ready (≤8 s). 5. `POST /command` with Bearer token; server reuses the warm browser context. 6. Server auto-shuts down after 30 min idle. ### Security - Localhost-only (`127.0.0.1`); not accessible remotely. - Random OS-assigned port per startup. - Bearer token is a UUID, stored in `~/.ibr/server.json` (mode `0600`). ### State File `~/.ibr/server.json` — written atomically; override path with `IBR_STATE_FILE`. ```json { "pid": 12345, "port": 51234, "token": "", "startedAt": 1234567890 } ``` ### Latency Breakdown | Mode | Time | |------|------| | Cold (stateless, default) | ~3800 ms | | Warm (daemon) | ~540 ms | ### Disable / Stop ```bash unset IBR_DAEMON # revert to stateless for this session kill $(jq .pid ~/.ibr/server.json) # stop the daemon manually ``` --- ## Tool Runner (`ibr tool`) Run pre-packaged browser workflows defined as YAML files in `tools/`. Params use `{{placeholder}}` syntax; defaults applied when omitted. ``` ibr tool [--param key=value ...] ibr tool --list ``` ### Built-in Tools | Name | Description | Required Params | |------|-------------|----------------| | `web-search` | Search the web; extract ranked results | `query` | | `web-fetch` | Fetch a URL; extract main content | `url` | | `trend-search` | Google Trends interest + related queries | `topic` | | `github-search` | GitHub repo/code/issue/user search | `query` | | `github-trending` | GitHub trending repos by language/period | _(all optional)_ | | `github-starred` | Browse a user's starred repos | `username` | ### Examples ```bash # Web search ibr tool web-search --param query="openai agents" # Google Trends (defaults: region=US, period=7d) ibr tool trend-search --param topic=javascript --param region=GB # GitHub repo search ibr tool github-search --param query=playwright --param type=repositories # GitHub trending (all params optional) ibr tool github-trending --param language=go --param period=weekly # User's starred repos with keyword filter ibr tool github-starred --param username=sindresorhus --param query=rust # List available tools ibr tool --list ``` ### YAML Tool Format Place `.yaml` files in `tools/` and they become available as `ibr tool `: ```yaml name: my-tool description: "Short description" params: - name: query description: "Search query" required: true - name: count description: "Number of results" default: "5" url: "https://www.google.com" instructions: - type {{query}} into the search box and press Enter - extract the top {{count}} results with titles and URLs ``` `{{param}}` placeholders are interpolated in both `url` and `instructions`. An instruction step whose placeholders all resolve to an empty or unset value is dropped, so a step that only uses an optional param (e.g. `select {{category}}`) runs only when that param has a value — no "if {{x}} is not empty" wording needed. Missing required params, or a `--param` key the tool does not declare → exit 1 with a `CONFIG_ERROR` before the browser starts; the unknown-key message lists the tool's valid params. ### VCR Test Record Mode E2E tests for tools use cassette replay by default. To record real cassettes from live sites (run once, then commit): ```bash VCR_RECORD=true OPENAI_API_KEY=sk-... \ node node_modules/vitest/vitest.mjs run test/e2e/cli-tool-vcr.test.js ``` The proxy forwards requests to the real AI endpoint, captures responses, and writes updated cassette files to `test/e2e/cassettes/`. --- ## DOM Inspector (`ibr snap`) Inspect the live DOM of any page without writing a full task. Outputs simplified DOM JSON to stdout; useful for debugging selectors, auditing interactive elements, or feeding context to other tools. ``` ibr snap [flags] ``` ### Flags | Flag | Description | |------|-------------| | `--aria` | Show ariaSnapshot (ARIA YAML tree) instead of DOM JSON | | `-i` | Interactive only: dom → xpath-indexed nodes; aria → role+name lines | | `-a` | Annotated screenshot → `/tmp/ibr-dom-annotated.png` (dom mode only) | | `-d ` | Depth limit — truncate tree at depth N (dom mode only) | | `-s ` | Scope output to a CSS selector subtree (dom mode only) | Two representations are available: - **DOM tree** (default): XPath-indexed JSON — what the AI sees in dom mode - **ARIA snapshot** (`--aria`): Playwright `ariaSnapshot()` YAML — what the AI sees in aria mode Use `--aria` to verify what the AI reasons over when running with `--mode aria`. ### Examples ```bash # Full DOM of a page (dom mode representation) ibr snap https://example.com # ARIA snapshot (aria mode representation) ibr snap --aria https://example.com # ARIA snapshot — interactive elements only (role + name present) ibr snap --aria -i https://example.com # DOM: interactive elements only (reduces noise) ibr snap https://example.com -i # DOM: annotated screenshot highlighting all interactive elements ibr snap https://example.com -a # DOM: limit tree depth to 4 levels ibr snap https://example.com -d 4 # DOM: scope to the navigation bar only ibr snap https://example.com -s "nav" # DOM: interactive elements in sidebar, depth 3, with screenshot ibr snap https://example.com -i -s "#sidebar" -d 3 -a ``` DOM mode outputs JSON on stdout with header `=== DOM Tree ===`. ARIA mode outputs YAML on stdout with header `=== ARIA Snapshot ===`. With `-a` (dom), the screenshot path is printed to stderr: ```bash # Capture DOM JSON and screenshot in one shot ibr snap https://example.com -i -a > dom.json # → stderr: Annotated screenshot: /tmp/ibr-dom-annotated.png ``` --- ## Camoufox — default when installed [Camoufox](https://github.com/daijro/camoufox): patched Firefox with fingerprint spoofing, driven through Playwright's Firefox protocol. Optional, installed by you, never by ibr; not an ibr dependency. **Default rule** (no `BROWSER_CHANNEL`, `BROWSER_EXECUTABLE_PATH`, CDP or cloud config): - Camoufox installed → Camoufox - not installed → Playwright's bundled Chromium; no warning, no extra output "Installed" = Node >= 22.15, `camoufox` package resolvable, a fetched browser build, and its fingerprint model. Anything missing → Chromium. **Install** ```bash npm i -g camoufox camoufox fetch # or: ibr browser pull camoufox ``` - `camoufox fetch` calls the GitHub API anonymously; a shared IP can hit the rate limit (`403`). Set `GITHUB_TOKEN` and retry. - `ibr browser pull camoufox` runs the package's own `camoufox fetch` (its output goes to stderr). From the standalone `dist/ibr` binary it only prints the two commands above. - ibr looks for the package beside itself, then in the global npm `node_modules` dirs (Node binary prefix, npm prefix env, platform defaults). Installed elsewhere: set `CAMOUFOX_MODULE_PATH` to the `camoufox` package dir. **Channels** | `BROWSER_CHANNEL` | Browser | Install | |-------------------|---------|---------| | `camoufox` | Camoufox (Firefox, fingerprint spoofing) | you: `npm i -g camoufox && camoufox fetch` | | `playwright-chromium` | Playwright's bundled Chromium | `npm run browser:install` | | `chromium` | system Chromium | your OS package manager | | `chrome` / `msedge` / `brave` / `arc` / `comet` | system browser | the vendor installer | | `lightpanda` | Lightpanda | ibr auto-download | **Select explicitly** ```bash BROWSER_CHANNEL=camoufox ibr "..." # Camoufox or BROWSER_NOT_FOUND BROWSER_CHANNEL=playwright-chromium ibr "..." # bundled Chromium, even if Camoufox is installed ibr browser which # what the default resolves to + install state ``` - Explicit `camoufox` and not installed → `BROWSER_NOT_FOUND` with the install hint; no fallback. - Installed but fails to launch → error; no silent retry on Chromium. - `browser.resolved` (stderr) reports what ran: `"channel":"camoufox"` on the Camoufox default path, `"channel":null` when the default fell back to Chromium. **Measured costs** (macOS arm64, build 158.0.1-beta.41) | What | Cost | |------|------| | Download | 1.3 GB browser + 53 MB GeoIP | | Disk | 2.7 GB (`~/Library/Caches/camoufox` on macOS), incl. 213 MB fingerprint model | | First launch per process | 8-14 s (host GPU probe launch first); ~2 s with `CAMOUFOX_CANVAS_NOISE=true` | | Later launches, same process | ~0.6 s | Daemon mode waits up to 30 s for a Camoufox daemon to start (8 s for Chromium). **Behaviour notes** - Fingerprint OS = host OS (`darwin` → macos, `win32` → windows, `linux` → linux); other fingerprint settings are Camoufox defaults - Window size is random per launch (from the fingerprint); `viewport` is null, screenshots differ in size between runs - `BROWSER_ARGS` is ignored (Chromium flags) - `page.evaluate()` runs in an isolated world: page globals are invisible. Augmentation rules with `scripting.evaluateBeforeSnapshot` still run against the DOM; ibr writes one `augmentation.script_isolated` JSON line to stderr per rule per process - `--cookies` reads Chromium-family cookie stores only; importing into a Camoufox session works, a Firefox cookie store is not a source - Camoufox cache is shared with every other camoufox user on the machine - One fingerprint identity per daemon (one browser launch serves all contexts) - Standalone `dist/ibr` (SEA) cannot load the package: always Chromium **License note**: the camoufox package is MIT, but its dependency tree pulls in `ua-parser-js` 2.x (AGPL-3.0-or-later). One reason it stays a user install rather than an ibr dependency. See [docs/testing-camoufox.md](docs/testing-camoufox.md) for the gated e2e suite. --- ## Lightpanda — fast headless mode [Lightpanda](https://github.com/lightpanda-io/browser) is a Zig-built headless browser with roughly 9× faster startup and 16× less memory than Chromium. ibr can auto-download it and drive it via Playwright CDP — no manual install. **One-liner** (auto-downloads stable release on first run, caches under `~/.cache/ibr/browsers/lightpanda/`): ```bash BROWSER_CHANNEL=lightpanda ibr "go to example.com and extract the heading" ``` **With fallback** (recommended during lightpanda beta — ibr silently retries on Playwright's bundled Chromium when a scenario hits an unimplemented Web API and records the failure in a capability manifest for future pre-flight warnings). `BROWSER_FALLBACK` takes a channel name: `playwright-chromium` is the bundled build; `chromium` means a system Chromium install. ```bash BROWSER_CHANNEL=lightpanda BROWSER_FALLBACK=playwright-chromium ibr "..." ``` **Pre-warm the cache in CI** (avoids first-run download latency): ```bash ibr browser pull lightpanda stable ``` **Inspect current resolver decision**: ```bash ibr browser which ``` **Lifecycle modes** - **Connect-only** — set `BROWSER_CDP_URL=ws://127.0.0.1:9222` to connect to an already-running CDP server (you manage the lifecycle). - **Daemon-owned** — long-running `IBR_DAEMON=true`; the server spawns + reuses the browser across requests. - **One-shot** — default CLI mode; spawn + connect + teardown per invocation. See `docs/testing-lightpanda.md` for the gated e2e suite and known compat gaps. ### Reusing an Authenticated Browser Session (CDP) Connect to a running browser to interact with authenticated pages (Gmail, Google Workspace, etc.) without re-authenticating: ```bash # 1. Launch browser with remote debugging "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser" \ --user-data-dir="$HOME/.ops/brave-profile" \ --profile-directory="Noor" \ --remote-debugging-port=9333 & # 2. Sign in manually in the browser window # 3. Snap the current page (no navigation, no re-auth) BROWSER_CDP_URL="ws://localhost:9333/devtools/browser/" \ BROWSER_REUSE_PAGE=true \ ibr snap current --aria # 4. Interact with the authenticated page BROWSER_CDP_URL="ws://localhost:9333/devtools/browser/" \ BROWSER_REUSE_PAGE=true \ ibr "url: current instructions: - click Settings gear icon - extract account email address" ``` Get the CDP websocket URL: `curl -s http://localhost:9333/json/version` `current` only works with `BROWSER_REUSE_PAGE=true` against a connected browser that has a tab open at `BROWSER_TAB_INDEX` (default `0`). Without `BROWSER_CDP_URL`, ibr launches a fresh browser with no page to reuse, so `ibr snap current` and `url: current` fail early with a `CONFIG_ERROR` that names `BROWSER_CDP_URL`, rather than navigating to the literal string. ### Custom Launch Args Pass extra Chromium flags to launch with a specific profile (Chromium-family channels only; ignored for Camoufox): ```bash BROWSER_CHANNEL=brave \ BROWSER_ARGS="--user-data-dir=$HOME/.ops/brave-profile --profile-directory=Noor" \ ibr snap "https://example.com" --aria ``` ### `ibr browser` subcommands ``` ibr browser list Show registry + cache state (Camoufox: installed version) ibr browser pull [channel] [version] Pre-warm browser cache (camoufox: runs camoufox fetch) ibr browser prune [--older-than] GC old cache entries ibr browser which Print resolver decision + Camoufox install state ``` --- ## Snapshot Diffing (Automatic) **Internal optimization — no user action required.** In loops and multi-step tasks, ibr tracks snapshots between actions. Instead of sending the full page representation to the AI on every step, it sends only what changed. - **~85% token reduction** in typical loop workflows - **dom mode**: compares added, removed, modified nodes by XPath identity - **aria mode**: line-based set diff of ariaSnapshot YAML lines; keyed by role+name - Falls back to full snapshot automatically when: - Navigation occurs (page URL changes) - >50% of nodes/lines change (large-change threshold) - Snapshot is older than 5 minutes (stale threshold) - Mode mismatch between stored and current snapshot No configuration needed. Token savings are logged at DEBUG level per `#findElements` call (`usedDiff`, `diffSummary`). --- ## Augmentations & Self-Healing `ibr` can automatically pre-process web pages to remove noise (paywalls, cookie banners) and autonomously heal itself when an action is blocked. ### Augmentation Engine Site-specific rules are defined in `~/.ibr/augmentations.json`. When `ibr` navigates to a URL matching a rule's `urlPattern`, it applies DOM mutations and scripts before the AI sees the page. #### Example `augmentations.json` ```json { "version": 1, "rules": [ { "id": "clean-news-site", "urlPattern": "^https://(www\\.)?news-site\\.com/.*", "domMutations": { "remove": [".paywall-modal", ".newsletter-popup"], "isolate": ["article.main-content"] }, "scripting": { "evaluateBeforeSnapshot": "document.querySelectorAll('time').forEach(t => t.innerText = new Date().toISOString());" } } ] } ``` - **remove**: Array of CSS selectors to delete from the DOM. - **isolate**: Array of CSS selectors to keep; everything else is removed. - **evaluateBeforeSnapshot**: JavaScript string executed in the browser context to normalize data or clean the UI. #### Bypass with `--raw` Use the `--raw` or `--ignore-augmentations` flag to bypass all site-specific rules: ```bash ibr --raw "url: https://example.com\ninstructions:\n - extract title" ``` ### Self-Healing (`fit` SDK) When an operation fails (e.g., a button is obscured by a modal), `ibr` enters **Heal Mode**. 1. **Hypothesize**: It asks the AI to identify the blocking element. 2. **Test**: It removes the element and re-verifies if the target is now clickable. 3. **Learn**: Successful fixes are saved to `~/.ibr/learnings.json` indexed by the page's **structural signature**. 4. **Intuition**: If Site B looks structurally similar to Site A, `ibr` uses Site A's successful learnings to guide its first healing hypothesis for Site B. #### Element relocation A planned target can match nothing because the page changed: arxiv, for example, relabelled its search select from "Field to search" to "Field", so a replayed `combobox "Field to search"` no longer exists. `ibr` checks the match count before scrolling or acting (allowing about a second for an element still being rendered) and treats zero matches as a find miss, then recovers on the same page, cheapest first: 1. **Re-ask**: one more call to the action model for this instruction, with a fresh page snapshot and a note naming the descriptor that matched nothing. The answer is used only if it matches exactly one element (or is scoped to one by the instruction's context); an ambiguous answer is refused rather than guessed. 2. **Visual** (`--mode auto` only): the usual Set-of-Marks escalation, within `VISUAL_MAX_ESCALATIONS`. 3. **Healing relocate**: Heal Mode may propose `{ "action": "relocate", "descriptor": { "role": ..., "name": ... } }`. It is scored on the new locator (exactly one match, visible, enabled) and the action is retried there once. This hypothesis is offered only when the original target matches nothing; overlay removal behaves as before. Relocations are not saved as augmentation rules or learnings. If every rung fails the run stops with `ELEMENT_NOT_FOUND`, naming both the original and the re-asked descriptor. Each instruction gets at most one re-ask and one heal, with no loop. When the action on the new target succeeds, an `element.relocated` NDJSON event records `step`, `from`, `to` and `via` (`reask`, `visual` or `healing`); it is never emitted for a relocation whose action then failed. Healing's checks on a target are bounded to 2 s each, so a doomed heal no longer waits the 30 s Playwright default. Relocation works on the current page only: if the target moved to another page, `ibr` does not navigate there. ### Run Recording (`xrr` SDK) Every AI interaction is recorded into YAML cassettes. This enables **Deterministic Replay** for debugging and CI testing. - **Record**: Set `XRR_MODE=record` to capture live interactions. - **Replay**: Set `XRR_MODE=replay` to run `ibr` without calling the live AI, using only cached cassettes. Default cassette location: `~/.ibr/cassettes/` (override with `XRR_CASSETTE_DIR`). ### Cloud Orchestration & Routing `ibr` can orchestrate multiple cloud browser providers (Browser-use, Browserless, etc.) to bypass bot detection, IP limits, or captchas. #### Configuration (`~/.ibr/infra.json`) Manage your cloud accounts and routing policies in `~/.ibr/infra.json` (override with `IBR_INFRA_CONFIG`): ```json { "providers": { "browser-use": { "accounts": [ { "name": "personal", "key": "sk-123" }, { "name": "work", "key": "sk-456" } ] }, "browserless": { "accounts": [ { "name": "default", "key": "bl-789" } ] } }, "routing": { "default": "local", "policies": [ { "urlPattern": "jira\\.mycompany\\.com", "providers": ["browser-use"], "stage": "proactive" } ] } } ``` - **Account Pooling**: `ibr` automatically rotates keys (Round-Robin) for every new session to stay within tier limits. - **Proactive Routing**: If a URL matches a policy with `stage: "proactive"`, `ibr` starts on that cloud provider immediately. - **Infra-Switching**: If local execution fails due to a block, the **Heal Mode** can autonomously suggest a switch to a cloud provider. `ibr` will migrate your session state (cookies) to the new instance and resume. --- ## Remote Execution with `pod` Use [`pod`](https://github.com/hop-top/pod) to provision remote compute and run `ibr` jobs on any cloud or local container. ### Run a remote job ```bash # 1. Provision a node pod create scraper-01 --provider hetzner --cpu 2 --ram 4 # 2. Run the job pod exec scraper-01 -- ibr "url: https://example.com instructions: - extract title" ``` ### Hybrid Workflow Attach a local `ibr` instance to a remote pod's reasoning model: ```bash pod launch ibr --pod scraper-01 -- "url: https://example.com instructions: - extract title" ``` --- ## Showcase Personas & E2E Examples Practical, live-site examples demonstrating `ibr` and `pod` integration for real-world user archetypes. All examples are verified with [VCR cassettes](test/e2e/cassettes/) for deterministic replay. ### [Homeowner](docs/personas/homeowner.md) *Focus: Personal automation, archival, and utility management.* - **[063: Local News Archival](docs/stories/063-local-news-archival.md)** ([Test](test/e2e/showcase/homeowner.test.js)) — Archive community blogs to the Wayback Machine. - **[064: Feed-based Insights](docs/stories/064-feed-insight-extraction.md)** ([Test](test/e2e/showcase/homeowner.test.js)) — Extract summaries from Miniflux news feeds. - **[065: Historical Research](docs/stories/065-historical-property-research.md)** ([Test](test/e2e/showcase/homeowner.test.js)) — Research property/community history via Wayback timeline. ### [Business Manager](docs/personas/business-manager.md) *Focus: Market intelligence, lead gen, and research feeds.* - **[066: Pricing Audit](docs/stories/066-competitor-pricing-audit.md)** ([Test](test/e2e/showcase/business-manager.test.js)) — Compare live pricing with historical snapshots. - **[067: Contributor Sourcing](docs/stories/067-oss-contributor-enrichment.md)** ([Test](test/e2e/showcase/business-manager.test.js)) — Extract talent data from GitHub repository graphs. - **[068: AI Research Feed](docs/stories/068-arxiv-research-feed.md)** ([Test](test/e2e/showcase/business-manager.test.js)) — Automate daily briefings using the `arxiv` tool. ### [Personal Shopper](docs/personas/personal-shopper.md) *Focus: Global arbitrage, inventory sniping, and vetting.* - **[069: Global Price Compare](docs/stories/069-global-price-comparison.md)** ([Narrative](docs/stories/069-global-price-comparison.md)) — Cross-region search using the `ebay` tool. - **[070: Historical Value](docs/stories/070-historical-value-research.md)** ([Test](test/e2e/showcase/personal-shopper.test.js)) — Verify "original" prices using historical data. - **[071: Review Verification](docs/stories/071-amazon-review-summary.md)** ([Narrative](docs/stories/071-amazon-review-summary.md)) — Deep-vet product quality using the `amazon` tool. ### [Infrastructure Routing](test/e2e/infra-fallback.test.js) *Focus: Proactive and reactive cloud browser orchestration.* - **Cloud Fallback** — Switch to `browserless` or `browser-use` when blocked. - **Proactive Routing** — Match high-entropy domains (Google, Pod) to specific infra immediately. --- ## How It Works 1. **Parse Instructions**: AI converts your natural language prompt into structured JSON 2. **Navigate**: Opens the URL in a Playwright browser 3. **Execute**: For each instruction: - Captures page as ARIA accessibility tree (semantic snapshot) - Asks AI to identify elements by `{role, name}` ARIA descriptor - Performs the action (click, fill, extract, etc.) - Tracks token usage across all providers 4. **Extract Data**: Returns extracted information from the page ### Page Representation — ARIA Accessibility Tree ibr uses Playwright's `ariaSnapshot()` to represent pages to the AI, instead of raw DOM/HTML. The ARIA snapshot is a hierarchical accessibility tree: roles, names, labels, and visible text — the same structure used by screen readers. **Why it matters:** - ~38x smaller context (e.g. 592 kB raw DOM → ~15 kB ARIA snapshot on large pages) - Semantically cleaner: no inline styles, script blocks, SVG noise - More reliable element targeting: AI returns `{role, name}` descriptors, which Playwright resolves via `getByRole` / `getByLabel` / `getByText` **Mode selection:** by default ibr scores the ARIA snapshot quality (sparsity ratio of unlabelled interactive elements) and falls back to `DomSimplifier` (XPath-indexed JSON tree) when quality is too low, snapshot is too large, or snapshot is empty. Use `--mode aria|dom` to override. See the `--mode` section above for details. **Element descriptor format (ARIA path):** ```json {"role": "button", "name": "Sign in"} {"role": "textbox", "name": "Email"} {"role": "link", "name": "Learn more"} ``` **Element descriptor format (DomSimplifier fallback):** ```json {"x": 42} ``` The switch is internal; prompts you write are unaffected — keep describing elements in plain English as always. ## Debugging & Troubleshooting ### Issue: Action Timeouts **Symptom**: "Timeout waiting for element" error **Solution**: - The element may be behind a modal or banner - Add instruction to close/dismiss overlays first - For CAPTCHAs or MFA, use `wait for human` and run with `BROWSER_HEADLESS=false` - Check browser window to see what's blocking the action - Use `BROWSER_SLOWMO` to slow down and observe ```bash BROWSER_SLOWMO=500 ibr "..." ``` ### Issue: Element Not Found **Symptom**: `Unable to resolve element descriptor: {...}` or action failure mentioning `hidden, disabled, or covered by another element` **Solutions**: - Run `ibr snap -i` to list interactive elements and their `@refs` - Use the exact role/name from the snapshot in your prompt - If the element is a pseudo-button (no ARIA role), use `--mode dom` and reference its index - If the element is present but action fails, check for overlays (modal, cookie banner) and add an instruction to dismiss them first ### Issue: JSON Parsing Errors **Symptom**: `Failed to parse task description` or `BAML parser: Unable to extract JSON` **Solutions**: - Set `AI_TEMPERATURE=0` for deterministic outputs - Ensure prompt includes `url:` and `instructions:` fields - If using a custom model, verify it returns structured JSON responses - Try switching `AI_MODEL` to a model known to follow instructions reliably ### Issue: Infinite Loops **Symptom**: Script runs forever on a "repeatedly" instruction **Solutions**: - The loop condition never becomes false - Make sure the condition you're checking actually disappears when done - Script has a safety limit of 100 iterations to prevent hangs - An extract-only loop over a page that never changes stops after its second identical iteration (logged as "made no progress") - Check logs to see which iteration it's stuck on ### Enable Detailed Logging See what's happening at each step: ```bash DEBUG=* ibr "..." ``` Logs show: - Which AI provider and model is being used - Prompt and response tokens for cost tracking - What elements were found - What actions were executed - Detailed error messages if anything fails ### Monitor in Real-Time Keep the browser visible and slow it down: ```bash BROWSER_HEADLESS=false BROWSER_SLOWMO=500 ibr "..." ``` Now you can watch exactly what the script is doing and see where it fails. ## Configuration Reference ### AI Configuration | Variable | Options | Default | Purpose | |----------|---------|---------|---------| | `AI_PROVIDER` | openai, anthropic, google | openai | Which AI service to use | | `AI_TEMPERATURE` | 0-2 | 0 | Response randomness (0=deterministic) | | `AI_MODEL` | Model name | Provider default | Override default model | | `AI_CALL_TIMEOUT_MS` | milliseconds (`0` = off) | 120000 | Per-LLM-call timeout; a hung call fails with `AI_TIMEOUT` and is not retried. Distinct from `EXECUTION_TIMEOUT_MS` (whole run) | | `AI_MAX_OUTPUT_TOKENS` | positive integer | _(provider default)_ | Cap completion tokens per LLM call | ### Browser Configuration | Variable | Values | Default | Purpose | |----------|--------|---------|---------| | `BROWSER_HEADLESS` | true/false | true | Run browser headless | | `BROWSER_SLOWMO` | milliseconds | 100 | Slow down browser actions | | `BROWSER_TIMEOUT` | milliseconds | 30000 | Page load timeout | | `BROWSER_LAUNCH_TIMEOUT_MS` | milliseconds (`0` = off) | 60000 | Cap on the whole launch-to-first-page phase (browser resolve/launch/connect, context, page). On expiry the browser is killed and ibr exits 1 with `BROWSER_LAUNCH_TIMEOUT` (step, browser, stderr tail in the message). Invalid value -> `CONFIG_ERROR` | | `BROWSER_SETTLE_MS` | milliseconds | 3000 | Max wait for network idle after page `load`; pages that never idle (long-polling, beacons) proceed after this cap. `0` = no settle wait | | `BROWSER_CHANNEL` | camoufox/playwright-chromium/chrome/brave/arc/comet/chromium/msedge/lightpanda | _(camoufox if installed, else playwright-chromium)_ | Browser to launch. `chromium` = system Chromium | | `BROWSER_EXECUTABLE_PATH` | path | — | Direct binary override; bypasses probe + cache | | `BROWSER_CDP_URL` | ws URL | — | Connect to running CDP server; skips spawn | | `BROWSER_ARGS` | space-separated | — | Extra Chromium launch flags (e.g. `--user-data-dir=... --profile-directory=...`); ignored for Camoufox | | `BROWSER_REUSE_PAGE` | true/false | false | Reuse existing page/tab in CDP-connected browser instead of opening new tab | | `BROWSER_TAB_INDEX` | integer | 0 | Which tab to reuse when `BROWSER_REUSE_PAGE=true` and multiple tabs open | | `LIGHTPANDA_WS` | ws URL | — | **Deprecated** alias of `BROWSER_CDP_URL` | | `BROWSER_VERSION` | stable/nightly/latest/exact | stable | Version for downloadable browsers | | `BROWSER_DOWNLOAD_URL` | URL | — | Mirror / air-gap binary source | | `BROWSER_FALLBACK` | channel name | — | Fallback channel on lightpanda failure (`playwright-chromium` = bundled Chromium) | | `CAMOUFOX_MODULE_PATH` | path | — | `camoufox` package dir when not resolvable from ibr | | `CAMOUFOX_EXECUTABLE_PATH` | path | — | Camoufox binary to launch instead of the fetched build | | `CAMOUFOX_CANVAS_NOISE` | true/false | false | Faster Camoufox start (~2 s instead of 8-14 s first launch) by skipping its host GPU probe; canvas then reads as privacy-hardened and Camoufox warns on stderr | | `BROWSER_STRICT` | true/false | false | Refuse launch on known-broken capability entries | | `BROWSER_REQUIRE_CHECKSUM` | true/false | false | Refuse install without sha256 checksum | | `LIGHTPANDA_TELEMETRY` | true/false | false | Opt-in lightpanda upstream telemetry | | `OBEY_ROBOTS` | true/false | false | Check robots.txt before automation | | `DIALOG_AUTO_ACCEPT` | true/false | true | Auto-accept browser dialogs (alert/confirm/prompt) | | `DIALOG_BUFFER_CAPACITY` | number | 50000 | Max dialog events to buffer | | `DIALOG_DEFAULT_PROMPT_TEXT` | string | '' | Default text submitted for prompt() dialogs | ### Daemon Configuration | Variable | Values | Default | Purpose | |----------|--------|---------|---------| | `IBR_DAEMON` | true/false | false | Enable persistent browser daemon | | `IBR_STATE_FILE` | path | `~/.ibr/server.json` | Daemon state file path | ### Tool Runner | Variable | Values | Default | Purpose | |----------|--------|---------|---------| | `IBR_TOOL_BASE_URL` | http(s) URL | _(unset)_ | `ibr tool` only: replace scheme + host (+ port) of the tool's `url:`, keep path + query (a path in the value is prefixed); point a tool at a mirror or local copy, e.g. `http://127.0.0.1:8080` | ### Observability | Variable | Values | Default | Purpose | |----------|--------|---------|---------| | `NDJSON_STREAM` | true/false | false | Stream browser events as NDJSON to stdout | | `ANNOTATED_SCREENSHOTS_ON_FAILURE` | true/false | false | Auto-capture annotated PNG on action failure | ### Visual Mode Configuration | Variable | Values | Default | Purpose | |----------|--------|---------|---------| | `VISUAL_AI_MODEL` | Model name | _(AI_MODEL)_ | Vision model for visual mode only; overrides `AI_MODEL` when `--mode visual` or auto-escalation uses vision | | `VISUAL_MAX_ESCALATIONS` | number | 3 | Max auto-mode visual escalations per run (explicit `--mode visual` ignores cap) | | `VISUAL_GRID` | RxC format | 8x8 | Grid fallback dimensions (e.g. `4x4`, `10x10`) when no interactive elements detected | **Grid-cell targets.** When the grid fallback is in play the resolved target is a coordinate (`visual-grid=r0c0`), not an element, so text entry clicks the cell centre to focus it and then types on the keyboard: `fill`/`type` become `keyboard.type(value)` and `press` becomes `keyboard.press(value)`, while `click` is the mouse click alone. A `fill`/`type`/`press` with no value fails with `MISSING_ACTION_VALUE` rather than degrading to a bare click, which would drop the value silently and still report success — state the text or key explicitly in the instruction (e.g. `type 'hello' into the canvas field`). ### API Keys (REQUIRED) - `OPENAI_API_KEY` - For OpenAI provider - `ANTHROPIC_API_KEY` - For Anthropic provider - `GOOGLE_GENERATIVE_AI_API_KEY` - For Google provider Only set the key for your selected provider. ## Output ### Extracted Data ```json [ { "title": "Product Name", "price": "$99.99", "rating": "4.5 stars" } ] ``` ### Token Usage ``` Token usage summary { promptTokens: 1250, completionTokens: 450, totalTokens: 1700 } ``` ### Run Stats (`--stats-json`) `--stats-json ` (or `--stats-json=`; `-` writes one JSON document to stdout) writes machine-readable run stats after a successful run. Additive: `-o`/`--output` and the stderr logs are unchanged. Intended for benchmark adapters (cold/warm/repeat-n). ```json { "schemaVersion": 1, "tokenUsage": { "prompt": 1250, "completion": 450, "total": 1700 }, "cache": { "hits": 2, "misses": 1, "created": 1 }, "plan": { "cached": false, "calls": 1, "tokens": { "prompt": 1000, "completion": 210, "total": 1210 } }, "map_created": 0, "map_reused": 0, "map_family_reused": 0, "map_refs_inferred": 0, "map_skipped": [] } ``` | Field | Meaning | |-------|---------| | `tokenUsage.{prompt,completion,total}` | AI tokens spent this run (same object as the daemon's `tokenUsage`) | | `cache.hits` | action/find lookups served from cache (no AI call) | | `cache.misses` | lookups that fell through to the AI (absent, DOM-incompatible, or failed) | | `cache.created` | cache entries written this run | | `plan.{cached,calls,tokens}` | task-parse LLM call: `cached` true when the plan came from the plan cache (then `calls` 0, tokens 0); `tokens` is the parse call's share of `tokenUsage` (which stays the run total). Plan lookups are not counted in `cache.*` (see [Task Plan Cache](#task-plan-cache)) | | `map_created` / `map_reused` | extract page-maps built fresh vs replayed from cache this run (see [Extract Page-Map Cache](#extract-page-map-cache)) | | `map_family_reused` | subset of `map_reused`: replays served by a verified layout-family map from another URL (opt-in, see [Layout families](#layout-families-opt-in)) | | `map_refs_inferred` | fields whose `_x` ref was missing/invalid and was resolved by [exact value search](#when-the-model-omits-_x) in maps stored this run | | `map_skipped` | `[{ "step": 0, "reason": "value_not_found" }]`: one entry per extract step and reason where a map was not stored or not replayed. `step` = 0-based extract ordinal. Codes are stable, see [Why a map was skipped](#why-a-map-was-skipped). Empty on a clean run | With `--stats-json -`, all logger output is routed to stderr so stdout is the stats JSON alone. Limitation: the interactive wait-for-human prompt still writes to stdout. The daemon `/run` response carries the same object (minus `schemaVersion`) under `stats`; its top-level `tokenUsage` is unchanged. Existing fields are never removed or renamed within a `schemaVersion`; new fields are additive. ### Task Plan Cache The prompt is parsed into `{url, instructions}` by one LLM call per run (~1.2k tokens). ibr caches that result, so a repeated task makes no parse call; with extract maps replaying too, a fully warm run makes 0 LLM calls. Key = your exact task text (only trimmed and whitespace-collapsed; case and punctuation kept) + provider and model + a hash of the parser prompt + ibr version. Changing any of them is a miss. `--param` / `ibr tool` params and stdin prompts are interpolated into the text before parsing, so they are part of the key. Entries expire after `CACHE_PLAN_TTL_DAYS` (default 7; `<=0` never). A cached plan that fails shape validation or names an unknown instruction type is deleted and re-parsed once; ordinary page/extract failures never touch it. `CACHE_ENABLED=false` disables it (every run parses). Stats: `plan` in `--stats-json` / daemon `stats`; plan lookups are not counted in `cache.hits/misses/created`. ### Extract Page-Map Cache In `dom` and default `auto` mode, an `extract` instruction asks the model for per-field source refs (`_x`, stripped from output). ibr stores them as a map `{ field: xpath }` per item, keyed by URL + your original task text + extract-step ordinal (the model's rewritten instruction is not used, so paraphrase cannot change the key) + a text-free structural DOM signature. On the next run the xpaths are read from the live page with no LLM call (`tokenUsage` 0 for that step, `map_reused` +1, `cache.hits` +1). If the layout drifted, a selector misses, or a value is empty, ibr falls back to the LLM and re-creates the map (`map_created` +1). Mode behavior: `auto` (default) sends extract steps in DOM representation when no map replays (DOM prompt with `_x` refs, more prompt tokens than ARIA on that first run), so a map is built and later runs replay it with 0 tokens even on pages where ARIA would otherwise be chosen. `--mode dom` same. `--mode aria` keeps the ARIA prompt: replays an existing map, never builds one. `--mode visual` does not use maps. With the cache disabled nothing changes (plain mode selection). Find/action selection is unaffected. List pages: when the extracted items are exactly all same-tag children of one container, ibr stores a row template (container, row tag, field paths relative to a row) rather than per-item xpaths. The structural signature collapses runs of identical sibling rows, so the same page with more or fewer rows still hits and replay returns every live row. Replay is strict: at least one row, and every field non-empty in every row; otherwise it falls back to the LLM and re-creates the map. Maps from older schema versions are re-created on first use. List-valued fields: a field whose value is an array gathered from several elements (tags, authors, bullet points) is asked for as an array of refs, one per element in value order (`"_x": {"tags": [21, 22]}`); scalar fields keep one integer. Each element is resolved like a scalar (live DOM, own text else an attribute, exact match) and the map stores ordered sources. Replay returns an array, so output shape equals the model's. Count rules: - Per-item maps (and row templates that cannot generalize): fixed count. Each stored source is read; a missing node or empty value rejects the replay. - Row templates: when, in every row, the elements are 2+ same-tag siblings in document order and are ALL siblings of that tag the page has (same completeness guard as rows), the field is stored as a repeated sub-selector and a warm page may have a different number of elements per row. The rule: at least 1 element per row, every element non-empty. Otherwise, if every row has the same count and relative paths, fixed per-index sources are kept; else the map falls back to per-item. - Probation compares array values as ordered lists (elements trimmed and whitespace-collapsed) inside the per-record multiset; renamed fields re-key their refs the same way. Attribute-valued fields: at map-build time ibr checks each field value against the referenced node: its text (own text, else textContent) or, failing that, one of its attributes (`title`, `alt`, `aria-label`, `href`, `src`, `content`, `name`, `id`, `role`). Comparison is exact after whitespace collapse. An attribute source is stored with the field (`{xpath, attr}`; in row templates `{segs, attr}`, which must agree across all rows) and replay reads that attribute. If a value matches neither text nor any attribute, no map is stored for that extract, so every run calls the LLM instead of replaying and failing. #### When the model omits `_x` The DOM extract prompt requires `_x` for every field, but models sometimes skip it. For each field whose ref is missing, invalid (not an integer, out of range, wrong array shape) or points at a node that does not reproduce the value, ibr searches the live DOM for the extracted value instead of giving up. Rules, all exact (no fuzzy, partial or case-insensitive matching): - A node matches when its own text (else textContent) or a kept attribute equals the value after whitespace collapse (same sources and order as above). Nodes with own text or a matching attribute win; wrapper nodes matching only through textContent count when nothing else matches. - Scalar: exactly one matching node, not claimed by another record's value for that field. List-valued field: each element resolves the same way, to distinct nodes. - Several matches on a list page: accepted only when all candidates group into exactly one same-tag row per record, in record order, with exactly one match per value inside its record's row. - Values under 3 characters (and pure numbers likewise) are accepted only through that row alignment, never on a single match; a short scalar or an unaligned short list element is `ref_ambiguous`. Empty values are always ambiguous. Anything else ambiguous skips with `ref_ambiguous`; no match is `value_not_found`. - Fields whose ref is valid and matches keep it (mixed output is fine). A valid ref whose node does not match the value falls back to the same search; if that also fails the skip is `value_not_found` (no match) or `ref_ambiguous` (several). Inferred fields are logged at debug (naming refs that mismatched) and counted in `map_refs_inferred`. The stored map replays like any other, and strict replay still guards correctness. #### Why a map was skipped Whenever a map is not stored or not replayed, ibr logs one info line per reason, `extract map skipped (step N): : `, with per-field detail (field name, element index, xpath) at debug level, and adds `{step, reason}` to `map_skipped` in `--stats-json` and the daemon `stats`. With `--stats-json -` the lines go to stderr. A plain first run (no stored map yet) is not a skip. | Code | Meaning | |------|---------| | `mode_not_dom` | aria or visual mode: no xpath refs (debug line only) | | `no_items` | the extraction returned no records | | `ref_missing` | record has no `_x`, or a field has no ref | | `ref_not_integer` / `ref_out_of_range` | ref is not an integer / not a valid x index | | `ref_ambiguous` | ref missing/invalid and the value cannot be pinned to one node: short (under 3 chars) or empty without row alignment, several nodes match, or no consistent one-per-row alignment | | `ref_not_array` / `ref_array_for_scalar` / `ref_count_mismatch` / `empty_list` | list-field ref shape wrong: array value needs an array ref of equal length; scalar needs a single integer; empty arrays cannot be mapped | | `value_not_found` | value matches neither the node's text nor any attribute | | `signature_unavailable` | no structural signature for the page | | `ambiguous_names` | probation matched but repeated values stop LLM names being aligned to the stored names | | `ttl_expired` / `failure_limit` | stored map expired (`CACHE_EXTRACT_TTL_DAYS`) / deleted after repeated failures | | `version_mismatch` / `shape_invalid` | stored map from another schema version / malformed | | `signature_drift` | page structure differs from the stored map | | `replay_empty_field` | a replayed field was missing or empty (field named in the log) | | `replay_count_mismatch` | wrong record count, zero rows, or a list field with no elements | | `replay_error` | the live read threw | | `family_no_wildcard` | family mode on but the URL has no id-shaped segment (debug line only) | | `family_unverified_creator` | unverified family was created by this URL; replay is no evidence | | `family_probation_mismatch` | probation run disagreed with the family map; family deleted | | `family_*` | a family replay rejected for any `replay_*`, `version_mismatch`, `shape_invalid`, `signature_drift`, `ttl_expired` or `failure_limit` reason | The log line for a live-DOM read that fell back to the simplified tree (`live_dom_unavailable`) is debug only and not counted in `map_skipped`: the map is still stored when the tree can resolve the values. #### Value attributes (opt-in) The DOM view the LLM sees keeps only `id href src alt title aria-label role name content`. `--value-attrs` (or `DOM_VALUE_ATTRS=1`; `--no-value-attrs` overrides the env var; `ibr snap --value-attrs` too) also keeps `datetime`, `value`, `aria-valuenow`, `aria-valuetext` and up to 10 `data-*` per element (sorted by name; values over 200 chars skipped), so ``, ``, ``, `` or `data-price` can be read and extracted. Off by default: it adds prompt tokens on attribute-heavy pages. Maps built with it on are keyed separately from maps built with it off. The daemon reads the env var only. Replay reads the live DOM, so it is independent of the flag. #### Layout families (opt-in) Off by default. `--extract-family` (or `CACHE_EXTRACT_FAMILY=1`) lets URLs of one layout family share a map: `/item/123` builds it, `/item/456` replays it. `--no-extract-family` overrides the env var. The daemon reads the env var only. - Family = origin + URL pattern + prompt + structural signature. Pattern: path segments that are digits (``), UUIDs, ISO dates, 16+ char hex, ULIDs, or 12+ char letter+digit tokens become wildcards. Slugs (`my-post`), locales (`/en/`), versions (`v2`) and plain words stay literal; a URL with no wildcard has no family. `/blog/2024` and `/blog/about` are different families. - Lookup: exact-URL map first. Only if that is absent or its signature differs (not if it replayed and failed) is the family map tried. Family replay is as strict as exact replay, and the signature must equal. - Probation: the first reuse of a family map on a URL other than the one that built it replays the map and also runs the LLM, then compares. Match: family verified, later reuses skip the LLM. Mismatch: family entry deleted, the LLM result is used and a fresh unverified family is built from this URL. A probation run counts as a cache miss with LLM tokens; `map_reused` and `map_family_reused` are not bumped. - Comparison: same item count, item order significant; per item, same field count and same multiset of values (field names and key order ignored, since LLMs rename keys between runs), values equal after `String()`, whitespace collapse and trim. Case-sensitive, no fuzzy matching, so a paraphrasing model keeps a family unverified (it just keeps using the LLM). - Field names: on a probation match the run returns the replayed values under the stored map's field names, and the URL's exact map is stored under those names too (LLM keys re-keyed by value; if a record repeats a value the mapping is ambiguous, so no exact map is written and the verified family serves the URL). On a mismatch the family is deleted and the LLM result is returned with the LLM's own key names. So a verified family always yields the stored names. - Family hits do not write an exact entry. Failures strike the family entry only (3 strikes delete it, same as exact maps). `CACHE_EXTRACT_TTL_DAYS` applies. | Variable | Values | Default | Purpose | |----------|--------|---------|---------| | `CACHE_ENABLED` | true/false | true | Master cache switch | | `CACHE_DIR` | path | XDG/OS cache dir | Cache location | | `CACHE_EXTRACT_TTL_DAYS` | number | 7 | Extract-map lifetime; `<=0` never expires extract maps (find/action entries never expire) | | `CACHE_PLAN_TTL_DAYS` | number | 7 | Task-plan lifetime; `<=0` never expires plans | | `DOM_VALUE_ATTRS` | bool | off | `1`/`true`: keep `datetime`, `value`, `aria-valuenow/text` and capped `data-*` in the DOM view (`--value-attrs` / `--no-value-attrs` override) | | `CACHE_EXTRACT_FAMILY` | bool | off | `1`/`true`: share extract maps across URLs of one layout family (`--extract-family` / `--no-extract-family` override) | ## Common Patterns ### Scrape Paginated Content ```yaml url: https://example.com/products instructions: - repeatedly: - extract all items: name, price - click 'next page' if found ``` ### Fill and Submit Form ```yaml url: https://example.com/contact instructions: - fill 'name' with John Doe - fill 'email' with john@example.com - fill 'message' with Hello World - click 'submit button' - extract confirmation message ``` ### Handle Dynamic Content ```yaml url: https://example.com instructions: - click 'load more' if found - wait for content to load - repeatedly: - scroll down - click 'load more' if found - extract new items - extract final data ``` ## Tips for Best Results 1. **Be Descriptive**: Instead of "button", use "submit button at bottom of form" 2. **Consider DOM Changes**: Elements may not be in the same place after actions 3. **Handle Common Issues**: Banners, popups, logins often block actions 4. **Test Incrementally**: Start with simple instructions and build up 5. **Watch Execution**: Use browser window to see what's happening 6. **Check Logs**: Detailed logs show exactly what failed and why 7. **Use Deterministic AI**: Keep `AI_TEMPERATURE=0` for consistent results ## Limitations - Requires API key for selected AI provider - `--cookies` flag supports macOS, Linux, and Windows - May struggle with heavily JavaScript-rendered content - No built-in retry on transient failures (but logs indicate when/why to retry) - Browser automation is slower than direct API calls ## LLM Judge (Extraction Quality) Scores E2E extraction results against fixture ground-truth using an LLM judge (0–10 scale). ```bash # Run after E2E tests have written results to test/results/e2e/ npm run judge:e2e # Options npm run judge:e2e -- --threshold 8 # fail if mean < 8 (default 7) npm run judge:e2e -- --validate # 3-run variance check npm run judge:e2e -- --run-id my-run # label the report npm run judge:e2e -- --output-dir /tmp/out # custom results dir ``` Writes `-quality.json` and `-summary.md` to the output dir. Exits 0 when mean score ≥ threshold; exits 1 when below. Fixtures without `expectedExtracts` are skipped — CI does not fail. ## Building Requires Node >=22. Run once to produce `dist/ibr` and `dist/ibr-server`: task build Binaries are self-contained (no Node runtime needed). Native deps (Playwright, better-sqlite3, @boundaryml/baml) must still exist in `node_modules` alongside the binary; they cannot be embedded in the SEA blob. On Homebrew (split-build) Node, the build downloads and caches a self-contained runtime in `dist/.node-sea-bin`; it is re-downloaded when its version or platform/arch no longer matches the local `node`. That download is verified: `SHASUMS256.txt.asc` is checked with system `gpg` against vendored Node.js release keys (`scripts/node-release-keys/`), then the tarball sha256 is checked against the verified text. `gpg` is needed only in this case (`brew install gnupg`); builds on a regular Node never need it. A missing `gpg`, bad signature, or signer outside the allowlist fails the build. Refresh the keys with `node scripts/refresh-node-release-keys.mjs` and review the diff. ## Version & Upgrade ```bash ibr version # human-readable version string ibr version --short # version only — scriptable (e.g. in CI checks) ibr version --json # JSON: version, node, platform, arch ibr upgrade # check for and install available updates ibr upgrade --auto # non-interactive install ibr upgrade --quiet # suppress output (use exit code only) ibr upgrade preamble # emit agent skill preamble fragment (for AI agent configs) ``` --- ## Related Tools | Tool | Notes | |------|-------| | [LightPanda](https://github.com/lightpanda-io/browser) | Headless browser in Zig; 11x faster, 9x less memory than Chrome. CDP-compatible. Beta — CORS gap limits Playwright parity today. Potential future ibr backend for high-throughput scraping workloads. | ## License ISC ## Support For issues and feedback, see `.env.example` for configuration help or check logs for detailed error messages.