gsd-browser
Native Rust browser automation CLI for AI agents. Use when the user needs to interact with websites — navigating pages, filling forms, clicking buttons, taking screenshots, sharing a live browser view, narrating browser actions, extracting structured data, running assertions, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "show me the browser", "share the screen", "pause the browser", "step through this", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", "visual regression test", "check for prompt injection", or any task requiring programmatic web interaction.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/gsd-build--gsd-browser)HTML
<a href="/listings/gsd-build--gsd-browser"><img src="/api/listings/gsd-build--gsd-browser/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
These steps run a script from the network that findsafeskills does not scan.
Recommended: installer (macOS / Linux)
curl -fsSL https://install.gsd.build/browser | bash
The installer downloads the correct `gsd-browser` binary for your platform. If Chrome or Chromium is already installed, it uses that. Otherwise it downloads Chromium automatically when Chrome for Testing is available for your platform. Run `gsd-browser update` to install the current release.
Pre-built binaries
Download from [GitHub Releases](https://github.com/gsd-build/gsd-browser/releases):
| Platform | Asset | |----------|-------| | macOS (Apple Silicon) | `gsd-browser-darwin-arm64` | | macOS (Intel) | `gsd-browser-darwin-x64` | | Linux (ARM64) | `gsd-browser-linux-arm64` | | Linux (x64) | `gsd-browser-linux-x64` |
Build from source
git clone https://github.com/gsd-build/gsd-browser.git cd gsd-browser cargo install --path cli
Package registries
The public npm package (`@gsd-build/gsd-browser`) and crates.io package (`gsd-browser`) are not published yet. Use the installer, GitHub release assets, or a source build.
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 783 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- ---
- name: gsd-browser
- description: >
- Native Rust browser automation CLI for AI agents. Use when the user needs to
- interact with websites — navigating pages, filling forms, clicking buttons,
- taking screenshots, sharing a live browser view, narrating browser actions,
- extracting structured data, running assertions, testing web apps, or
- automating any browser task. Triggers include requests to "open a website",
- "fill out a form", "click a button", "take a screenshot", "show me the
- browser", "share the screen", "pause the browser", "step through this",
- "scrape data from a page", "test this web app", "login to a site",
- "automate browser actions", "visual regression test", "check for prompt
- injection", or any task requiring programmatic web interaction.
- allowed-tools: Bash(gsd-browser:*), Bash(gsd-browser *)
- ---
- # Browser Automation with gsd-browser
- ## Critical Rules
- 1. **The daemon auto-starts on browser commands.** `daemon health` only reports state; it does not start a session. Use `daemon start` only when you want to pre-warm or verify daemon lifecycle explicitly.
- 2. **Always re-snapshot after page changes.** Refs are versioned (`@v1:e1`). After navigation, form submission, or dynamic content loading, old refs are stale. Run `gsd-browser snapshot` to get fresh refs.
- 3. **Use `--json` when parsing output.** Use text mode when reading output yourself. Use `--json` when you need to extract values programmatically (e.g., checking assertion results, parsing snapshot refs).
- 4. **Positional args have no flag prefix.** Commands like `click`, `type`, `hover` take positional args — do NOT add `--selector`. See exact syntax in command reference below.
- 5. **Use `batch` for atomic multi-step flows.** Batch reduces round trips and keeps pass/fail checks in one call. Use separate commands when you need intermediate output (e.g., snapshot to discover refs).
- 6. **Use `view` when the user wants to watch or direct the browser.** The live viewer is an authenticated local workbench with Control, Annotate, Record, and Sensitive modes. Keep CLI commands on the same named session.
- ## Core Workflow
- Every browser automation follows this pattern:
- 1. **Navigate**: `gsd-browser navigate <url>`
- 2. **Snapshot**: `gsd-browser snapshot` (get versioned refs like `@v1:e1`, `@v1:e2`)
- 3. **Interact**: Use refs to click, fill, hover
- 4. **Re-snapshot**: After navigation or DOM changes, get fresh refs
- ```bash
- gsd-browser navigate https://example.com/form
- gsd-browser snapshot
- # Output: @v1:e1 [input type="email"], @v1:e2 [input type="password"], @v1:e3 [button] "Submit"
- gsd-browser fill-ref @v1:e1 "user@example.com"
- gsd-browser fill-ref @v1:e2 "password123"
- gsd-browser click-ref @v1:e3
- gsd-browser wait-for --condition network_idle
- gsd-browser snapshot # REQUIRED — old refs are now stale
- ```
- ## Command Chaining
- Commands can be chained with `&&` in a single shell invocation. Browser state also persists across separate invocations through the background daemon when you stay on the same session.
- ```bash
- # Chain navigate + wait + snapshot
- gsd-browser navigate https://example.com && gsd-browser wait-for --condition network_idle && gsd-browser snapshot
- # Chain multiple interactions
- gsd-browser fill-ref @v1:e1 "user@example.com" && gsd-browser fill-ref @v1:e2 "password123" && gsd-browser click-ref @v1:e3
- ```
- **When to chain:** Use `&&` when you don't need intermediate output. Run commands separately when you need to parse output first (e.g., snapshot to discover refs, then interact).
- ---
- ## Command Reference
- Argument syntax: `<arg>` = required positional, `[arg]` = optional positional, `--flag` = named option. Do NOT add `--` prefix to positional args.
- ### Navigation
- ```bash
- gsd-browser navigate <url> # Navigate to a URL
- gsd-browser back # Go back in browser history
- gsd-browser forward # Go forward in browser history
- gsd-browser reload # Reload the current page
- ```
- ### Interaction
- All selectors are **positional** — do NOT use `--selector`.
- ```bash
- # Click
- gsd-browser click <selector> # Click by CSS selector
- gsd-browser click --x 100 --y 200 # Click by coordinates (no selector)
- # Type — positional: <selector> <text>
- gsd-browser type <selector> <text> # Atomic fill (replaces content)
- gsd-browser type <selector> <text> --slowly # Character-by-character
- gsd-browser type <selector> <text> --clear-first # Clear field before typing
- gsd-browser type <selector> <text> --submit # Press Enter after typing
- # Other interaction — all positional selectors
- gsd-browser press <key> # Press key: Enter, Escape, Tab, Meta+A
- gsd-browser hover <selector> # Hover over element
- gsd-browser scroll --direction down # Scroll down 300px (default)
- gsd-browser scroll --direction up --amount 500 # Scroll up 500px
- gsd-browser select-option <selector> <option> # Select dropdown by label or value
- gsd-browser set-checked <selector> --checked # Check checkbox/radio (omit --checked to uncheck)
- gsd-browser drag <source-selector> <target-selector> # Drag-and-drop
- gsd-browser upload-file <selector> <file>... # Set files on <input type="file">
- gsd-browser set-viewport --preset mobile # Preset: mobile, tablet, desktop, wide
- gsd-browser set-viewport --width 1920 --height 1080 # Custom dimensions
- ```
- ### Snapshot & Refs
- Refs are versioned (`@v1:e1`, `@v2:e3`). The version increments each snapshot. **Old refs become stale after page changes — always re-snapshot.**
- ```bash
- # Take snapshot
- gsd-browser snapshot # Snapshot interactive elements, assign refs
- gsd-browser snapshot --selector "form" # Scope to a CSS selector
- gsd-browser snapshot --mode <mode> # Semantic mode (see below)
- gsd-browser snapshot --limit 80 # Increase element limit (default: 40)
- # Use refs — all positional
- gsd-browser get-ref <ref> # Get metadata for a ref
- gsd-browser click-ref <ref> # Click element by ref
- gsd-browser hover-ref <ref> # Hover element by ref
- gsd-browser fill-ref <ref> <text> # Type into element by ref
- ```
- **Snapshot modes** (`--mode`):
- | Mode | What it captures |
- |------|-----------------|
- | `interactive` | Buttons, inputs, links, selects (default) |
- | `form` | Form fields with labels and current values |
- | `dialog` | Elements inside open dialogs/modals |
- | `navigation` | Links and nav elements |
- | `errors` | Error messages, validation warnings |
- | `headings` | Heading elements (h1-h6) for page structure |
- | `visible_only` | All visible elements regardless of interactivity |
- ### Inspection
- ```bash
- gsd-browser accessibility-tree # Full accessibility tree (roles, names, states)
- gsd-browser find --text "Sign In" # Find elements by text (case-insensitive)
- gsd-browser find --role button # Find by ARIA role
- gsd-browser find --selector ".my-class" # Find by CSS selector
- gsd-browser find --role link --limit 50 # Increase limit (default: 20)
- gsd-browser page-source # Get raw HTML of page
- gsd-browser page-source --selector "main" # Scoped HTML source
- gsd-browser eval '<js-expression>' # Evaluate JavaScript in page context
- ```
- ### Assertions
- Run explicit pass/fail checks against the current page state. Prefer this over inferring success from output.
- ```bash
- gsd-browser assert --checks '[
- {"kind": "url_contains", "text": "/dashboard"},
- {"kind": "text_visible", "text": "Welcome"},
- {"kind": "selector_visible", "selector": "#user-menu"},
- {"kind": "value_equals", "selector": "input[name=email]", "value": "user@test.com"},
- {"kind": "no_console_errors"},
- {"kind": "no_failed_requests"}
- ]'
- ```
- **Assertion kinds (17):** `url_contains`, `text_visible`, `text_hidden`, `selector_visible`, `selector_hidden`, `value_equals`, `checked`, `no_console_errors`, `no_failed_requests`, `request_url_seen`, `response_status`, `console_message_matches`, `network_count`, `console_count`, `element_count`, `no_console_errors_since`, `no_failed_requests_since`.
- ### Batch Execution
- Execute multiple steps in one call to reduce round trips. Stops on first failure by default.
- ```bash
- gsd-browser batch --steps '[
- {"action": "navigate", "url": "https://example.com"},
- {"action": "wait_for", "condition": "network_idle"},
- {"action": "click", "selector": "#login-btn"},
- {"action": "type", "selector": "input[name=email]", "text": "user@test.com"},
- {"action": "type", "selector": "input[name=password]", "text": "secret", "submit": true},
- {"action": "assert", "checks": [{"kind": "url_contains", "text": "/dashboard"}]}
- ]'
- # With --summary-only to reduce output
- gsd-browser batch --steps '[...]' --summary-only
- ```
- **Batch actions:** `navigate`, `click`, `type`, `key_press`, `wait_for`, `assert`, `click_ref`, `fill_ref`.
- ### Wait Conditions
- ```bash
- gsd-browser wait-for --condition selector_visible --value "#content"
- gsd-browser wait-for --condition selector_hidden --value ".spinner"
- gsd-browser wait-for --condition url_contains --value "/dashboard"
- gsd-browser wait-for --condition network_idle
- gsd-browser wait-for --condition delay --value 2000
- gsd-browser wait-for --condition text_visible --value "Success"
- gsd-browser wait-for --condition text_hidden --value "Loading"
- gsd-browser wait-for --condition request_completed --value "/api/data"
- gsd-browser wait-for --condition console_message --value "ready"
- gsd-browser wait-for --condition element_count --value ".item" --threshold ">=5"
- gsd-browser wait-for --condition region_stable --value "#content"
- # Custom timeout (default: 10000ms)
- gsd-browser wait-for --condition selector_visible --value "#slow" --timeout 30000
- ```
- ### Forms (Smart Fill)
- Analyze forms and fill them by field label, name, placeholder, or aria-label — no selectors needed.
- ```bash
- # Analyze form structure
- gsd-browser analyze-form
- gsd-browser analyze-form --selector "#signup-form"
- # Fill by field identifiers (resolved: label -> name -> placeholder -> aria-label)
- gsd-browser fill-form --values '{"Email": "a@b.com", "Password": "secret", "Country": "US"}'
- gsd-browser fill-form --values '{"Email": "a@b.com"}' --submit # Fill and click submit
- gsd-browser fill-form --values '{"Email": "a@b.com"}' --selector "#login-form"
- ```
- ### Intent-Based Interaction
- Find and act on elements by semantic intent — no selectors or refs needed. Intents are predefined categories, not free-form text.
- ```bash
- # Find top candidates for an intent (returns scored matches with selectors)
- gsd-browser find-best --intent submit_form
- gsd-browser find-best --intent accept_cookies
- gsd-browser find-best --intent primary_cta --scope "#modal"
- # Act: find best match and click/focus it in one call
- gsd-browser act --intent submit_form
- gsd-browser act --intent accept_cookies
- gsd-browser act --intent fill_email
- ```
- **Intents (15):**
- | Intent | Action | Description |
- |--------|--------|-------------|
- | `submit_form` | click | Submit buttons, form actions |
- | `close_dialog` | click | Modal/dialog close buttons |
- | `primary_cta` | click | Primary call-to-action elements |
- | `search_field` | focus | Search inputs and searchboxes |
- | `next_step` | click | Next/continue/proceed buttons |
- | `dismiss` | click | Dismiss overlays, banners, toasts |
- | `auth_action` | click | Login/signup/register buttons |
- | `back_navigation` | click | Back/previous navigation links |
- | `fill_email` | focus | Email input fields |
- | `fill_password` | focus | Password input fields |
- | `fill_username` | focus | Username/login input fields |
- | `accept_cookies` | click | Cookie consent accept buttons |
- | `main_content` | click | Main content area (`<main>`, `<article>`, semantic markup required) |
- | `pagination_next` | click | Next page in pagination |
- | `pagination_prev` | click | Previous page in pagination |
- ### Pages & Frames
- Page and frame IDs are **positional** — do NOT use `--id`.
- ```bash
- gsd-browser list-pages # List all open tabs
- gsd-browser switch-page <id> # Switch to tab by ID (positional)
- gsd-browser close-page <id> # Close a tab by ID (positional)
- gsd-browser list-frames # List all frames (main + iframes)
- gsd-browser select-frame --name "iframe-name" # Select frame by name
- gsd-browser select-frame --url-pattern "embed" # Select frame by URL substring
- gsd-browser select-frame --index 0 # Select by index
- gsd-browser select-frame --name main # Return to main frame
- ```
- ### Diagnostics
- ```bash
- gsd-browser console # Get console log entries (clears buffer)
- gsd-browser console --no-clear # Read without clearing
- gsd-browser network # Get network log entries
- gsd-browser dialog # Get dialog events (alert, confirm, prompt)
- gsd-browser timeline # Query the action timeline
- gsd-browser session-summary # Diagnostic summary of current session
- gsd-browser debug-bundle # Full debug bundle: screenshot + logs + timeline + a11y tree
- ```
- ### Live Viewer & Workbench
- The live viewer is a localhost screen-sharing and control surface for the active browser session. It prints or opens a tokenized URL bound to the session, viewer id, local origin, expiry, and capabilities. The viewer displays live frames, narrated action history, ref overlays, target rings, click ripples, failure markers, and page-following across navigation or tab changes.
- ```bash
- gsd-browser view # Open the live viewer
- gsd-browser view --print-only # Print tokenized URL only
- gsd-browser view --interactive # Interactive local workbench
- gsd-browser view --history # Open history-focused viewer
- gsd-browser view --history --print-only # Print history URL only
- gsd-browser goal "Find the checkout button" # Set viewer goal banner
- gsd-browser goal --clear # Clear goal banner
- gsd-browser control-state # Show shared owner/mode/version
- gsd-browser takeover # Give page input to the viewer
- gsd-browser release-control # Return page input to the agent
- gsd-browser pause # Pause before next narrated action
- gsd-browser resume # Resume actions
- gsd-browser step # Allow one action, then pause
- gsd-browser abort # Abort next gated action
- gsd-browser sensitive-on # Local human control with redaction
- gsd-browser sensitive-off # Leave sensitive mode
- ```
- Use one named session for the whole shared-screen flow:
- ```bash
- gsd-browser --session demo navigate https://example.com
- gsd-browser --session demo view --print-only
- gsd-browser --session demo click "h1"
- ```
- Viewer controls:
- | Control | Effect |
- |---------|--------|
- | Control | Forwards pointer, wheel, keyboard, text, and paste input to Chrome |
- | Annotate | Creates point annotations without forwarding page input |
- | Record | Starts or stops a local recording bundle |
- | Sensitive | Keeps local viewer control active and applies redaction policy |
- | Pause | Blocks agent page input |
- | Resume | Allows actions to continue |
- | Step | Allows one action, then returns to paused mode |
- | Abort | Aborts the next gated action |
- | Refs overlay | Shows or hides target boxes/labels |
- Keyboard shortcuts: Space pauses/resumes, Right Arrow steps, Escape aborts, `R` toggles refs.
- Risky visible targets such as destructive labels, payment actions, OAuth grants, credential entry, file transfer, production/admin surfaces, and cross-origin navigation produce an approval banner. Approval dispatches the exact pending command stored by the daemon.
- Annotations:
- ```bash
- gsd-browser annotations
- gsd-browser annotation-get <id>
- gsd-browser annotation-clear <id>
- gsd-browser annotation-clear --all
- gsd-browser annotation-resolve <id>
- gsd-browser annotation-export --output annotations.json
- gsd-browser annotation-request "Select the button to restyle"
- ```
- Recording bundles:
- ```bash
- gsd-browser record-start --name checkout-bug
- gsd-browser record-stop
- gsd-browser record-pause
- gsd-browser record-resume
- gsd-browser recordings
- gsd-browser recording-get <id>
- gsd-browser recording-export <id> --output <path>
- gsd-browser recording-discard <id>
- gsd-browser recording-validate <id-or-path> --json
- ```
- Viewer annotations and recording bundles are local daemon artifacts. Recording manifests use `BrowserArtifactBundleV1`, ordered JSONL events, redaction metadata, and local artifact directories under the browser state path.
- Use `--no-narration-delay` for fast agent-only runs that keep narration events/history without lead-time sleeps:
- ```bash
- gsd-browser --session demo --no-narration-delay click "h1"
- ```
- ### Visual
- ```bash
- gsd-browser screenshot # Screenshot to stdout (JPEG base64)
- gsd-browser screenshot --output page.png # Write to file
- gsd-browser screenshot --format png # Force PNG format
- gsd-browser screenshot --full-page # Full scrollable page
- gsd-browser screenshot --selector "#hero" # Crop to element (always PNG)
- gsd-browser screenshot --quality 50 # JPEG quality 1-100 (default: 80)
- gsd-browser zoom-region --x 100 --y 200 --width 400 --height 300 # Capture region
- gsd-browser zoom-region --x 0 --y 0 --width 200 --height 200 --scale 3 # Upscale
- gsd-browser save-pdf # Save page as PDF (A4 default)
- gsd-browser save-pdf --output report.pdf # Custom output path
- gsd-browser save-pdf --format Letter # Page format: A4, Letter, Legal, Tabloid
- ```
- ### Visual Regression
- ```bash
- # First run: saves baseline screenshot
- gsd-browser visual-diff --name "homepage"
- # Subsequent runs: compare against baseline, report mismatch
- gsd-browser visual-diff --name "homepage"
- gsd-browser visual-diff --name "homepage" --threshold 0.05 # Stricter tolerance (0-1)
- gsd-browser visual-diff --selector "#hero" --name "hero" # Scope to element
- gsd-browser visual-diff --name "homepage" --update-baseline # Reset baseline
- ```
- ### Structured Data Extraction
- ```bash
- # Single item
- gsd-browser extract --schema '{
- "type": "object",
- "properties": {
- "title": {"_selector": "h1", "_attribute": "textContent"},
- "price": {"_selector": ".price", "_attribute": "textContent"},
- "image": {"_selector": "img.product", "_attribute": "src"}
- }
- }'
- # Array of items
- gsd-browser extract --selector ".product-card" --multiple --schema '{
- "type": "object",
- "properties": {
- "name": {"_selector": "h3", "_attribute": "textContent"},
- "price": {"_selector": ".price", "_attribute": "textContent"}
- }
- }'
- ```
- ### Network Mocking
- ```bash
- gsd-browser mock-route --url "**/api/users*" --body '[{"name":"Alice"}]' --status 200
- gsd-browser mock-route --url "**/api/data" --body '{"ok":true}' --delay 3000 # Slow response
- gsd-browser block-urls "**/analytics*" "**/ads*" # Block URL patterns (positional)
- gsd-browser clear-routes # Remove all mocks and blocks
- ```
- ### Device Emulation
- ```bash
- gsd-browser emulate-device <device-name> # Full device emulation (positional)
- gsd-browser emulate-device "iPhone 15"
- gsd-browser emulate-device "Pixel 7"
- gsd-browser emulate-device "iPad Pro 11"
- gsd-browser emulate-device list # Show all available presets
- ```
- **Warning:** Device emulation recreates the browser context — current page state and cookies are lost.
- ### State & Auth
- ```bash
- # Save/restore browser state (cookies, localStorage, sessionStorage)
- gsd-browser save-state --name "logged-in"
- gsd-browser restore-state --name "logged-in"
- # Auth vault (encrypted credentials)
- gsd-browser vault-save --profile github --url https://github.com/login \
- --username user --password "secret"
- gsd-browser vault-login --profile github
- gsd-browser vault-list # List profiles (no secrets shown)
- ```
- Vault encryption requires `GSD_BROWSER_VAULT_KEY` env var set **before the daemon starts**. If the daemon is already running, stop it first, set the var, then run your vault command.
- ### Tracing & Recording
- ```bash
- gsd-browser trace-start # Start CDP performance trace
- gsd-browser trace-start --name "checkout-flow" # Named trace
- gsd-browser trace-stop # Stop and write trace to disk
- gsd-browser trace-stop --name "checkout.json" # Custom output filename
- gsd-browser har-export # Export network as HAR 1.2 JSON
- gsd-browser har-export --filename "session.har" # Custom output path
- gsd-browser generate-test # Generate Playwright test from timeline
- gsd-browser generate-test --name "login-flow" --output tests/login.spec.ts
- ```
- ### Security
- ```bash
- gsd-browser check-injection # Scan for prompt injection in page content
- gsd-browser check-injection --include-hidden # Include hidden/invisible text (default: true)
- ```
- ### Action Cache
- Reduce repeated element lookups by caching intent-to-selector mappings.
- ```bash
- gsd-browser action-cache --action stats # Show cache metrics
- gsd-browser action-cache --action get --intent submit_form # Look up cached selector
- gsd-browser action-cache --action put --intent submit_form --selector "#submit-btn" --score 0.95
- gsd-browser action-cache --action clear # Flush cache
- ```
- ### Daemon Management
- The daemon auto-starts on browser commands. These are for explicit lifecycle control.
- ```bash
- gsd-browser daemon stop # Stop daemon (idempotent — safe on dead processes)
- gsd-browser daemon health # Health check (read-only, does not auto-start)
- gsd-browser daemon start # Explicit start (pre-warm browser before commands)
- gsd-browser update # Install the current release
- ```
- ---
- ## Global Options
- Available on all commands:
- | Flag | Description |
- |------|-------------|
- | `--json` | Output as JSON (use when parsing output programmatically) |
- | `--browser-path <path>` | Path to Chrome/Chromium binary |
- | `--cdp-url <url>` | Attach to an already-running Chrome (e.g. `http://localhost:9222`) |
- | `--session <name>` | Named session for parallel browser instances |
- | `--no-narration-delay` | Skip narration lead-time sleeps while keeping history/events |
- ---
- ## Error Recovery
- ### Stale refs
- ```
- Error: resolve_ref: JS evaluation failed: ref @v1:e3 not found
- ```
- Refs become stale after page changes. Fix: re-snapshot and use the new version.
- ```bash
- gsd-browser snapshot # Get fresh refs (@v2:eN)
- gsd-browser click-ref @v2:e1
- ```
- ### Click/type timeouts
- ```
- Error: click timed out after 10s for: #submit-btn
- ```
- The element may not be visible, may be behind an overlay, or may not exist. Try:
- ```bash
- gsd-browser find --selector "#submit-btn" # Verify element exists
- gsd-browser scroll --direction down # Scroll it into view
- gsd-browser wait-for --condition selector_visible --value "#submit-btn" # Wait for it
- gsd-browser click "#submit-btn" # Retry
- ```
- ### Empty console/network logs
- Console and network buffers start fresh each navigation. If you need logs from a specific action, check them **before** navigating away:
- ```bash
- gsd-browser navigate https://example.com
- gsd-browser eval "fetch('/api/data')"
- gsd-browser network # Check network BEFORE navigating away
- ```
- ### Cookie banners / overlays blocking interaction
- Many sites show consent banners that block clicks. Dismiss them first:
- ```bash
- gsd-browser act --intent accept_cookies # Auto-find and click accept button
- gsd-browser act --intent dismiss # Or dismiss generic overlays
- ```
- ### Session is stopped, unhealthy, or opens a fresh blank page
- If `daemon health` reports `stopped` or `unhealthy`, or a named session no longer has the page you expected, that session does not currently map to a live daemon/browser pair.
- ```bash
- gsd-browser --session site1 daemon health
- gsd-browser --session site1 daemon stop
- gsd-browser --session site1 navigate https://example.com
- ```
- Use the same `--session` value on every follow-up command. `batch` is still useful for atomic flows, but separate invocations are supported when the session is healthy.
- ### Daemon won't start
- ```
- Error: daemon did not start within 10s
- ```
- Usually the session is unhealthy, startup exited early, or browser launch state is stale. Fix:
- ```bash
- gsd-browser daemon health # Inspect current state
- gsd-browser daemon stop # Clear the current session state
- gsd-browser daemon start # Retry explicit startup
- ```
- ---
- ## Common Patterns
- ### Form Submission
- ```bash
- gsd-browser navigate https://example.com/signup
- gsd-browser analyze-form # Discover field labels and types
- gsd-browser fill-form --values '{"Full Name": "Jane Doe", "Email": "jane@example.com", "State": "California"}' --submit
- gsd-browser wait-for --condition network_idle
- gsd-browser assert --checks '[{"kind": "text_visible", "text": "Welcome"}]'
- ```
- ### Login Flow (Refs)
- ```bash
- gsd-browser navigate https://app.example.com/login
- gsd-browser act --intent accept_cookies # Dismiss cookie banner if present
- gsd-browser snapshot
- # Read snapshot output to find email, password, and submit refs
- gsd-browser fill-ref @v1:e1 "$USERNAME"
- gsd-browser fill-ref @v1:e2 "$PASSWORD"
- gsd-browser click-ref @v1:e3
- gsd-browser wait-for --condition url_contains --value "/dashboard"
- gsd-browser save-state --name "myapp-auth" # Save for reuse
- ```
- ### Login Flow (Vault)
- ```bash
- # Save credentials once (encrypted at rest)
- gsd-browser vault-save --profile myapp \
- --url https://app.example.com/login \
- --username user@example.com \
- --password "$PASSWORD"
- # Login in any future session
- gsd-browser vault-login --profile myapp
- gsd-browser wait-for --condition url_contains --value "/dashboard"
- ```
- ### Reuse Saved Auth
- ```bash
- gsd-browser restore-state --name "myapp-auth"
- gsd-browser navigate https://app.example.com/dashboard # Already logged in
- ```
- ### Data Scraping
- ```bash
- gsd-browser navigate https://example.com/products
- gsd-browser extract --selector ".product" --multiple --schema '{
- "type": "object",
- "properties": {
- "name": {"_selector": ".title", "_attribute": "textContent"},
- "price": {"_selector": ".price", "_attribute": "textContent"},
- "link": {"_selector": "a", "_attribute": "href"}
- }
- }'
- ```
- ### Visual Regression Testing
- ```bash
- # Establish baseline (first run)
- gsd-browser navigate https://example.com
- gsd-browser visual-diff --name "home-page"
- # Later: compare current state
- gsd-browser navigate https://example.com
- gsd-browser visual-diff --name "home-page"
- # Output: similarity %, diff pixel count, diff image path
- ```
- ### Network Mocking for Testing
- ```bash
- gsd-browser mock-route --url "**/api/users" --body '{"error":"server error"}' --status 500
- gsd-browser navigate https://app.example.com
- gsd-browser assert --checks '[{"kind": "text_visible", "text": "Something went wrong"}]'
- gsd-browser clear-routes # Clean up mocks
- ```
- ### Parallel Sessions
- ```bash
- gsd-browser --session site1 navigate https://site-a.com
- gsd-browser --session site2 navigate https://site-b.com
- gsd-browser --session site1 snapshot
- gsd-browser --session site2 snapshot
- # Clean up both
- gsd-browser --session site1 daemon stop
- gsd-browser --session site2 daemon stop
- ```
- ### Performance Audit
- ```bash
- gsd-browser navigate https://example.com
- gsd-browser trace-start --name "perf-audit"
- # ... interact with the page ...
- gsd-browser trace-stop --name "perf-audit.json"
- gsd-browser har-export --filename "network.har"
- ```
- ### Prompt Injection Scanning
- ```bash
- gsd-browser navigate https://untrusted-page.com
- gsd-browser check-injection
- # Returns severity-rated findings for visible and hidden injection patterns
- ```
- ---
- ## Configuration
- ### Config Files (TOML)
- gsd-browser loads config with 5-layer merge precedence:
- 1. Compiled defaults
- 2. User config: `~/.gsd-browser/config.toml`
- 3. Project config: `./gsd-browser.toml`
- 4. Environment variables: `GSD_BROWSER_*`
- 5. CLI flags (highest priority)
- Example `gsd-browser.toml`:
- ```toml
- [browser]
- path = "/usr/bin/chromium"
- [daemon]
- port = 9222
- host = "127.0.0.1"
- [screenshot]
- quality = 90
- format = "png"
- full_page = false
- [settle]
- timeout_ms = 500
- poll_ms = 40
- quiet_window_ms = 100
- [logs]
- max_buffer_size = 1000
- [artifacts]
- dir = "./browser-artifacts"
- [timeline]
- max_entries = 500
- ```
- ### Environment Variables
- Supported config overrides use `GSD_BROWSER_<SECTION>_<FIELD>` naming:
- ```bash
- GSD_BROWSER_BROWSER_PATH=/usr/bin/chromium
- GSD_BROWSER_DAEMON_PORT=9223
- GSD_BROWSER_SCREENSHOT_QUALITY=90
- GSD_BROWSER_SETTLE_TIMEOUT_MS=1000
- GSD_BROWSER_VAULT_KEY=your-encryption-key
- ```
- ---
- ## Session Cleanup
- Always stop the daemon when done to avoid leaked Chrome processes:
- ```bash
- gsd-browser daemon stop
- ```
- For parallel sessions:
- ```bash
- gsd-browser --session agent1 daemon stop
- gsd-browser --session agent2 daemon stop
- ```
README.md · README · 219 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- # gsd-browser
- Native Rust browser automation CLI for Chrome/Chromium via CDP. `gsd-browser` keeps a persistent background daemon, auto-starts on first use, and exposes 92 top-level commands for navigation, interaction, authenticated live viewing, annotations, recording bundles, snapshots with versioned refs, assertions, structured extraction, network control, visual diffing, tracing, and stateful auth flows.
- Built for AI agents, CI pipelines, and developers who want deterministic browser control without adopting a full browser test framework.
- ## Install
- ### Recommended: installer (macOS / Linux)
- ```bash
- curl -fsSL https://install.gsd.build/browser | bash
- ```
- The installer downloads the correct `gsd-browser` binary for your platform. If Chrome or Chromium is already installed, it uses that. Otherwise it downloads Chromium automatically when Chrome for Testing is available for your platform.
- Run `gsd-browser update` to install the current release.
- ### Pre-built binaries
- Download from [GitHub Releases](https://github.com/gsd-build/gsd-browser/releases):
- | Platform | Asset |
- |----------|-------|
- | macOS (Apple Silicon) | `gsd-browser-darwin-arm64` |
- | macOS (Intel) | `gsd-browser-darwin-x64` |
- | Linux (ARM64) | `gsd-browser-linux-arm64` |
- | Linux (x64) | `gsd-browser-linux-x64` |
- ### Build from source
- ```bash
- git clone https://github.com/gsd-build/gsd-browser.git
- cd gsd-browser
- cargo install --path cli
- ```
- ### Package registries
- The public npm package (`@gsd-build/gsd-browser`) and crates.io package (`gsd-browser`) are not published yet. Use the installer, GitHub release assets, or a source build.
- ## Quick Start
- The daemon starts automatically on first use.
- ```bash
- # Navigate to a page
- gsd-browser navigate https://example.com
- # Snapshot interactive elements and assign refs like @v1:e1
- gsd-browser snapshot
- # On example.com the only interactive element is the "More information..." link
- gsd-browser click-ref @v1:e1
- # Wait for navigation and assert the result
- gsd-browser wait-for --condition network_idle
- gsd-browser assert --checks '[{"kind":"url_contains","text":"iana.org"}]'
- # Capture a PNG
- gsd-browser screenshot --output page.png --format png
- ```
- ## Interactive Workbench
- `gsd-browser view` starts an authenticated localhost workbench for the active session. The URL is bound to the session, viewer id, loopback origin, expiry, and viewer capabilities. Use `view --print-only` when another tool needs the URL.
- ```bash
- gsd-browser view
- gsd-browser view --print-only
- gsd-browser control-state
- gsd-browser takeover
- gsd-browser release-control
- gsd-browser sensitive-on
- gsd-browser sensitive-off
- ```
- The viewer streams the real Chrome page, forwards pointer, wheel, keyboard, text, and paste input while in Control mode, creates annotations in Annotate mode, and starts/stops local recording bundles in Record mode. Sensitive mode keeps local human control available while cloud frame capture and evidence surfaces use redaction policy.
- Annotations and recordings stay local to the daemon state directory:
- ```bash
- gsd-browser annotations
- gsd-browser annotation-get <id>
- gsd-browser annotation-clear <id>
- gsd-browser annotation-resolve <id>
- gsd-browser annotation-export --output annotations.json
- gsd-browser record-start --name checkout-bug
- gsd-browser record-stop
- gsd-browser recordings
- gsd-browser recording-get <id>
- gsd-browser recording-export <id> --output <path>
- gsd-browser recording-discard <id>
- gsd-browser recording-validate <id-or-path> --json
- ```
- ## Command Surface
- `gsd-browser` currently exposes 92 top-level commands:
- | Area | Commands |
- |------|----------|
- | Navigation | `navigate`, `back`, `forward`, `reload` |
- | Logs & JavaScript | `console`, `network`, `dialog`, `eval` |
- | Interaction | `click`, `type`, `press`, `hover`, `scroll`, `select-option`, `set-checked`, `drag`, `set-viewport`, `upload-file` |
- | Inspection | `accessibility-tree`, `find`, `page-source` |
- | Waits | `wait-for` |
- | Snapshots & refs | `snapshot`, `get-ref`, `click-ref`, `hover-ref`, `fill-ref` |
- | Assertions & batching | `assert`, `diff`, `batch` |
- | Pages & frames | `list-pages`, `switch-page`, `close-page`, `list-frames`, `select-frame` |
- | Forms & semantic actions | `analyze-form`, `fill-form`, `find-best`, `act` |
- | Live workbench | `goal`, `view`, `control-state`, `takeover`, `release-control`, `pause`, `resume`, `step`, `abort`, `sensitive-on`, `sensitive-off` |
- | Annotations | `annotations`, `annotation-get`, `annotation-clear`, `annotation-resolve`, `annotation-export`, `annotation-request` |
- | Recording bundles | `record-start`, `record-stop`, `record-pause`, `record-resume`, `recordings`, `recording-get`, `recording-export`, `recording-discard`, `recording-validate` |
- | Diagnostics | `timeline`, `session-summary`, `debug-bundle` |
- | Screenshots & document output | `screenshot`, `zoom-region`, `save-pdf` |
- | Visual regression | `visual-diff` |
- | Structured extraction | `extract` |
- | Network control | `mock-route`, `block-urls`, `clear-routes` |
- | Device & browser state | `emulate-device`, `save-state`, `restore-state` |
- | Auth vault | `vault-save`, `vault-login`, `vault-list` |
- | Recording & traces | `generate-test`, `har-export`, `trace-start`, `trace-stop` |
- | Safety, caching & daemon management | `action-cache`, `check-injection`, `daemon` |
- ## Highlights
- - Persistent daemon with automatic startup for fast repeated commands
- - Durable named sessions with explicit health reporting and no silent session replacement
- - Versioned refs from `snapshot` for deterministic interaction (`@v1:e1`, `@v2:e3`)
- - Explicit assertions with `assert` and multi-step automation with `batch`
- - Shared inspection semantics across `snapshot`, `find`, `wait-for`, `assert`, and ref-driven actions
- - Semantic `find-best` and `act` flows covering 15 built-in intents
- - Named sessions via `--session` for isolated parallel browser workers
- - Authenticated local viewer with human takeover, pause/step/abort, annotations, sensitive mode, and bounded recording bundles
- - Structured JSON output on every command via `--json`
- - Visual diffing, HAR export, PDF generation, and CDP tracing in the same tool
- - Saved browser state plus encrypted credential replay through the auth vault
- - Prompt injection scanning for agent-facing browsing workflows
- ## Configuration
- `gsd-browser` merges configuration in this order:
- 1. Built-in defaults
- 2. User config: `~/.gsd-browser/config.toml`
- 3. Project config: `./gsd-browser.toml`
- 4. Environment variables: `GSD_BROWSER_*`
- 5. CLI flags
- Example `gsd-browser.toml`:
- ```toml
- [browser]
- path = "/usr/bin/chromium"
- cdp_url = "http://localhost:9222" # attach to existing Chrome instead of launching
- headless = true
- [daemon]
- port = 9222
- host = "127.0.0.1"
- [screenshot]
- quality = 90
- format = "png"
- full_page = false
- [settle]
- timeout_ms = 500
- poll_ms = 40
- quiet_window_ms = 100
- [logs]
- max_buffer_size = 1000
- [artifacts]
- dir = "./browser-artifacts"
- [timeline]
- enabled = true
- max_entries = 500
- ```
- Supported environment variable overrides use `GSD_BROWSER_<SECTION>_<FIELD>` naming:
- ```bash
- export GSD_BROWSER_BROWSER_PATH=/usr/bin/chromium
- export GSD_BROWSER_BROWSER_CDP_URL=http://localhost:9222
- export GSD_BROWSER_BROWSER_HEADLESS=true
- export GSD_BROWSER_DAEMON_PORT=9333
- export GSD_BROWSER_SCREENSHOT_QUALITY=90
- export GSD_BROWSER_SETTLE_TIMEOUT_MS=1000
- export GSD_BROWSER_ARTIFACTS_DIR=./browser-artifacts
- export GSD_BROWSER_VAULT_KEY=your-encryption-key
- ```
- ## How It Works
- - The CLI parses commands and sends them to a local daemon over a loopback HTTP channel.
- - The daemon maintains the browser lifecycle, page/frame routing, network hooks, action timeline, and session manifest state.
- - `--session <name>` creates isolated daemon and browser instances for parallel workflows.
- ## For AI Agents
- - The daemon auto-starts. You almost never need `gsd-browser daemon start`.
- - `gsd-browser daemon health` reports the current session state and does not auto-start the daemon.
- - Use `--json` when you need structured output.
- - Prefer `snapshot` then `click-ref` or `fill-ref` for stable interaction, and re-snapshot after page changes.
- - Use `assert` and `batch` when you need deterministic pass/fail automation.
- - `find-best` and `act` cover 15 built-in semantic intents for common navigation, form, dialog, auth, and pagination actions.
- - Read [SKILL.md](./SKILL.md) for the full command reference and workflow patterns.
- ## License
- Licensed under either of:
- - [MIT License](LICENSE-MIT)
- - [Apache License, Version 2.0](LICENSE-APACHE)
- at your option.
install.sh · Bundled script · 578 lines · 1 finding marked
- #!/usr/bin/env bash
- set -euo pipefail
- # gsd-browser installer
- # Usage: curl -fsSL https://install.gsd.build/browser | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 5 on GitHub
- #
- # Environment variables (advanced):
- # GSD_BROWSER_VERSION - install a specific version (default: latest)
- # GSD_BROWSER_DIR - override install directory (default: $HOME/.gsd-browser)
- # GSD_BROWSER_INSTALL_MODE - install or update (default: install)
- # GSD_BROWSER_SKIP_CHROMIUM - skip Chrome/Chromium setup when set to 1
- # GSD_BROWSER_SKIP_SKILL - skip AI agent skill installation when set to 1
- VERSION="${GSD_BROWSER_VERSION:-latest}"
- REPO="gsd-build/gsd-browser"
- INSTALL_DIR="${GSD_BROWSER_DIR:-$HOME/.gsd-browser}"
- BIN_DIR="$INSTALL_DIR/bin"
- CHROMIUM_DIR="$INSTALL_DIR/chromium"
- INSTALL_MODE="${GSD_BROWSER_INSTALL_MODE:-install}"
- SKIP_CHROMIUM="${GSD_BROWSER_SKIP_CHROMIUM:-0}"
- SKIP_SKILL="${GSD_BROWSER_SKIP_SKILL:-0}"
- # Colors
- cyan="\033[36m"
- green="\033[32m"
- yellow="\033[33m"
- red="\033[31m"
- dim="\033[2m"
- bold="\033[1m"
- reset="\033[0m"
- banner() {
- echo ""
- printf "${cyan}${bold}"
- echo " ██████╗ ███████╗██████╗ ██████╗ ██████╗ ██████╗ ██╗ ██╗███████╗███████╗██████╗ "
- echo " ██╔════╝ ██╔════╝██╔══██╗ ██╔══██╗██╔══██╗██╔═══██╗██║ ██║██╔════╝██╔════╝██╔══██╗"
- echo " ██║ ███╗███████╗██║ ██║█████╗██████╔╝██████╔╝██║ ██║██║ █╗ ██║███████╗█████╗ ██████╔╝"
- echo " ██║ ██║╚════██║██║ ██║╚════╝██╔══██╗██╔══██╗██║ ██║██║███╗██║╚════██║██╔══╝ ██╔══██╗"
- echo " ╚██████╔╝███████║██████╔╝ ██████╔╝██║ ██║╚██████╔╝╚███╔███╔╝███████║███████╗██║ ██║"
- echo " ╚═════╝ ╚══════╝╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ ╚══════╝╚══════╝╚═╝ ╚═╝"
- printf "${reset}\n"
- printf " ${dim}Browser automation for AI agents${reset}\n\n"
- }
- info() { printf " ${cyan}>${reset} %s\n" "$1"; }
- ok() { printf " ${green}✓${reset} %s\n" "$1"; }
- warn() { printf " ${yellow}!${reset} %s\n" "$1"; }
- fail() { printf " ${red}✗${reset} %s\n" "$1"; exit 1; }
- parse_args() {
- for arg in "$@"; do
- case "$arg" in
- --update)
- INSTALL_MODE="update"
- SKIP_CHROMIUM=1
- SKIP_SKILL=1
- ;;
- --skip-chromium)
- SKIP_CHROMIUM=1
- ;;
- --skip-skill)
- SKIP_SKILL=1
- ;;
- *)
- fail "Unknown option: $arg"
- ;;
- esac
- done
- case "$INSTALL_MODE" in
- install|update) ;;
- *) fail "Invalid GSD_BROWSER_INSTALL_MODE: $INSTALL_MODE" ;;
- esac
- }
- detect_platform() {
- local os arch
- os="$(uname -s)"
- arch="$(uname -m)"
- case "$os" in
- Darwin) os="darwin" ;;
- Linux) os="linux" ;;
- *) fail "Unsupported OS: $os (Windows users: use WSL)" ;;
- esac
- case "$arch" in
- x86_64|amd64) arch="x64" ;;
- arm64|aarch64) arch="arm64" ;;
- *) fail "Unsupported architecture: $arch" ;;
- esac
- PLATFORM="${os}-${arch}"
- # Chrome for Testing platform names (different from ours)
- case "$PLATFORM" in
- darwin-arm64) CHROME_PLATFORM="mac-arm64" ;;
- darwin-x64) CHROME_PLATFORM="mac-x64" ;;
- linux-x64) CHROME_PLATFORM="linux64" ;;
- linux-arm64) CHROME_PLATFORM="" ;; # Not available
- *) CHROME_PLATFORM="" ;;
- esac
- }
- resolve_version() {
- if [ "$VERSION" = "latest" ]; then
- info "Fetching latest release..."
- VERSION=$(curl -fsSL "https://api.github.com/repos/$REPO/releases/latest" | grep '"tag_name"' | sed -E 's/.*"v?([^"]+)".*/\1/')
- if [ -z "$VERSION" ]; then
- fail "Could not determine latest version. Set GSD_BROWSER_VERSION manually."
- fi
- fi
- ok "Version: $VERSION"
- }
- download_binary() {
- local url filename
- filename="gsd-browser-${PLATFORM}"
- url="https://github.com/$REPO/releases/download/v${VERSION}/${filename}"
- info "Downloading gsd-browser for $PLATFORM..."
- mkdir -p "$BIN_DIR"
- local target="$BIN_DIR/gsd-browser"
- local tmp
- tmp="$(mktemp "$BIN_DIR/.gsd-browser.XXXXXX")"
- trap 'rm -f "$tmp"' EXIT
- if ! curl -fsSL -o "$tmp" "$url"; then
- rm -f "$tmp"
- fail "Download failed: $url"
- fi
- chmod +x "$tmp"
- mv -f "$tmp" "$target"
- chmod +x "$target"
- # On macOS, strip quarantine/provenance attributes added by curl, then verify
- # the Developer ID signature. Fall back to ad-hoc signing only if the binary
- # has no valid signature (manual builds, stripped signatures).
- if [ "$(uname -s)" = "Darwin" ]; then
- xattr -d com.apple.quarantine "$target" 2>/dev/null || true
- xattr -d com.apple.provenance "$target" 2>/dev/null || true
- if command -v codesign >/dev/null 2>&1; then
- if codesign --verify --strict "$target" 2>/dev/null; then
- if "$target" --version >/dev/null 2>&1; then
- ok "Binary signature verified (Developer ID)"
- else
- warn "Developer ID signature verifies but macOS refused to launch the binary"
- codesign --sign - --force "$target" 2>/dev/null && "$target" --version >/dev/null 2>&1 && {
- ok "Ad-hoc signed for macOS Gatekeeper"
- } || {
- warn "Ad-hoc signing failed — binary may be blocked by Gatekeeper"
- warn "Fix manually: codesign --sign - --force $target"
- }
- fi
- else
- codesign --sign - --force "$target" 2>/dev/null && {
- ok "Ad-hoc signed for macOS Gatekeeper"
- } || {
- warn "Ad-hoc signing failed — binary may be blocked by Gatekeeper"
- warn "Fix manually: codesign --sign - --force $target"
- }
- fi
- fi
- fi
- trap - EXIT
- ok "Binary installed: $target"
- }
- detect_existing_chrome() {
- # Check standard Chrome/Chromium locations — mirrors find_chrome() in common/src/chrome.rs
- local candidates=()
- case "$(uname -s)" in
- Darwin)
- candidates=(
- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
- )
- ;;
- Linux)
- candidates=(
- "/usr/bin/google-chrome"
- "/usr/bin/google-chrome-stable"
- "/usr/bin/chromium-browser"
- "/usr/bin/chromium"
- "/snap/bin/chromium"
- )
- ;;
- esac
- for path in "${candidates[@]}"; do
- if [ -x "$path" ]; then
- echo "$path"
- return 0
- fi
- done
- # Check PATH
- for name in google-chrome google-chrome-stable chromium-browser chromium; do
- if command -v "$name" >/dev/null 2>&1; then
- command -v "$name"
- return 0
- fi
- done
- return 1
- }
- download_chromium() {
- if [ "$SKIP_CHROMIUM" = "1" ]; then
- info "Skipping Chrome/Chromium setup"
- return
- fi
- if [ -z "$CHROME_PLATFORM" ]; then
- warn "Chromium not available for $PLATFORM via Chrome for Testing"
- warn "Install Chrome/Chromium manually and set GSD_BROWSER_BROWSER_PATH"
- return
- fi
- # Check if a system Chrome/Chromium is already available
- local system_chrome
- if system_chrome=$(detect_existing_chrome); then
- ok "Found Chrome at: $system_chrome (skipping download)"
- SKIP_CHROMIUM_CONFIG=1
- return
- fi
- # Check if we previously downloaded Chrome for Testing
- if [ -f "$CHROMIUM_DIR/version" ]; then
- local existing
- existing=$(cat "$CHROMIUM_DIR/version")
- info "Chromium $existing already installed"
- read -rp " Reinstall? [y/N] " yn < /dev/tty || yn="n"
- case "$yn" in
- [Yy]*) ;;
- *) ok "Keeping existing Chromium"; return ;;
- esac
- fi
- info "Fetching Chrome for Testing metadata..."
- local json chrome_url chrome_version
- json=$(curl -fsSL "https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json")
- chrome_version=$(echo "$json" | grep -o '"Stable"[^}]*"version":"[^"]*"' | head -1 | grep -o '"version":"[^"]*"' | cut -d'"' -f4)
- chrome_url=$(echo "$json" | python3 -c "
- import sys, json
- data = json.load(sys.stdin)
- for entry in data['channels']['Stable']['downloads']['chrome']:
- if entry['platform'] == '$CHROME_PLATFORM':
- print(entry['url'])
- break
- " 2>/dev/null || echo "")
- if [ -z "$chrome_url" ]; then
- warn "Could not find Chromium download for $CHROME_PLATFORM"
- return
- fi
- info "Downloading Chromium $chrome_version for $CHROME_PLATFORM..."
- mkdir -p "$CHROMIUM_DIR"
- local tmpzip="$CHROMIUM_DIR/chrome.zip"
- if ! curl -fsSL -o "$tmpzip" "$chrome_url"; then
- warn "Chromium download failed — you can install Chrome manually"
- rm -f "$tmpzip"
- return
- fi
- info "Extracting Chromium..."
- unzip -qo "$tmpzip" -d "$CHROMIUM_DIR"
- rm -f "$tmpzip"
- # Find the chrome binary inside the extracted directory
- local chrome_bin=""
- case "$CHROME_PLATFORM" in
- mac-arm64|mac-x64)
- chrome_bin=$(find "$CHROMIUM_DIR" -name "Google Chrome for Testing" -type f 2>/dev/null | head -1)
- if [ -z "$chrome_bin" ]; then
- chrome_bin=$(find "$CHROMIUM_DIR" -name "Chromium" -type f 2>/dev/null | head -1)
- fi
- ;;
- linux64)
- chrome_bin=$(find "$CHROMIUM_DIR" -name "chrome" -type f 2>/dev/null | head -1)
- ;;
- esac
- if [ -n "$chrome_bin" ]; then
- echo "$chrome_version" > "$CHROMIUM_DIR/version"
- echo "$chrome_bin" > "$CHROMIUM_DIR/binary_path"
- ok "Chromium $chrome_version installed"
- else
- warn "Chromium extracted but binary not found — check $CHROMIUM_DIR"
- fi
- }
- setup_path() {
- local target="/usr/local/bin/gsd-browser"
- local source="$BIN_DIR/gsd-browser"
- # Try symlink to /usr/local/bin
- if [ -w "/usr/local/bin" ] || [ -w "$(dirname /usr/local/bin)" ]; then
- ln -sf "$source" "$target" 2>/dev/null && {
- ok "Linked to $target"
- return
- }
- fi
- # Try with sudo
- if command -v sudo >/dev/null 2>&1; then
- info "Linking to /usr/local/bin (may need password)..."
- sudo ln -sf "$source" "$target" 2>/dev/null && {
- ok "Linked to $target"
- return
- }
- fi
- # Fallback: tell user to add to PATH
- warn "Could not link to /usr/local/bin"
- echo ""
- printf " Add this to your shell profile:\n"
- printf " ${bold}export PATH=\"$BIN_DIR:\$PATH\"${reset}\n"
- echo ""
- }
- write_config() {
- # If system Chrome was detected, no config needed — find_chrome() will discover it
- if [ "${SKIP_CHROMIUM_CONFIG:-}" = "1" ]; then
- return
- fi
- # If we downloaded Chromium, write a config pointing to it
- if [ -f "$CHROMIUM_DIR/binary_path" ]; then
- local chrome_path
- chrome_path=$(cat "$CHROMIUM_DIR/binary_path")
- local config_dir="$HOME/.gsd-browser"
- mkdir -p "$config_dir"
- cat > "$config_dir/config.toml" << TOML
- [browser]
- path = "$chrome_path"
- TOML
- ok "Config written: $config_dir/config.toml"
- fi
- }
- verify() {
- info "Verifying installation..."
- local bin=""
- if ! command -v gsd-browser >/dev/null 2>&1; then
- # Try the direct path
- if [ -x "$BIN_DIR/gsd-browser" ]; then
- bin="$BIN_DIR/gsd-browser"
- else
- warn "gsd-browser not in PATH yet — restart your shell or run: export PATH=\"$BIN_DIR:\$PATH\""
- return
- fi
- else
- bin="gsd-browser"
- fi
- "$bin" daemon stop >/dev/null 2>&1 || true
- if "$bin" daemon start >/dev/null 2>&1; then
- local health_output
- health_output=$("$bin" daemon health 2>&1 || true)
- if printf '%s\n' "$health_output" | grep -q '^Daemon: healthy$'; then
- if [ "$bin" = "$BIN_DIR/gsd-browser" ]; then
- ok "Daemon healthy (using direct path)"
- else
- ok "Daemon healthy"
- fi
- "$bin" daemon stop >/dev/null 2>&1 || true
- return
- fi
- fi
- "$bin" daemon stop >/dev/null 2>&1 || true
- warn "Daemon test failed — this is normal if Chrome is not in the default path"
- warn "Set browser.path in ~/.gsd-browser/config.toml"
- }
- SKILL_REPO_BASE="https://raw.githubusercontent.com/$REPO/main/gsd-browser-skill"
- SKILL_FILES=(
- "SKILL.md"
- "references/command-reference.md"
- "references/snapshot-and-refs.md"
- "references/semantic-intents.md"
- "references/configuration.md"
- "references/error-recovery.md"
- "workflows/scrape-and-extract.md"
- "workflows/setup-and-configure.md"
- "workflows/live-viewer-and-narration.md"
- "workflows/navigate-and-interact.md"
- "workflows/test-and-assert.md"
- "workflows/debug-and-diagnose.md"
- )
- install_skill_to() {
- local dest="$1"
- mkdir -p "$dest" "$dest/references" "$dest/workflows"
- local failed=0
- for file in "${SKILL_FILES[@]}"; do
- if ! curl -fsSL -o "$dest/$file" "$SKILL_REPO_BASE/$file" 2>/dev/null; then
- failed=1
- break
- fi
- done
- if [ "$failed" -eq 1 ]; then
- warn "Failed to download skill files — check network or repo access"
- rm -rf "$dest"
- return 1
- fi
- ok "Skill installed: $dest"
- return 0
- }
- install_skill() {
- if [ "$SKIP_SKILL" = "1" ]; then
- info "Skipping skill installation"
- return
- fi
- echo ""
- printf " ${cyan}${bold}AI Agent Skill Installation${reset}\n"
- printf " ${dim}Install the gsd-browser skill so your AI coding agent knows how to use it${reset}\n"
- echo ""
- # Detect available AI CLIs
- local available=()
- local labels=()
- if command -v claude >/dev/null 2>&1; then
- available+=("claude")
- labels+=("Claude Code")
- fi
- if command -v codex >/dev/null 2>&1; then
- available+=("codex")
- labels+=("OpenAI Codex CLI")
- fi
- if command -v gemini >/dev/null 2>&1; then
- available+=("gemini")
- labels+=("Google Gemini CLI")
- fi
- if [ ${#available[@]} -eq 0 ]; then
- info "No AI coding agents detected (claude, codex, gemini)"
- info "Install one, then re-run: gsd-browser skill install"
- return
- fi
- printf " Detected AI agents:\n"
- local idx=1
- for label in "${labels[@]}"; do
- printf " ${bold}%d)${reset} %s\n" "$idx" "$label"
- idx=$((idx + 1))
- done
- printf " ${bold}a)${reset} All detected agents\n"
- printf " ${bold}s)${reset} Skip\n"
- echo ""
- local choice
- read -rp " Install skill for which agent(s)? [a]: " choice < /dev/tty || choice="a"
- choice="${choice:-a}"
- if [ "$choice" = "s" ] || [ "$choice" = "S" ]; then
- info "Skipping skill installation"
- return
- fi
- # Build list of selected tools
- local selected=()
- if [ "$choice" = "a" ] || [ "$choice" = "A" ]; then
- selected=("${available[@]}")
- else
- # Parse comma-separated or single number
- IFS=',' read -ra nums <<< "$choice"
- for num in "${nums[@]}"; do
- num=$(echo "$num" | tr -d ' ')
- if [[ "$num" =~ ^[0-9]+$ ]] && [ "$num" -ge 1 ] && [ "$num" -le ${#available[@]} ]; then
- selected+=("${available[$((num - 1))]}")
- fi
- done
- fi
- if [ ${#selected[@]} -eq 0 ]; then
- warn "No valid selection — skipping skill installation"
- return
- fi
- # Ask scope
- echo ""
- printf " Install scope:\n"
- printf " ${bold}g)${reset} Global (available in all projects)\n"
- printf " ${bold}l)${reset} Local (current directory only)\n"
- echo ""
- local scope
- read -rp " Scope? [g]: " scope < /dev/tty || scope="g"
- scope="${scope:-g}"
- for tool in "${selected[@]}"; do
- local dest=""
- case "$tool" in
- claude)
- if [ "$scope" = "l" ] || [ "$scope" = "L" ]; then
- dest=".claude/skills/gsd-browser"
- else
- dest="$HOME/.claude/skills/gsd-browser"
- fi
- ;;
- codex)
- if [ "$scope" = "l" ] || [ "$scope" = "L" ]; then
- dest=".codex/skills/gsd-browser"
- else
- dest="$HOME/.codex/skills/gsd-browser"
- fi
- ;;
- gemini)
- if [ "$scope" = "l" ] || [ "$scope" = "L" ]; then
- dest=".gemini/skills/gsd-browser"
- else
- dest="$HOME/.gemini/skills/gsd-browser"
- fi
- ;;
- esac
- if [ -n "$dest" ]; then
- info "Installing skill for $tool → $dest"
- install_skill_to "$dest"
- fi
- done
- }
- main() {
- parse_args "$@"
- if [ "$INSTALL_MODE" = "update" ]; then
- echo ""
- printf " ${cyan}${bold}Updating gsd-browser${reset}\n\n"
- else
- banner
- fi
- detect_platform
- ok "Platform: $PLATFORM"
- resolve_version
- download_binary
- if [ "$INSTALL_MODE" = "update" ]; then
- verify
- echo ""
- printf " ${green}${bold}Update complete!${reset}\n"
- echo ""
- return
- fi
- download_chromium
- setup_path
- write_config
- verify
- install_skill
- echo ""
- printf " ${green}${bold}Installation complete!${reset}\n"
- echo ""
- printf " ${dim}Quick start:${reset}\n"
- printf " gsd-browser navigate https://example.com\n"
- printf " gsd-browser screenshot --output page.png\n"
- printf " gsd-browser snapshot\n"
- echo ""
- }
- main "$@"
npm/scripts/postinstall.js · Bundled script · 126 lines · 1 finding marked
- #!/usr/bin/env node
- "use strict";
- const fs = require("fs");
- const path = require("path");
- const https = require("https");
- const { execSync } = require("child_process");
- const REPO = "gsd-build/gsd-browser";
- const PLATFORM_MAP = {
- "darwin-arm64": "gsd-browser-darwin-arm64",
- "darwin-x64": "gsd-browser-darwin-x64",
- "linux-arm64": "gsd-browser-linux-arm64",
- "linux-x64": "gsd-browser-linux-x64",
- };
- function fetchJSON(url) {
- return new Promise((resolve, reject) => {
- https.get(url, { headers: { "User-Agent": "gsd-browser-npm" } }, (res) => {
- if (res.statusCode === 302 || res.statusCode === 301) {
- return fetchJSON(res.headers.location).then(resolve, reject);
- }
- if (res.statusCode !== 200) {
- return reject(new Error(`HTTP ${res.statusCode} from ${url}`));
- }
- let data = "";
- res.on("data", (chunk) => (data += chunk));
- res.on("end", () => {
- try { resolve(JSON.parse(data)); }
- catch (e) { reject(e); }
- });
- }).on("error", reject);
- });
- }
- function downloadFile(url, dest) {
- return new Promise((resolve, reject) => {
- https.get(url, { headers: { "User-Agent": "gsd-browser-npm" } }, (res) => {
- if (res.statusCode === 302 || res.statusCode === 301) {
- return downloadFile(res.headers.location, dest).then(resolve, reject);
- }
- if (res.statusCode !== 200) {
- return reject(new Error(`HTTP ${res.statusCode} downloading ${url}`));
- }
- const file = fs.createWriteStream(dest);
- res.pipe(file);
- file.on("finish", () => { file.close(); resolve(); });
- }).on("error", reject);
- });
- }
- async function main() {
- const platform = process.platform;
- const arch = process.arch;
- const key = `${platform}-${arch}`;
- const binaryName = PLATFORM_MAP[key];
- if (!binaryName) {
- console.error(
- `gsd-browser: unsupported platform ${key}.\n` +
- `Supported: ${Object.keys(PLATFORM_MAP).join(", ")}`
- );
- process.exit(1);
- }
- const binDir = path.join(__dirname, "..", "bin");
- fs.mkdirSync(binDir, { recursive: true });
- const isWindows = platform === "win32";
- const targetName = isWindows ? "gsd-browser.exe" : "gsd-browser";
- const targetPath = path.join(binDir, targetName);
- // Check if binary already exists (e.g., bundled in package)
- if (fs.existsSync(targetPath)) {
- console.log(`gsd-browser: binary already present at ${targetPath}`);
- return;
- }
- // Determine version from package.json
- const pkg = require("../package.json");
- let version = pkg.version;
- // Download from GitHub releases
- let url = `https://github.com/${REPO}/releases/download/v${version}/${binaryName}`;
- // If version is 0.1.0 or similar pre-release, try latest
- try {
- console.log(`gsd-browser: downloading ${binaryName} v${version}...`);
- await downloadFile(url, targetPath);
- } catch (e) {
- // Fall back to latest release
- console.log(`gsd-browser: v${version} not found, trying latest release...`);
- try {
- const release = await fetchJSON(`https://api.github.com/repos/${REPO}/releases/latest`);
- const asset = release.assets.find((a) => a.name === binaryName);
- if (!asset) {
- throw new Error(`No asset ${binaryName} in latest release`);
- }
- await downloadFile(asset.browser_download_url, targetPath);
- version = release.tag_name;
- } catch (e2) {
- console.error(
- `gsd-browser: failed to download binary.\n` +
- ` ${e2.message}\n` +
- ` You can build from a repo checkout:\n` +
- ` git clone https://github.com/${REPO}.git\n` +
- ` cd gsd-browser\n` +
- ` cargo install --path cli\n` +
- ` Or use the installer: curl -fsSL https://install.gsd.build/browser | bash`
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 110 on GitHub
- );
- process.exit(1);
- }
- }
- if (!isWindows) {
- fs.chmodSync(targetPath, 0o755);
- }
- console.log(`gsd-browser: installed ${binaryName} (${version}) to ${targetPath}`);
- }
- main().catch((e) => {
- console.error(`gsd-browser: postinstall failed: ${e.message}`);
- process.exit(1);
- });
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.