diff --git a/.github/workflows/publish-opencode.yml b/.github/workflows/publish-opencode.yml new file mode 100644 index 0000000..ca23a74 --- /dev/null +++ b/.github/workflows/publish-opencode.yml @@ -0,0 +1,75 @@ +name: Publish OpenCode Plugin + +on: + push: + branches: + - main + paths: + - "opencode/package.json" + workflow_dispatch: + inputs: + force: + description: "Force publish even if version exists (will fail if already published)" + required: false + default: "false" + type: boolean + +permissions: + contents: read + id-token: write + +jobs: + publish: + runs-on: ubuntu-latest + defaults: + run: + working-directory: opencode + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + registry-url: https://registry.npmjs.org + + - name: Get package info + id: pkg + run: | + NAME=$(node -pe "require('./package.json').name") + VERSION=$(node -pe "require('./package.json').version") + echo "name=$NAME" >> "$GITHUB_OUTPUT" + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + echo "Package: $NAME@$VERSION" + + - name: Check if version already published + id: check + run: | + if npm view "${{ steps.pkg.outputs.name }}@${{ steps.pkg.outputs.version }}" version 2>/dev/null; then + echo "exists=true" >> "$GITHUB_OUTPUT" + echo "Version ${{ steps.pkg.outputs.version }} already exists on npm" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + echo "Version ${{ steps.pkg.outputs.version }} not yet published" + fi + + - name: Install dependencies + if: steps.check.outputs.exists == 'false' || inputs.force == 'true' + run: npm ci --ignore-scripts || npm install --ignore-scripts + + - name: Type check + if: steps.check.outputs.exists == 'false' || inputs.force == 'true' + run: npm run check + + # Uses npm OIDC trusted publishing - no NPM_TOKEN secret required. + # First-time setup: someone with @browserbasehq npm org access must + # configure this package to trust GitHub Actions from this repo/workflow. + # See: https://docs.npmjs.com/generating-provenance-statements + - name: Publish to npm + if: steps.check.outputs.exists == 'false' || inputs.force == 'true' + run: npm publish --access public --provenance + + - name: Skip publish (version exists) + if: steps.check.outputs.exists == 'true' && inputs.force != 'true' + run: | + echo "::notice::Skipping publish - ${{ steps.pkg.outputs.name }}@${{ steps.pkg.outputs.version }} already exists on npm" diff --git a/README.md b/README.md index f511c70..286c181 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # browse plugin marketplace -Install the [`browse`](https://github.com/browserbase/stagehand/tree/main/packages/cli) CLI as a native plugin in Claude Code, Cursor, Codex, Grok, Muse Code, Gemini CLI, and Google Antigravity. +Install the [`browse`](https://github.com/browserbase/stagehand/tree/main/packages/cli) CLI as a native plugin in Claude Code, Cursor, Codex, Grok, Muse Code, Gemini CLI, Google Antigravity, and OpenCode. This repo has no application code. It's a set of static JSON manifests that let each agent marketplace install and SHA-pin the `browse` plugin, plus the skill that teaches the agent to drive `browse` from the shell. @@ -16,6 +16,7 @@ This repo has no application code. It's a set of static JSON manifests that let | `.muse-plugin/plugin.json` | Muse Code native plugin (uses the `.agents` marketplace above) | | `gemini-extension.json` | Gemini CLI extension (`GEMINI.md` context file) | | `.antigravity-plugin/plugin.json` | Google Antigravity marketplace | +| `opencode/` | OpenCode npm plugin (`@browserbasehq/opencode`) | See [`docs/add-a-plugin.md`](docs/add-a-plugin.md) for the full repo layout and how to update the plugin. @@ -27,6 +28,7 @@ See [`docs/add-a-plugin.md`](docs/add-a-plugin.md) for the full repo layout and - **Muse Code**: install the native plugin from a local checkout or the marketplace. See [Muse Code setup](docs/muse-code.md). - **Gemini CLI**: install this repo as an extension (`gemini-extension.json` + `GEMINI.md`). - **Antigravity**: install with `agy plugin install https://github.com/browserbase/browse-plugin`. +- **OpenCode**: `opencode plugin add @browserbasehq/opencode` or add `"@browserbasehq/opencode"` to `plugins` in your `opencode.jsonc`. Then install the CLI: `npm install -g browse`. Then just ask your agent: diff --git a/docs/add-a-plugin.md b/docs/add-a-plugin.md index 36568de..57b0057 100644 --- a/docs/add-a-plugin.md +++ b/docs/add-a-plugin.md @@ -23,6 +23,14 @@ If Browserbase ever needs a second distinct plugin, it belongs in its own dedica ├── assets/logo.svg ├── assets/logo-antigravity.svg # Antigravity logo with transparent padding ├── skills/browse/SKILL.md # YAML frontmatter: name + description +├── opencode/ # OpenCode npm plugin package +│ ├── package.json # npm manifest for @browserbasehq/opencode +│ ├── index.ts # entrypoint (exports v1 + v2) +│ ├── v1.ts # OpenCode 1 plugin hooks +│ ├── v2.ts # OpenCode 2 plugin setup +│ ├── skills.ts # bundled skills loader +│ ├── skills/browse/SKILL.md # copy of the shared skill +│ └── README.md # OpenCode-specific install docs └── scripts/ ├── validate-template.mjs # run by CI and locally, see "Validate" below ├── gemini-sync.mjs # shared logic: derive GEMINI.md's expected content from SKILL.md @@ -68,3 +76,60 @@ Fix all reported errors before committing. This also runs in CI on every pull re - A marketplace `source`/`path` pointing at anything other than `"."` — this repo has no nested plugin folder anymore. - Editing `skills/browse/SKILL.md` without running `node scripts/sync-gemini.mjs` afterward — CI fails if `GEMINI.md` drifts out of sync. - Bumping `plugin.json`'s `version` without running `node scripts/sync-version.mjs` afterward — CI fails if the other manifests drift out of sync. + +## OpenCode plugin + +Unlike the other agent marketplaces that use static JSON manifests, OpenCode supports plugins distributed as npm packages (among other methods like local files). The `opencode/` directory is a publishable npm package (`@browserbasehq/opencode`) that: + +- Supports both OpenCode 1 (`plugin` config) and OpenCode 2 (`plugins` config) from the same package +- Bundles the browse skill (a copy of `skills/browse/SKILL.md`) +- Injects `BROWSERBASE_API_KEY` and `BROWSERBASE_PROJECT_ID` into shell commands when present + +### CI publishing + +The `.github/workflows/publish-opencode.yml` workflow publishes the package to npm automatically when `opencode/package.json`'s version changes on push to main. It uses npm OIDC trusted publishing (no `NPM_TOKEN` secret required). + +#### First-time setup (one-time, requires @browserbasehq npm org access) + +Before CI can publish, someone with access to the `@browserbasehq` npm organization must: + +1. **Create the package on npm** (if it doesn't exist): + ```bash + cd opencode && npm publish --access public + ``` + Or just let the first CI run create it (it will fail, but the package name will be reserved). + +2. **Configure trusted publishing** on npmjs.com: + - Go to [npmjs.com/package/@browserbasehq/opencode](https://www.npmjs.com/package/@browserbasehq/opencode) → Settings → Publishing access + - Add a new trusted publisher: + - **Repository**: `browserbase/browse-plugin` + - **Workflow**: `publish-opencode.yml` + - **Environment**: (leave blank for default) + +After this one-time setup, CI will publish automatically on version bumps. + +### Updating the OpenCode plugin + +1. Update `opencode/skills/browse/SKILL.md` when the shared skill changes (currently a manual copy) +2. Bump the version in `opencode/package.json` +3. Merge to main — CI publishes automatically once trusted publishing is configured + +For manual publishing (before trusted publishing is set up): +```bash +cd opencode && npm publish --access public +``` + +### Installing for users + +```bash +opencode plugin add @browserbasehq/opencode +npm install -g browse +``` + +Or in `opencode.jsonc`: + +```jsonc +{ + "plugins": ["@browserbasehq/opencode"] +} +``` diff --git a/opencode/README.md b/opencode/README.md new file mode 100644 index 0000000..91d5287 --- /dev/null +++ b/opencode/README.md @@ -0,0 +1,108 @@ +# @browserbasehq/opencode + +[OpenCode](https://opencode.ai) plugin for [Browserbase](https://browserbase.com) browser automation. It gives your agent the [browse CLI](https://github.com/browserbase/stagehand/tree/main/packages/cli) for navigating pages, extracting content, taking screenshots, and interacting with real web pages. + +## Installation + +The plugin supports OpenCode 2 and OpenCode 1 from the same package. + +### OpenCode 2 + +```bash +opencode plugin add @browserbasehq/opencode +``` + +Or add it to `opencode.jsonc` yourself: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugins": ["@browserbasehq/opencode"] +} +``` + +### OpenCode 1 + +Add it to `opencode.json`: + +```json +{ + "$schema": "https://opencode.ai/config.json", + "plugin": ["@browserbasehq/opencode"] +} +``` + +OpenCode installs the package on the next start. + +### Install the browse CLI + +The plugin bundles the browse skill, but you need the CLI installed globally: + +```bash +npm install -g browse +``` + +Verify the installation: + +```bash +which browse && browse --help +``` + +## Authentication + +### Local browsing (no key required) + +For local browser sessions, no API key is needed. The browse CLI uses Chrome or Chromium on your machine: + +```bash +browse open https://example.com --local +browse snapshot +browse stop +``` + +### Browserbase cloud + +For remote stealth sessions, proxies, and CAPTCHA solving, set your API key: + +```bash +export BROWSERBASE_API_KEY=your-api-key +``` + +Get a key at [browserbase.com/settings](https://browserbase.com/settings). + +Optionally set a project ID: + +```bash +export BROWSERBASE_PROJECT_ID=your-project-id +``` + +The plugin passes these environment variables to shell commands automatically, so the browse CLI is authenticated without manual configuration in each session. + +## Skills + +The plugin bundles the browse CLI skill, which teaches your agent: + +- Opening and navigating web pages +- Taking accessibility snapshots (structured page state) +- Taking screenshots +- Clicking, typing, and interacting with elements +- Managing browser sessions and tabs +- Using Browserbase cloud APIs +- Working with contexts, extensions, and functions + +Just ask your agent: + +- *"Go to Hacker News and get the top 5 stories."* +- *"Fill out the signup form on example.com."* +- *"Take a screenshot of localhost:3000."* + +## Links + +- [browse CLI documentation](https://github.com/browserbase/stagehand/tree/main/packages/cli) +- [Browserbase documentation](https://docs.browserbase.com) +- [OpenCode plugin docs](https://opencode.ai/v2/docs/plugins) +- [browse-plugin repository](https://github.com/browserbase/browse-plugin) + +## License + +MIT diff --git a/opencode/index.ts b/opencode/index.ts new file mode 100644 index 0000000..b77adfb --- /dev/null +++ b/opencode/index.ts @@ -0,0 +1,5 @@ +import { server } from "./v1.ts"; +import { v2 } from "./v2.ts"; + +// One entrypoint for both hosts: OpenCode 1 calls `server()`, OpenCode 2 reads `id` and `setup()`. +export default { ...v2, server }; diff --git a/opencode/package.json b/opencode/package.json new file mode 100644 index 0000000..54f6e26 --- /dev/null +++ b/opencode/package.json @@ -0,0 +1,57 @@ +{ + "name": "@browserbasehq/opencode", + "version": "0.4.0", + "description": "Browserbase browse plugin for OpenCode: browser automation, navigation, extraction, screenshots, and interaction via the browse CLI", + "type": "module", + "main": "index.ts", + "files": [ + "index.ts", + "v1.ts", + "v2.ts", + "skills.ts", + "skills" + ], + "keywords": [ + "opencode", + "opencode-plugin", + "browserbase", + "browser", + "automation", + "stagehand", + "browse", + "web-scraping", + "screenshot", + "llm", + "ai" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/browserbase/browse-plugin.git", + "directory": "opencode" + }, + "homepage": "https://browserbase.com", + "author": { + "name": "Browserbase", + "email": "support@browserbase.com", + "url": "https://browserbase.com" + }, + "scripts": { + "check": "tsc --noEmit" + }, + "dependencies": { + "gray-matter": "^4.0.3" + }, + "devDependencies": { + "@opencode-ai/plugin": "^1.19.5", + "@opencode/plugin": "^2.2.5", + "@types/node": "^22.0.0", + "typescript": "^5.0.0" + }, + "exports": { + ".": "./index.ts" + }, + "publishConfig": { + "access": "public" + } +} diff --git a/opencode/skills.ts b/opencode/skills.ts new file mode 100644 index 0000000..6368765 --- /dev/null +++ b/opencode/skills.ts @@ -0,0 +1,61 @@ +import { readdir, readFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import matter from "gray-matter"; + +export const skillsDir = join(dirname(fileURLToPath(import.meta.url)), "skills"); + +export type BundledSkill = { + id: string; + name: string; + description?: string; + path: string; + content: string; +}; + +/** The bundled skills, for OpenCode 2, which takes skills from plugins as entries rather than directories. */ +export async function bundledSkills(): Promise { + const entries = await readdir(skillsDir, { withFileTypes: true }); + return Promise.all( + entries + .filter((entry) => entry.isDirectory()) + .map(async (entry) => { + const skillPath = join(skillsDir, entry.name, "SKILL.md"); + const raw = await readFile(skillPath, "utf8"); + const { data, content } = matter(raw); + return { + id: entry.name, + name: (data.name as string) ?? entry.name, + ...(data.description && { description: data.description as string }), + path: skillPath, + content, + }; + }) + ); +} + +/** The CLI install instructions for the system prompt. */ +export async function installInstructions() { + return `## Browse CLI Setup + +Install the browse CLI globally to enable browser automation: + +\`\`\`bash +npm install -g browse +\`\`\` + +Verify the installation: + +\`\`\`bash +which browse && browse --help +\`\`\` + +For remote Browserbase sessions, set your API key: + +\`\`\`bash +export BROWSERBASE_API_KEY=your-api-key +\`\`\` + +Get an API key at https://browserbase.com/settings. Local mode uses Chrome/Chromium on your machine and needs no key. +`; +} diff --git a/opencode/skills/browse/SKILL.md b/opencode/skills/browse/SKILL.md new file mode 100644 index 0000000..13b856f --- /dev/null +++ b/opencode/skills/browse/SKILL.md @@ -0,0 +1,372 @@ +--- +name: browse +description: Use the browse CLI for Browserbase browser automation, Browserbase cloud APIs, Browserbase Functions, templates, web fetch/search, diagnostics, and Browse.sh skill discovery/installation. Use when the user asks to navigate pages, inspect browser state, run local or remote browser sessions, manage Browserbase resources, call Browserbase Functions, browse or scaffold Browserbase templates, fetch or search web content, diagnose browse setup, find or install a skill for a website task, discover site-specific Browse.sh skills, or install/refresh this browse skill. +compatibility: "Requires the browse CLI (`npm install -g browse`). Remote Browserbase sessions and cloud API commands require `BROWSERBASE_API_KEY`. Local mode uses Chrome/Chromium on the machine." +license: MIT +allowed-tools: Bash +metadata: + openclaw: + requires: + bins: + - browse + install: + - kind: node + package: browse + bins: [browse] + homepage: https://github.com/browserbase/stagehand/tree/main/packages/cli +--- + +# Browse CLI + +Use `browse` as the primary Browserbase command-line interface. + +It can: + +- drive a local or Browserbase-hosted browser session +- inspect pages through accessibility snapshots, screenshots, DOM/text reads, and network capture +- interact with pages by refs, selectors, XPath, keyboard, mouse, files, and viewport controls +- manage Browserbase projects, sessions, contexts, extensions, fetch, and search APIs +- develop, publish, and invoke Browserbase Functions +- browse and scaffold Browserbase templates +- diagnose local or remote browser setup issues +- discover and install Browse.sh catalog skills +- install or refresh this Browse CLI skill + +## Setup Check + +Verify the CLI exists before relying on it: + +```bash +which browse || npm install -g browse +browse --help +``` + +Install or refresh this skill with: + +```bash +browse skills install +``` + +Use `browse --help` for exact flags before running unfamiliar commands. + +## Browser Target Selection + +Browser driver commands auto-start the browse daemon when needed. Choose the browser target per command with flags: + +```bash +browse open https://example.com --local +browse open https://example.com --local --headed +browse open https://example.com --remote +browse open https://example.com --remote --verified --proxies +browse open https://example.com --auto-connect +browse open https://example.com --cdp 9222 +browse open https://example.com --cdp ws://127.0.0.1:9222/devtools/browser/ +``` + +Use local mode for development, localhost, trusted sites, and fast iteration. Use `--auto-connect` only when the user explicitly wants to attach to an already-running debuggable Chrome session with existing cookies or login state; use `--local` when no debuggable Chrome is available. Use remote mode when Browserbase credentials are available and the site needs hosted browser infrastructure, Verified browser mode, CAPTCHA solving, proxies, or session persistence. + +`--local` requires Chrome or Chromium already installed on the machine. In containers, CI, and sandboxes with no browser installed, use `--remote` instead of `--local`. If `--local` fails with "No Chrome or Chromium found" and `BROWSERBASE_API_KEY` is set, switch to `--remote` — do not retry `--local`. + +For a Verified and/or proxied remote session, add `--verified` and/or `--proxies` to `--remote` — a single command that keeps the Browserbase session identity, so `browse status` and `browse doctor` report the session ID and live-view URL. `--verified` requires a Browserbase Scale plan. These flags only apply to `--remote` and are sticky for the session's lifetime, like `--headed`. Reach for `browse cloud sessions create` + `--cdp` only when you need session options `open` doesn't expose (region, keep-alive, contexts). + +Choose headed/headless and local/remote mode when starting a session. A running session keeps its mode: passing a conflicting flag such as `--headed` to an already-running headless session fails until you run `browse stop --session ` or target a different session. + +Use named sessions for any non-trivial work, especially when multiple agents or parallel tasks may run at once. Every browser command accepts `--session ` (or `-s `); the `BROWSE_SESSION` env var sets the default, and commands without either share the `default` session. + +If `BROWSE_SESSION` is already set in the environment, every command already targets that session — do not pass `--session` or invent a new name. An explicit `--session ` always overrides `BROWSE_SESSION` for that command, so only pass it to deliberately target a different session. + +```bash +browse open https://example.com --session research --local +browse snapshot --session research +``` + +Remote browser and cloud API commands require: + +```bash +export BROWSERBASE_API_KEY=... +``` + +## Browser Automation Workflow + +Start by opening the page, then inspect state, act, and verify. + +```bash +browse open https://example.com --session research --local +browse snapshot --session research +browse click @0-5 --session research +browse type "hello" --session research +browse snapshot --session research +browse stop --session research +``` + +Prefer `browse snapshot` over screenshots for most browser work. It is structured, fast, and returns refs like `@0-5` for reliable element interaction. Use screenshots when visual layout, images, or pixel-level state matter. + +Refs are refreshed on every snapshot. After clicks, form submits, navigation, or UI re-renders, take a new snapshot before using another ref. + +## Parallel Browser Work + +Use a different `--session` value for each independent browser task. Sessions isolate tabs, cookies, refs, and daemon state; parallel tasks that omit `--session` share the `default` session and overwrite each other's active page. + +```bash +browse open https://example.com/search-a --session search-a --local +browse open https://example.com/search-b --session search-b --local +browse snapshot --session search-a +browse snapshot --session search-b +``` + +When a task is complete, stop only that task's session: + +```bash +browse stop --session search-a +``` + +## Core Browser Commands + +Navigation: + +```bash +browse open +browse reload +browse back +browse forward +browse wait load +browse wait selector "#result" +``` + +Page state: + +```bash +browse snapshot # formatted tree only +browse snapshot --full # also include ref maps (xpathMap, urlMap) +browse get url +browse get title +browse get text body +browse get html "#main" +browse get value "#email" +browse get markdown body # page/element content as markdown +browse eval "document.title" # run JavaScript in the active page +browse screenshot # saves screenshot-.png, prints { "saved": "" } +browse screenshot --path page.png # choose the output path +browse screenshot --base64 # legacy: print base64 JSON to stdout (avoid in agent loops) +``` + +Interaction: + +```bash +browse click @0-5 +browse fill @0-8 "search query" +browse type "text for the focused element" +browse press Enter +browse select "select[name=country]" "United States" +browse upload @0-12 ./file.pdf +browse highlight @0-5 +browse is visible "#modal" +``` + +Mouse and viewport: + +```bash +browse mouse click 240 320 +browse mouse hover 240 320 +browse mouse drag 80 80 310 100 +browse mouse scroll 500 300 0 600 +browse viewport 1280 720 +browse cursor # show a visible cursor overlay +``` + +Tabs, network, and CDP: + +```bash +browse tab list +browse tab new https://example.com +browse tab switch +browse tab close # refuses to close the last tab +browse network on +browse network off +browse network path +browse network clear +browse cdp 9222 --pretty +``` + +Session management: + +```bash +browse doctor +browse doctor --json +browse status +browse stop +browse stop --force +``` + +Use `browse doctor` before debugging a broken browser session. Use `browse doctor --json` when another agent or CI needs structured diagnostics. + +If a page command reports that no active page is available, inspect and recover the named session: + +```bash +browse status --session research +browse tab list --session research +browse tab new https://example.com --session research +browse open https://example.com --session research +``` + +## Cloud APIs + +Use `browse cloud` for Browserbase platform APIs: + +```bash +browse cloud projects list +browse cloud projects get +browse cloud projects usage +browse cloud sessions create +browse cloud sessions create --proxies --verified +browse cloud sessions list +browse cloud sessions get +browse cloud sessions update +browse cloud sessions debug +browse cloud sessions logs +browse cloud sessions downloads get +browse cloud sessions uploads create ./file.pdf +browse cloud contexts create --name github +browse cloud contexts add github +browse cloud contexts list +browse cloud contexts get +browse cloud contexts update +browse cloud contexts delete +browse cloud extensions upload ./extension.zip +browse cloud extensions get +browse cloud extensions delete +browse cloud fetch https://example.com +browse cloud search "browser automation" +``` + +For remote sessions with context persistence: + +```bash +browse cloud sessions create --context-id --persist +``` + +Contexts persist cookies and local storage (logins) across sessions. Name a +context once with `--name` to save a local alias, then reuse the name anywhere a +context ID is accepted instead of memorizing the ID: + +```bash +browse cloud contexts create --name github # saves github -> ctx_... +browse cloud contexts add github # name a context you already have +browse cloud sessions create --context-id github --persist +browse cloud contexts list # show saved names +``` + +Use `--verified` when the task needs Browserbase Verified browser mode. To drive a Verified/proxied session directly, prefer `browse open --remote --verified --proxies` over create-then-attach — it keeps the session identity so `browse status`/`browse doctor` can report it. Use `browse cloud sessions create` for session options the driver flags don't cover (region, keep-alive, contexts, full `--stdin` body). + +Use `browse cloud fetch` when the user needs a simple HTTP fetch without browser interaction. It returns markdown-formatted page content by default; pass `--format raw` for the original response body or `--format json --schema ` for structured extraction. Use `browse cloud search` when the user asks for web search results. + +## Browserbase Functions + +Use `browse functions` to create, develop, publish, and invoke Browserbase Functions: + +```bash +browse functions init my-function +browse functions dev index.ts +browse functions publish index.ts +browse functions publish index.ts --dry-run +browse functions invoke --params '{"url":"https://example.com"}' +browse functions invoke --check-status +``` + +Functions commands use `BROWSERBASE_API_KEY`. Generated projects import `defineFn` from `@browserbasehq/sdk-functions`. + +## Templates + +Use `browse templates` to discover and scaffold Browserbase starter templates: + +```bash +browse templates list +browse templates list --tag Python --source Browserbase +browse templates find google-trends-keywords +browse templates find amazon --json +browse templates clone google-trends-keywords +browse templates clone amazon-product-scraping --language python ./my-scraper +browse templates clone dynamic-form-filling ./form-bot --language typescript +``` + +Use `browse templates find` before cloning when the exact slug is uncertain. Use `--language typescript` or `--language python` to choose the generated project runtime when a template supports both. + +## Skills + +Install or refresh this bundled CLI skill: + +```bash +browse skills install +``` + +### Discovering Browse.sh Skills + +Browse.sh (https://browse.sh) is a catalog of site-specific browser automation skills. Each skill is scoped to one task on one website and identified by a `/` slug. An installed skill encodes a proven strategy for that site — API endpoints, selectors, anti-bot handling — so it completes the task faster and more reliably than exploring the site from scratch. + +Search the catalog proactively when: + +- the user asks to complete a task on a specific website — search the domain before automating it by hand +- the user asks for a task in a common category like flights, food delivery, reviews, recipes, tickets, jobs, or shopping — search the keyword +- the user asks "is there a skill for X" or wants new capabilities + +```bash +browse skills list # browse the catalog +browse skills find # search by slug, domain, title, description, category, alias, or tag +browse skills add / # install an exact slug +``` + +### Search Strategy + +Search the domain first, then the task, then broaden: + +```bash +browse skills find yelp.com # 1. exact domain +browse skills find yelp # 2. site name +browse skills find reviews # 3. task keyword +browse skills find "restaurant reviews" # 4. multi-word query +browse skills find food --limit 5 # 5. category keyword, capped +``` + +- Querying an exact slug (`browse skills find yelp.com/extract-reviews-2ikb22`) prints a detail view with the full description and install command. +- If a search returns nothing, try synonyms (`flights` vs `travel`, `food` vs `restaurants`) before concluding no skill exists. +- Each result shows a recommended method — `api`, `fetch`, `browser`, or `hybrid` — indicating how the skill drives the site. Install counts signal which skills are proven. +- Many slugs end in a generated suffix (`-2ikb22`), so never guess or construct them. Install only with an exact slug copied from `list` or `find` output: `browse skills add yelp.com/extract-reviews-2ikb22`. The installed skill becomes available to the agent as a regular skill; a new agent session may be needed to pick it up. + +### Output Formats + +Output is a table in a terminal and JSON when piped, so agents get structured JSON by default. Force a format with `--format table|json` or `--json`. + +```bash +browse skills find food --format table --limit 10 +browse skills find food --json | jq -r '.skills[] | "\(.slug)\t\(.title)"' +``` + +JSON output includes every match with full descriptions and ignores `--limit`; `browse skills list --json` returns the entire catalog, which is large. Prefer `browse skills find ` to narrow first, or `--format table --limit ` for a compact view. + +## Best Practices + +1. Run the real command and inspect its output instead of guessing. +2. Use `browse snapshot` before interacting so you have current refs. +3. Re-run `browse snapshot` after navigation or DOM-changing actions because refs can change. +4. Prefer refs from snapshots for clicks and uploads; use selectors or XPath when refs are unavailable. +5. Use `--local` for localhost and repeatable development; use `--remote` for protected sites or Browserbase-specific behavior. +6. Use a distinct `--session ` for each parallel or long-running task; commands without the flag share the `default` session. +7. Use `--auto-connect` only when attaching to an existing debuggable local Chrome session is intended. +8. Use `browse doctor` when session startup, browser discovery, CDP attach, or Browserbase auth looks wrong. +9. Never retry a failing command unchanged. If the same command fails twice with the same error, stop — run `browse doctor --json`, then change approach (fix the key, switch `--local`/`--remote`, or `browse stop --force` and start fresh). Repeating an identical failing command will keep failing. +10. Use `browse stop` (or `browse stop --session `) when finished to clean up daemon state. +11. For unfamiliar command details, run `browse --help` and follow the exact dash-case flags. + +## Troubleshooting + +- "No active page": run `browse status --session `, then `browse open --session ` or `browse tab new --session `; use `browse stop --force` if the daemon is stale. +- Chrome not found: use `--remote` with Browserbase credentials, install Chrome, or attach with `--cdp`. +- Action fails: run `browse snapshot` and use a visible ref from the current page state. +- 401 Unauthorized on `open`, `get`, or other driver commands: a set `BROWSERBASE_API_KEY` makes `browse` default to remote mode. Fix the key at https://browserbase.com/settings, unset it, or pass `--local` to run a managed local browser (no key needed). +- Same command fails twice with the same error: stop retrying — never retry a failing command unchanged. Init failures are cached for several seconds, so instant retries return identical errors. Run `browse doctor --json`, then change approach: fix the key, switch `--local`/`--remote`, or `browse stop --force` and start fresh. +- Remote command fails: verify `BROWSERBASE_API_KEY` and inspect `browse cloud projects list`. +- Session setup is unclear: run `browse doctor` or `browse doctor --json`. +- Protected site blocks local mode: retry with `--remote`. +- `browse skills find` returns nothing: broaden the query — bare domain, then site name, then a task keyword or synonym. +- `browse skills add` fails on `npx`: install Node.js from https://nodejs.org, then rerun. +- Newly added skill is not available: it installs for future sessions; list installed skills or start a new agent session. diff --git a/opencode/tsconfig.json b/opencode/tsconfig.json new file mode 100644 index 0000000..1b1392f --- /dev/null +++ b/opencode/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "allowImportingTsExtensions": true, + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "noEmit": true, + "resolveJsonModule": true + }, + "include": ["*.ts"], + "exclude": ["node_modules"] +} diff --git a/opencode/v1.ts b/opencode/v1.ts new file mode 100644 index 0000000..808eaa7 --- /dev/null +++ b/opencode/v1.ts @@ -0,0 +1,32 @@ +import type { Plugin } from "@opencode-ai/plugin"; +import { join } from "node:path"; +import { skillsDir } from "./skills.ts"; + +/** OpenCode 1: hooks returned from `server()`, with credentials read from the environment. */ +export const server: Plugin = async () => { + const apiKey = process.env.BROWSERBASE_API_KEY; + const projectId = process.env.BROWSERBASE_PROJECT_ID; + + return { + async config(input) { + input.instructions ??= []; + // @ts-expect-error -- opencode reads skills.paths, but the plugin SDK's Config type does not declare it yet + input.skills ??= {}; + // @ts-expect-error -- see above + input.skills.paths ??= []; + + // Add the bundled skills directory + // @ts-expect-error -- see above + input.skills.paths.push(skillsDir); + }, + + "shell.env": async (_input, output) => { + if (apiKey) { + output.env.BROWSERBASE_API_KEY = apiKey; + } + if (projectId) { + output.env.BROWSERBASE_PROJECT_ID = projectId; + } + }, + }; +}; diff --git a/opencode/v2.ts b/opencode/v2.ts new file mode 100644 index 0000000..8a4be4a --- /dev/null +++ b/opencode/v2.ts @@ -0,0 +1,36 @@ +import type { Plugin, Skill } from "@opencode/plugin"; +import { bundledSkills, installInstructions } from "./skills.ts"; + +/** + * OpenCode 2: skills and shell credentials come from environment variables. + * No custom tools are registered; the plugin bundles the browse CLI skill + * and injects BROWSERBASE_API_KEY/BROWSERBASE_PROJECT_ID into shell commands. + */ +export const v2: Plugin.Plugin = { + id: "browserbase", + async setup(ctx) { + const apiKey = () => process.env.BROWSERBASE_API_KEY; + const projectId = () => process.env.BROWSERBASE_PROJECT_ID; + + const [skills, instructions] = await Promise.all([bundledSkills(), installInstructions()]); + + // Register bundled skills + // SAFETY: Skill.Info's ids and paths are branded strings; the brands are compile-time only. + await ctx.skill.transform((editor) => + skills.forEach((skill) => editor.add(skill as unknown as Skill.Info)) + ); + + // Add install instructions to system prompt + await ctx.session.hook("context", (event) => { + event.system.push({ type: "text", text: instructions }); + }); + + // Inject environment variables into shell commands + await ctx.shell.hook("create.before", async (event) => { + const key = apiKey(); + const project = projectId(); + if (key) event.env.BROWSERBASE_API_KEY = key; + if (project) event.env.BROWSERBASE_PROJECT_ID = project; + }); + }, +};