455 Commits

Author SHA1 Message Date
github-actions[bot]
977f3524d1
Release @browserbasehq/browse-cli@0.4.2 (#1942)
Prepare the next browse-cli release by versioning the package on `main`.

What this PR does:
- bumps `packages/cli/package.json` to `0.4.2`
- updates the browse-cli changelog
- consumes the pending browse-cli changesets

After this PR merges, the `Release` workflow on `main` will publish
`@browserbasehq/browse-cli@0.4.2` from that exact commit using `pnpm
pack` + `npm publish --provenance`.


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Publish `@browserbasehq/browse-cli` 0.4.2 by bumping the version and
updating the changelog. This release adds a command to convert page HTML
to Markdown.

- **New Features**
- Add `browse get markdown [selector]` to convert page HTML to Markdown.
Defaults to body; supports an optional selector; preserves links,
tables, and code blocks via `node-html-markdown`.

<sup>Written for commit eb2b85ff35405600cb3911bc2ad3fd09b018d149.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1942">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-31 16:29:37 -07:00
Sam F
249f5ed634
fix: pass through server-v3 operation errors (#1937)
## Summary
- return underlying operation error messages from server-v3 streaming
handlers
- return underlying non-AppError messages from the top-level server-v3
error wrapper
- preserve existing status code behavior while making local
act/extract/observe 500s diagnosable

## Testing
- pnpm --filter @browserbasehq/stagehand-server-v3 typecheck

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Pass through underlying operation errors in
`@browserbasehq/stagehand-server-v3` so clients see real failure
messages during streaming and top-level responses, and force flow logs
on for easier debugging. Status codes stay the same, making local
act/extract/observe 500s diagnosable.

- **Bug Fixes**
- Streaming + error wrapper: return the thrown error’s message for
non-`AppError` cases; fall back to a default when not an `Error`,
preserving status codes.
- Observe route: remove unused `Variables` import/cast to satisfy lint;
no behavior change.

<sup>Written for commit ba08fd08ef6750ef525e4aed246f693f4f4c6f92.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1937">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-03-31 22:44:33 +02:00
Derek
3917df4851
Add browse get markdown command (#1907)
## Summary
- Adds `browse get markdown [selector]` to convert page HTML to clean
markdown
- Defaults to body content when no selector given, accepts optional
CSS/XPath/ref selector
- Uses `node-html-markdown` for quality conversion (links, tables, code
blocks preserved)
- Useful for agents that need readable page content without HTML noise

## Usage
```bash
browse get markdown                # full page body as markdown
browse get markdown .article       # specific element
browse get markdown @0-5           # ref from snapshot
```

## Test results
| Test | Local | Remote (Browserbase) |
|------|-------|---------------------|
| `get markdown` (body default) | HN full page markdown | HN full page
markdown |
| `get markdown .titleline` (selector) | Clean link with title | Clean
link with title |

## Test plan
- [x] Test locally with no selector (full body)
- [x] Test locally with CSS selector
- [x] Test on remote Browserbase session (no selector)
- [x] Test on remote Browserbase session (with selector)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 13:06:28 -07:00
tkattkat
d3c3736c57
Add support for LLM middleware (#1872)
# why

- In some scenarios, users need more granular control / access to the
LLM at the provider leve

# what changed

- Added support for passing custom "middleware" in the model options 

# test plan

- wrote tests 
- tested locally with own middleware 

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds first-class LLM middleware to intercept and wrap model calls for
logging, usage tracking, or request transforms without changing call
sites. Per-call middleware is used only for that call and is not cached.

- **New Features**
- Accepts `middleware: LanguageModelV2Middleware` in `V3` model config;
`LLMProvider` and `getAISDKLanguageModel` wrap models via
`wrapLanguageModel` from `ai`.
- Supports per-call overrides via `model` options; override middleware
is passed through `LLMProvider.getClient`, applies only to that call,
and is never cached.
- Works across providers and preserves `modelId`, `doGenerate`, and
`doStream`. Tests cover usage capture, streaming, errors, chaining, and
edge cases.

- **Migration**
- To use: pass `middleware` in `model` config or a per-call override,
e.g. `{ modelName: 'openai/gpt-4o', apiKey: '...', middleware }`.
- Middleware is only applied in direct/local execution and is not
serialized over HTTP.

<sup>Written for commit b09e42c72ae27d7c988776962e30e9c0aec3dfda.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1872">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-03-31 11:10:16 -07:00
github-actions[bot]
ad055f9153
Release @browserbasehq/browse-cli@0.4.1 (#1932)
Prepare the next browse-cli release by versioning the package on `main`.

What this PR does:
- bumps `packages/cli/package.json` to `0.4.1`
- updates the browse-cli changelog
- consumes the pending browse-cli changesets

After this PR merges, the `Release` workflow on `main` will publish
`@browserbasehq/browse-cli@0.4.1` from that exact commit using `pnpm
pack` + `npm publish --provenance`.


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Release `@browserbasehq/browse-cli@0.4.1`, a patch that fixes an invalid
session metadata key. This bumps the package version and updates the
changelog for publishing from `main`.

- **Bug Fixes**
- Use underscore in `browse_cli` session metadata keys instead of a
hyphen.

<sup>Written for commit 022c400a4e398a222b0691f6c0d4c3c02621d471.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1932">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-31 08:50:43 -07:00
Derek
56d7b9f5cc
[STG-1733] fix: use valid metadata key for browse-cli sessions (#1911)
## Summary
- The `browse-cli` metadata key (with hyphen) is rejected by the
Browserbase API as an invalid metadata key, causing `env remote` to fail
with a `400 Key is not a valid metadata key: browse-cli` error.
- Changed the key to `browse_cli` (underscore) which is a valid metadata
key format.

Linear:
https://linear.app/browserbase/issue/STG-1733/fix-use-valid-metadata-key-for-browse-cli-sessions

## Test plan
- [x] Verified old key (`browse-cli`) returns 400 from Browserbase API
- [x] Verified new key (`browse_cli`) returns 201 and session creates
successfully

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Shrey Pandya <shrey@browserbase.com>
2026-03-31 08:29:22 -07:00
Sean McGuire
a1ab39e7aa
[fix]: attach to manually-created new tabs (#1924)
# why
- when a user created a new tab by clicking the "+" icon in a headful
chromium browser, stagehand would not attach to it, because it filtered
out the `"chrome://newtab"` url pattern
# what changed
- extended the conditional in `isNonWebTarget()` to allow for
`"chrome://newtab"` URLs to pass through, so that stagehand can attach
to them
<img width="491" height="95" alt="Screenshot 2026-03-30 at 4 00 48 PM"
src="https://github.com/user-attachments/assets/64638fc4-7334-4438-8df5-5a91344b6afb"
/>
# test plan
- added a test which creates a newtab target, & confirms that a new page
object gets created

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes `@browserbasehq/stagehand` not attaching to tabs opened via the
"+" button in Chromium by tracking `chrome://newtab/` page targets so a
page is created and becomes usable after navigation.

- **Bug Fixes**
- Updated `isNonWebTarget()` to always track top-level `page` targets,
even with non-web schemes like `chrome://newtab/`.
- Added Playwright tests to verify `chrome://newtab/` tabs appear in
`pages()` and work after navigating to a web URL.

<sup>Written for commit 9791271a1bb1aa4cb5622955071f67166b7007ca.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1924">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-03-30 17:20:02 -07:00
github-actions[bot]
be6798aefd
Release @browserbasehq/browse-cli@0.4.0 (#1925)
Prepare the next browse-cli release by versioning the package on `main`.

What this PR does:
- bumps `packages/cli/package.json` to `0.4.0`
- updates the browse-cli changelog
- consumes the pending browse-cli changesets

After this PR merges, the `Release` workflow on `main` will publish
`@browserbasehq/browse-cli@0.4.0` from that exact commit using `pnpm
pack` + `npm publish --provenance`.


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Release `@browserbasehq/browse-cli` 0.4.0 with new session attach and
smarter local Chrome discovery, plus stability fixes. Bumps the package
version and updates the changelog; the Release workflow will publish
from this commit.

- **New Features**
  - Add `--connect` to attach to an existing Browserbase session by ID.
- `browse env local` auto-discovers debuggable Chrome and attaches when
found (falls back to isolated). Adds `--isolated`, positional CDP
target, and `--ws` accepts bare port numbers.

- **Bug Fixes**
  - Add CLI metadata to Browserbase sessions created via the CLI.
- Clear cached browser state when CDP connection drops to prevent
“awaitActivePage: no page available” errors.

<sup>Written for commit d74493490d65ffd4f18e128ae2afb8448c4117f0.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1925">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-30 16:17:16 -07:00
Sean McGuire
f5d1f1ff80
[fix]: handle mapping timeout -> timeoutMs (#1901)
# why
- the `timeoutMs` param in `goto` was not being respected when using the
stagehand api
- the `/navigate` route on the server expects `timeout`, while the
actual `goto()` implementation in node expects `timeoutMs`
# what changed
- added logic to correctly send the `timeoutMs` param to the server as
`timeout`
- added server side logic to map the `timeout` back to `timoeutMs`
(which is what `goto()` expects)
### screenshot: (navigate correctly adheres to defined timeout)
<img width="691" height="462" alt="Screenshot 2026-03-27 at 4 13 04 PM"
src="https://github.com/user-attachments/assets/946de567-70d5-4fa9-be8e-646bb996e894"
/>


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes timeout handling for navigation by mapping `timeoutMs` on the
client to `timeout` over the API, then back to `timeoutMs` for
`page.goto()`. Navigations now respect the configured timeout when using
the Stagehand API.

- **Bug Fixes**
  - Client sends `timeout` to `/navigate` from `options.timeoutMs`.
  - Server maps `timeout` to `timeoutMs` before calling `page.goto()`.

<sup>Written for commit 783fa2b80e2f3f4bb601e1c239c3991957149e53.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1901">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-03-27 16:24:51 -07:00
Shrey Pandya
bd2a9cfcad
STG-1668: browse env local auto-discovers existing Chrome via CDP (#1886)
## Summary

- `browse env local` now auto-discovers an already-running Chrome with
remote debugging enabled (via `DevToolsActivePort` files and common port
probing), attaching to it instead of always launching an isolated
browser
- Falls back to isolated launch when no debuggable Chrome is found —
keeps the command reliable
- Added `--isolated` flag to force clean isolated browser (old behavior)
- Added positional CDP target argument: `browse env local 9222` or
`browse env local ws://...`
- `browse status` now reports `localStrategy`, `localSource`,
`resolvedCdpUrl`, and `fallbackReason`

**Sister PR:** browserbase/skills#54

## Test plan

<img width="698" height="373" alt="image"
src="https://github.com/user-attachments/assets/1612cf7e-61f4-46b8-9cc6-e739c7363a5a"
/>

- [x] All 44 existing tests pass
- [x] `browse env local` with Chrome running +
`--remote-debugging-port=9222` → attaches to existing Chrome
- [x] `browse env local` without debuggable Chrome → falls back to
isolated launch
- [x] `browse env local --isolated` → always launches clean browser
- [x] `browse env local 9222` → persists CDP strategy targeting
127.0.0.1:9222
- [x] `browse status` shows local strategy details
- [x] `browse env remote` → unchanged

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 16:13:51 -07:00
tkattkat
6dc2276144
Fix OpenAI cua agent (#1899)
# why

- OpenAI now requires a screenshot on initial message for computer use
agents

# what changed

- added screenshot to initial message 
- imported types from openai sdk for stronger typing 

# test plan

- tested locally using operator-example script 

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Send an initial screenshot with the first message in `OpenAICUAClient`
to meet OpenAI’s computer-use requirement and prevent startup errors.
Also adopt `openai` SDK response types for stricter typing.

- **Bug Fixes**
- Capture and attach a high-detail screenshot on the first request when
available; gracefully skip on failure.
- Build the first message using `EasyInputMessage`, `ResponseInputText`,
and `ResponseInputImage`; include an optional system message from
`userProvidedInstructions`; make `createInitialInputItems` async and
update method signatures to accept a unified `OpenAIRequestInputItem`
type.

- **Dependencies**
  - Add changeset for a patch release of `@browserbasehq/stagehand`.

<sup>Written for commit f01d8a81e79b1cd304ce357016b2f87850a8001b.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1899">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-03-27 11:40:39 -07:00
Shrey Pandya
3bd09d3abc
chore: Decouple browse-cli release cycle from stagehand core (#1885)
## Summary

- Adds `@browserbasehq/browse-cli` to the changeset `ignore` list so the
main "Version Packages" PR no longer includes CLI version bumps
- Creates a new `release-cli.yml` workflow (triggered via
`workflow_dispatch`) that independently versions and publishes
browse-cli to npm

### How it works

**Main release flow (`release.yml`)** — unchanged, but now skips
browse-cli. Core stagehand changesets are versioned and published as
before.

**CLI release flow (`release-cli.yml`)** — triggered manually via GitHub
Actions "Run workflow":
1. Detects pending browse-cli changesets (fails early if a changeset
mixes browse-cli with other packages)
2. Temporarily swaps the changeset ignore config to version only
browse-cli
3. Runs `changeset version` to consume CLI changesets and bump
`packages/cli/package.json`
4. Builds all packages, publishes browse-cli to npm via Trusted
Publishing
5. Commits the version bump and pushes a git tag

### Constraints
- Changesets that reference **both** browse-cli and another package
(e.g., stagehand core) must be split into separate changeset files — the
workflow enforces this with a pre-check
- browse-cli is excluded from canary (`alpha`) releases — add a canary
step to `release-cli.yml` if needed later

## Test plan
- [ ] Verify existing `release.yml` still creates "Version Packages" PR
for core changesets (browse-cli changesets should be excluded)
- [ ] Trigger `release-cli.yml` via workflow_dispatch with a pending
browse-cli changeset and verify it publishes correctly
- [ ] Verify mixed changeset detection fails the workflow with a clear
error

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Decouples the `@browserbasehq/browse-cli` release cycle from stagehand
core so we can ship CLI updates independently. Implements STG-1663.

- **New Features**
- Adds `@browserbasehq/browse-cli` to `.changeset` ignore so
`release.yml` skips CLI.
- Adds `release-cli.yml` (manual via `workflow_dispatch`, restricted to
`main`) to version and publish CLI with Trusted Publishing.
  - Pre-checks for CLI-only changesets; fails on mixed changesets.
- Temporarily swaps `.changeset` ignore to version only CLI and strips
the `@browserbasehq/stagehand` workspace dep before `changeset version`
to satisfy Changesets; restores both after.
- Builds and publishes `packages/cli` to npm, commits the bump, and
tags.

- **Migration**
  - Split changesets that touch CLI and core.
  - Use the “Release CLI” workflow to publish CLI releases.
  - Canary releases for CLI are not included.

<sup>Written for commit c2989049e7994389ba1c391f95eb70628e174a4c.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1885">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 16:55:15 -07:00
Shrey Pandya
e81dde7157
STG-1672: Add --connect flag to browse CLI for existing Browserbase sessions (#1889)
## Summary

- Adds a global `--connect <session-id>` flag to the `browse` CLI that
connects to an existing Browserbase session instead of creating a new
one
- Uses Stagehand core's existing `browserbaseSessionID` support with
`keepAlive: true` so the session stays alive after the CLI disconnects
- Follows the same state-file pattern as `--context-id` (writes session
ID to `/tmp/browse-{session}.connect`, daemon reads it during
initialization)

## Test procedure

```
# 1. Sync cookies
node cookie-sync.mjs --domains github.com
# → Session ID: 3ee737d4-237f-4557-a1ca-09a3d5dcbaf2

# 2. Connect and browse (dev build)
browse --connect 3ee737d4-... open https://github.com/notifications  ✅
browse eval "..."  ✅
```

## Tests completed

- [x] `browse --connect <id> open ...` in local mode → errors with "only
supported in remote mode"
- [x] `browse --connect <id> open --context-id <ctx> ...` → errors with
mutual exclusion message
- [x] `--connect` writes session ID to connect file before daemon start
- [x] Commands without `--connect` clear stale connect file
- [x] `browse status` output includes `browserbaseSessionId` field
- [x] Manual: `browse --connect <valid-bb-session> open
https://example.com` connects and navigates
- [x] Manual: `browse stop` disconnects without killing the BB session

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Fixes STG-1672


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds a `--connect <session-id>` flag to the `browse` CLI to attach to an
existing Browserbase session instead of creating a new one, leaving the
session running after the CLI exits. Implements STG-1672.

- **New Features**
- New global `--connect <session-id>` for `browse` to attach to an
existing Browserbase session
  - Remote mode only; errors in local mode
  - Mutually exclusive with `--context-id`
- Persists the session ID to `/tmp/browse-{session}.connect`; clears
when unused and restarts the daemon if the ID changes
- Uses `browserbaseSessionID` with `keepAlive: true` so the session
persists after disconnect
  - `browse status` now includes a `browserbaseSessionId` field
  - Minor release for `@browserbasehq/browse-cli`

<sup>Written for commit aff1badd630fbbf2276b8121f5981b551850be2f.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1889">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 22:16:14 -07:00
Shrey Pandya
6e3c14bd8c
STG-1669: fix(cli): clear cached state when browser connection dies (#1887)
## Summary
- When the browse CLI daemon outlives its Chrome browser (e.g., between
Claude Code sessions), `ensureBrowserInitialized()` returns the cached
`stagehand`/`context` without checking if the browser is still alive
- This causes `"No Page found for awaitActivePage: no page available"`
errors requiring a manual `browse stop` + retry
- Fix: register an `onTransportClosed` handler on the CDP connection
that clears the cached state, so the next command triggers a full
re-initialization

## Root cause
The daemon is spawned as a detached process (`detached: true`,
`child.unref()`) and persists across CLI sessions. When Chrome dies,
`_onCdpClosed` fires and calls `stagehand.close()`, but the daemon's
closure variables `stagehand` and `context` are never cleared. The next
command hits the early return at `if (stagehand && context) { return ...
}` and tries to use dead objects.

## Test plan

**Regression test added to PR is illustrative** 

- [x] Start a `browse` session, close Chrome manually, run another
`browse open` — should auto-recover instead of erroring
- [x] Normal `browse` workflow (open, snapshot, click, stop) still works
- [x] Daemon restart across mode switches (local ↔ remote) still works
- [x] Regression test added: kills Chrome under daemon, verifies
auto-recovery (fails on main, passes with fix)

## Verified test results

**On `main` (without fix):** Test fails — after killing Chrome, the
retry returns exit code 1 with `"Error: No Page found for
awaitActivePage: no page available"`. The daemon is alive but returns
stale cached Stagehand/context objects.

**On this branch (with fix):** Test passes — after killing Chrome, the
`onTransportClosed` handler nulls the cached state, and the retry
triggers a full browser re-initialization. All 37 CLI tests pass (full
suite, 67s).

> **Note:** When building locally, use `npx tsup src/index.ts --format
cjs --out-dir dist --no-splitting` inside `packages/cli/` rather than
`pnpm run build:cli`, since turbo may serve a stale cached build that
doesn't include the fix.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 21:27:31 -07:00
Shrey Pandya
6c89565cd1
feat(cli): add browse-cli metadata to Browserbase sessions (#1890)
## Summary
- Adds `userMetadata: { "browse-cli": "true" }` to every Browserbase
session created through the browse CLI
- Enables usage attribution to distinguish CLI-originated sessions from
SDK-originated ones

## Test plan
- [x] Run `browse open https://example.com` in Browserbase mode and
verify the session has `browse-cli: true` in its metadata
- [x] Verify local mode is unaffected

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds `userMetadata: { "browse-cli": "true" }` to
`browserbaseSessionCreateParams` for sessions started by
`@browserbasehq/browse-cli` in Browserbase mode, enabling usage
attribution and distinguishing CLI vs SDK sessions. Satisfies STG-1678;
local mode is unaffected.

<sup>Written for commit 58c10fdf25c5494bdb2b1c1e793344009fa6374a.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1890">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 14:30:15 -07:00
Miguel
a98801a17f
Fix schema parsing bug for Pydantic .model_json_schema() (#1873)
# why
JSON schema parsing for schemas generated from Pydantic
`.model_json_schema()` were dropping the nested references

# what changed
Before (from test script) with schema: 
```python
class RequiredInputType(StrEnum):
    USERNAME = "username"
    EMAIL = "email"
    PHONE = "phone"
    OTP = "otp"
    PASSWORD = "password"
    CARD_LAST_8 = "card_last_8"
    SOMETHING_ELSE = "something_else"

class PageState(StrEnum):
    LOGIN_FORM = "login_form"
    ERROR = "error"
    AUTHENTICATED = "authenticated"
    UNKNOWN = "unknown"

class PageAnalysis(BaseModel):
    page_state: PageState
    required_input: RequiredInputType | None = None
    contact_id_of_required_input: str | None = None
    error_message: str | None = None
    reasoning: str = ""
```
<img width="654" height="373" alt="Screenshot 2026-03-23 at 1 09 01 PM"
src="https://github.com/user-attachments/assets/29a24eea-cfda-40a8-8e43-10f959c71ad2"
/>

After: 
<img width="650" height="310" alt="Screenshot 2026-03-23 at 1 06 17 PM"
src="https://github.com/user-attachments/assets/9f62d1ad-04bb-41e4-9dbc-85d7b68c84aa"
/>

1. Added resolveRefs() function that inlines $ref/$defs before Zod
conversion (Pydantic
  v2's model_json_schema() generates these)
2. Changed z.string().refine() → z.enum() so enum constraints are
expressed in the
  schema sent to the LLM, not just validated post-hoc


# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes missing nested `$ref` when converting Pydantic v2
`.model_json_schema()` to Zod in `@browserbasehq/stagehand-server-v3`,
and emits proper `z.enum()` types so LLM-facing schemas are accurate.
Adds a `test:unit` script, moves tests to `tests/`, and updates the
runner to scan directories or single files.

- **Bug Fixes**
- Resolves `$ref` from `$defs` before conversion via `resolveRefs()`
with a cycle guard, handling refs in objects, arrays,
`anyOf`/`oneOf`/`allOf`, and root-level refs (unknown refs fall back
safely).
- Replaces `z.string().refine()` with `z.enum()` so enum values are
surfaced in generated schemas and enforced.

<sup>Written for commit ae9e2e5b509faa90c89e52ec71c3d444b2181abb.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1873">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-03-24 15:55:40 -07:00
Miguel
f3fe7ce597
Include LLM headers in ModelConfig (#1874)
# why
Custom headers for LLM requests are supported in Stagehand, canonical
SDKs were not accounting for this until now.

# what changed
Added headers to ModelConfig

# test plan



<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds an optional `headers` field to `ModelConfig` to send custom headers
with every LLM request. Also includes a patch changeset for
`@browserbasehq/stagehand`.

- **New Features**
- Add `headers?: Record<string, string>` to `ModelConfigObjectSchema` in
`packages/core/lib/v3/types/public/api.ts`.
- Update `packages/server-v3/openapi.v3.yaml` to document `headers` in
`ModelConfig`.
- Update `packages/server-v4/openapi.v4.yaml` to use selector-based
result/output schemas for page actions (click, hover, scroll,
drag-and-drop) and add `returnSelector` support.

<sup>Written for commit f83bd8bee8ab6c17a237125a2a41d0278ca01768.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1874">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->

---------

Co-authored-by: Sean McGuire <seanmcguire1@outlook.com>
2026-03-24 11:29:40 -07:00
Sam F
8bf5db8eb8
Add explicit SSE event names for local v3 streaming (#1858)
## Why
The stainless sdks are dropping the final finished SSE event instead of
yielding it. This is due to the fact that we were not using `event`
fields (basically setting event types) as per the SSE spec.

The fix is to emit explicit SSE `event:` names and match them in
Stainless. But on the hosted API we cannot switch that on for everyone
at once, because older clients still expect the old `data:`-only SSE
framing. Thus, we will need to have branching logic in our hosted
server:

1. Legacy (old stainless sdks, stagehand-js): continue to not return
`event` field.
2. New Stainless SDKs on `>= 3.13.0`: use typed SSE framing with
`event:` + `data:`.

Once this and it's core counterpart PR are merged, then we will release
another version of all stainless sdks - `3.13`, which will be the first
typed-SSE release.

## What Changed
- emit explicit SSE `event:` names from the local v3 streaming helper
while keeping the JSON `data:` payload unchanged
- switch Stainless streaming matching to explicit `event_type` handlers
- update the documented stream shape, regenerated v3 OpenAPI, and a
focused integration assertion

## Testing
- `pnpm --dir /tmp/stagehand-local-sse.lSk5Av --filter
@browserbasehq/stagehand-server-v3 run gen:openapi`
- `pnpm --dir /tmp/stagehand-local-sse.lSk5Av exec prettier --check
stainless.yml`
- `pnpm --dir /tmp/stagehand-local-sse.lSk5Av --filter
@browserbasehq/stagehand lint`
- `pnpm --dir /tmp/stagehand-local-sse.lSk5Av --filter
@browserbasehq/stagehand-server-v3 lint`

A test run with the three different client types against the updated
server:
<img width="765" height="230" alt="Screenshot 2026-03-20 at 11 01 50 AM"
src="https://github.com/user-attachments/assets/af97c8ec-d7f9-4ae6-95a0-16a3c2906934"
/>

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Emit explicit SSE event names for v3 streaming (`starting`, `connected`,
`running`, `finished`, `error`) while keeping the JSON `data:` payload
unchanged. Updates the streaming helper, Stainless config, OpenAPI docs,
and tests to use and verify typed events.

- New Features
  - Server now sends `event: <status>` with `data: { data, type, id }`.
- Switched `stainless.yml` streaming matching to `event_type` (yields on
starting/connected/running/finished; handles `error`).
- Added integration test asserting event names match payload status;
updated OpenAPI description and core type docs.

- Dependencies
- Added changeset to publish patch updates for
`@browserbasehq/stagehand` and `@browserbasehq/stagehand-server-v3`.

<sup>Written for commit 96cd0372df7cad7d1986de0f9405e5a4f7f0e781.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1858">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-03-24 18:20:43 +01:00
Sean McGuire
144e18e9e0
[feat]: apply toolTimeout arg to more tools (#1843)
# why
- `toolTimeout` was only being applied to the `act`, `extract`,
`fillForm`, & `ariaTree` tools
- we want the `toolTimeout` to take effect across all of the tools (with
the exception of `wait` & `think`)
- additionally, when a timeout was being hit, the duration of the
timeout was not being included in the error logs
# what changed
- wrapped all agent tool calls (other than `wait` & `think`) in
`withTimeout()`
- update error logs to include the timeout duration in the log message
### updated error logs with timeout duration:
<img width="887" height="98" alt="Screenshot 2026-03-17 at 3 53 50 PM"
src="https://github.com/user-attachments/assets/957d2e68-0078-47c2-98d7-32f28f76f105"
/>

### example of tool call respecting timeout (`screenshot()` had no
`toolTimeout` before)

<img width="698" height="108" alt="Screenshot 2026-03-17 at 4 13 02 PM"
src="https://github.com/user-attachments/assets/344df89d-f545-4380-92bb-562633e34ce9"
/>

# test plan
- extended tests in `timeout.spec.ts` to validate that all of the tools
correctly respect `toolTimeout`

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Applies a user-defined `toolTimeout` to all async agent tools (except
`wait` and `think`) via a centralized wrapper at tool init. Timeouts
return a consistent `TimeoutError` that includes the duration (ms) and
short hints. Addresses Linear STG-1510.

- New Features
- Centralized timeouts: wrap tool execute in `createAgentTools()` with
`withTimeout()`; covers `act`, `extract`, `fillForm`, `fillFormVision`,
`ariaTree`, `click`, `clickAndHold`, `dragAndDrop`, `type`, `keys`,
`scroll` (DOM/hybrid), `screenshot`, `goto`, `navback`, and `search`
(Brave/Browserbase).
- Consistent errors and logs: tools re-throw timeouts to the wrapper;
wrapper logs and returns `{ success: false, error }`; simplified
non-timeout messages in `search`, `click`, `clickAndHold`,
`dragAndDrop`, `type`, and `keys`.
- Tests: expanded `timeouts.spec.ts` to cover DOM and hybrid tools;
asserts the timeout duration (e.g., "1ms") is included.

- Migration
- No breaking changes. Set `toolTimeout` via `createAgentTools(v3, {
toolTimeout: <ms> })` or `v3.agent({ toolTimeout: <ms> })`.

<sup>Written for commit 9e818797cac965264f04b0bba1ba30d9f6000195.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1843">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-03-18 16:45:39 -07:00
github-actions[bot]
3c904cb789
Version Packages (#1754)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and the packages will
be published to npm automatically. If you're not ready to do a release
yet, that's fine, whenever you add more changesets to main, this PR will
be updated.


# Releases
## @browserbasehq/browse-cli@0.2.0

### Minor Changes

- [#1816](https://github.com/browserbase/stagehand/pull/1816)
[`687d54a`](687d54adda)
Thanks [@shrey150](https://github.com/shrey150)! - Add `--context-id`
and `--persist` flags to `browse open` for loading and persisting
Browserbase Contexts across sessions

- [#1793](https://github.com/browserbase/stagehand/pull/1793)
[`e38c13b`](e38c13b752)
Thanks [@shrey150](https://github.com/shrey150)! - Initial release of
browse CLI - browser automation for AI agents

### Patch Changes

- [#1806](https://github.com/browserbase/stagehand/pull/1806)
[`f8c7738`](f8c773898f)
Thanks [@shrey150](https://github.com/shrey150)! - Fix `browse env`
showing stale mode after `browse env remote`

- Updated dependencies
\[[`505e8c6`](505e8c6736),
[`2f43ffa`](2f43ffac11),
[`63ee247`](63ee247ac6),
[`7dc35f5`](7dc35f5e25),
[`335cf47`](335cf4730e),
[`6ba0a1d`](6ba0a1db7f),
[`4ff3bb8`](4ff3bb831a),
[`c27054b`](c27054bbd0),
[`2abf5b9`](2abf5b90f1),
[`7817fcc`](7817fcc315),
[`7390508`](73905088c5),
[`611f43a`](611f43ac8d),
[`521a10e`](521a10e369),
[`2402a3c`](2402a3c4d5)]:
    -   @browserbasehq/stagehand@3.2.0

## @browserbasehq/stagehand@3.2.0

### Minor Changes

- [#1779](https://github.com/browserbase/stagehand/pull/1779)
[`2f43ffa`](2f43ffac11)
Thanks [@shrey150](https://github.com/shrey150)! - feat: add
`cdpHeaders` option to `localBrowserLaunchOptions` for passing custom
HTTP headers when connecting to an existing browser via CDP URL

- [#1834](https://github.com/browserbase/stagehand/pull/1834)
[`63ee247`](63ee247ac6)
Thanks [@tkattkat](https://github.com/tkattkat)! - Update stagehand
agents search tool

- [#1774](https://github.com/browserbase/stagehand/pull/1774)
[`521a10e`](521a10e369)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - add new
page.setExtraHTTPHeaders() method

### Patch Changes

- [#1759](https://github.com/browserbase/stagehand/pull/1759)
[`505e8c6`](505e8c6736)
Thanks [@shrey150](https://github.com/shrey150)! - Add bedrock to the
provider enum in model configuration schemas and regenerate OpenAPI
spec.

- [#1814](https://github.com/browserbase/stagehand/pull/1814)
[`7dc35f5`](7dc35f5e25)
Thanks [@tkattkat](https://github.com/tkattkat)! - Change usage of
openai provider in agent to default to store:false

- [#1846](https://github.com/browserbase/stagehand/pull/1846)
[`335cf47`](335cf4730e)
Thanks [@aq17](https://github.com/aq17)! - Fix streaming finished event
being silently dropped. The final SSE event containing the result
payload (success status, message, actions, usage, and messages) was
previously discarded instead of being yielded to the caller.

- [#1764](https://github.com/browserbase/stagehand/pull/1764)
[`6ba0a1d`](6ba0a1db7f)
Thanks [@shrey150](https://github.com/shrey150)! - Expose `headers` in
`GoogleVertexProviderSettings` so model configs can pass custom provider
headers (for example `X-Goog-Priority`) without TypeScript errors.

- [#1847](https://github.com/browserbase/stagehand/pull/1847)
[`4ff3bb8`](4ff3bb831a)
Thanks [@miguelg719](https://github.com/miguelg719)! - Enable FlowLogger
on BROWSERBASE_FLOW_LOGS=1

- [#1752](https://github.com/browserbase/stagehand/pull/1752)
[`c27054b`](c27054bbd0)
Thanks [@derekmeegan](https://github.com/derekmeegan)! - fix: pause
Browserbase agents while captcha solving is active and improve CUA
recovery after the solve completes

- [#1800](https://github.com/browserbase/stagehand/pull/1800)
[`2abf5b9`](2abf5b90f1)
Thanks [@shrey150](https://github.com/shrey150)! - Make projectId
optional for Browserbase sessions — only BROWSERBASE_API_KEY is required

- [#1766](https://github.com/browserbase/stagehand/pull/1766)
[`7817fcc`](7817fcc315)
Thanks [@tkattkat](https://github.com/tkattkat)! - Add configurable
timeout to tools in agent

- [#1749](https://github.com/browserbase/stagehand/pull/1749)
[`7390508`](73905088c5)
Thanks [@pirate](https://github.com/pirate)! - When connecting to a
browser session that has zero open tabs, Stagehand now automatically
creates an initial `about:blank` tab so the connection can continue.

- [#1761](https://github.com/browserbase/stagehand/pull/1761)
[`611f43a`](611f43ac8d)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue
where handlePossibleNavigation was producing unnecessary error logs on
clicks that trigger page close

- [#1817](https://github.com/browserbase/stagehand/pull/1817)
[`2402a3c`](2402a3c4d5)
Thanks [@tkattkat](https://github.com/tkattkat)! - Add support for
passing custom headers in clientOptions

## @browserbasehq/stagehand-evals@1.1.9

### Patch Changes

- Updated dependencies
\[[`505e8c6`](505e8c6736),
[`2f43ffa`](2f43ffac11),
[`63ee247`](63ee247ac6),
[`7dc35f5`](7dc35f5e25),
[`335cf47`](335cf4730e),
[`6ba0a1d`](6ba0a1db7f),
[`4ff3bb8`](4ff3bb831a),
[`c27054b`](c27054bbd0),
[`2abf5b9`](2abf5b90f1),
[`7817fcc`](7817fcc315),
[`7390508`](73905088c5),
[`611f43a`](611f43ac8d),
[`521a10e`](521a10e369),
[`2402a3c`](2402a3c4d5)]:
    -   @browserbasehq/stagehand@3.2.0

## @browserbasehq/stagehand-server-v3@3.6.1

### Patch Changes

- [#1759](https://github.com/browserbase/stagehand/pull/1759)
[`505e8c6`](505e8c6736)
Thanks [@shrey150](https://github.com/shrey150)! - Add bedrock to the
provider enum in model configuration schemas and regenerate OpenAPI
spec.

- Updated dependencies
\[[`505e8c6`](505e8c6736),
[`2f43ffa`](2f43ffac11),
[`63ee247`](63ee247ac6),
[`7dc35f5`](7dc35f5e25),
[`335cf47`](335cf4730e),
[`6ba0a1d`](6ba0a1db7f),
[`4ff3bb8`](4ff3bb831a),
[`c27054b`](c27054bbd0),
[`2abf5b9`](2abf5b90f1),
[`7817fcc`](7817fcc315),
[`7390508`](73905088c5),
[`611f43a`](611f43ac8d),
[`521a10e`](521a10e369),
[`2402a3c`](2402a3c4d5)]:
    -   @browserbasehq/stagehand@3.2.0

## @browserbasehq/stagehand-server-v4@3.6.1

### Patch Changes

- Updated dependencies
\[[`505e8c6`](505e8c6736),
[`2f43ffa`](2f43ffac11),
[`63ee247`](63ee247ac6),
[`7dc35f5`](7dc35f5e25),
[`335cf47`](335cf4730e),
[`6ba0a1d`](6ba0a1db7f),
[`4ff3bb8`](4ff3bb831a),
[`c27054b`](c27054bbd0),
[`2abf5b9`](2abf5b90f1),
[`7817fcc`](7817fcc315),
[`7390508`](73905088c5),
[`611f43a`](611f43ac8d),
[`521a10e`](521a10e369),
[`2402a3c`](2402a3c4d5)]:
    -   @browserbasehq/stagehand@3.2.0

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-18 14:38:34 -07:00
Derek
c27054bbd0
[feat]: auto-pause agent during Browserbase captcha solving (#1752)
# why

Browserbase can solve captchas asynchronously, but agents were still
trying to interact with the page while the solver was active. That led
to CUA and DOM/hybrid flows clicking solved captcha widgets again,
pausing on confirmation questions, or resuming with stale assumptions
instead of continuing the original task cleanly.

This PR pauses agent execution while Browserbase's captcha solver is
active and hardens the post-solve resume path so the agent keeps working
on the original task after Browserbase finishes.

# what changed

- added a shared `CaptchaSolver` utility that listens for Browserbase
`browserbase-solving-started/finished/errored` console events, supports
concurrent waiters, and disposes listeners cleanly
- paused DOM/hybrid `prepareStep` execution and CUA `prepareStep` /
action execution while Browserbase is solving a captcha
- enabled Browserbase captcha solving by default unless
`browserSettings.solveCaptchas: false`
- updated agent prompts and follow-up messages to tell the model that
captchas are handled automatically and should not be clicked again after
they are solved
- added OpenAI CUA recovery behavior so it can:
  - carry one-shot context notes into the next model turn
  - auto-continue when the model asks for confirmation instead of acting
- guard post-solve clicks that target the solved captcha widget and
restate the original instruction so the model re-anchors on the task
- added focused unit coverage for solver state, Browserbase session
accessors, CUA/regular agent hooks, and OpenAI CUA confirmation handling

# test plan

- `pnpm --filter @browserbasehq/stagehand lint`
- `pnpm --filter @browserbasehq/stagehand build:esm`
- `cd packages/core && pnpm exec vitest run --config
vitest.esm.config.mjs dist/esm/tests/unit/openai-cua-client.test.js
dist/esm/tests/unit/captcha-solver.test.js
dist/esm/tests/unit/agent-captcha-hooks.test.js
dist/esm/tests/unit/browserbase-session-accessors.test.js`

Browserbase smoke:

- OpenAI CUA + reCAPTCHA demo: strict pass on `Verification Success`
- Anthropic CUA + reCAPTCHA demo: strict pass on `Verification Success`
- Hybrid Gemini + reCAPTCHA demo: strict pass on `Verification Success`
- OpenAI CUA + `solveCaptchas: false`: solver stays disabled, no
wait/resume path is triggered, and the agent stops at the captcha
instead of bypassing it

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Shrey Pandya <shrey@browserbase.com>
2026-03-18 17:03:59 -04:00
Miguel
4ff3bb831a
Enable FlowLogger on BROWSERBASE_FLOW_LOGS=1 (#1847) 2026-03-18 13:58:33 -07:00
Alex Qiu
335cf4730e
[STG-1607] Yield finished SSE event instead of silently dropping it (#1846)
# why

Monarch Money reported a bug in the Python SDK (stagehand-python
v3.6.0).

In src/stagehand/_streaming.py, both the sync Stream.__stream__() (line
62-63) and async AsyncStream.__stream__() (line 147-148) have:

```
python
if sse.data.startswith('{"data":{"status":"finished"'):
    break  # ← drops the event without yielding it
```

When the server sends the finished SSE event (which contains success,
message, actions, usage, and messages), the SDK immediately breaks out
of the loop without yielding the event to the caller. This means the
final result payload is silently dropped.

# what changed

The streaming on_event config had `handle: done` for the
`{"data":{"status":"finished"...}}` event. Stainless generates this as a
bare break, which exits the SSE loop without yielding the event –
silently dropping the final result payload (success status, message,
actions, usage, and messages) from every streaming response.

Fix – Changed to `handle: yield` so the finished event is delivered to
callers before the stream terminates. This is safe because the server
explicitly calls `reply.raw.end()` immediately after sending the
finished event (packages/server-v3/src/lib/stream.ts), so the SSE
connection closes right after the yield and the loop exits naturally on
EOF – no hang risk.

# test plan

Regenerate SDKs and confirm fix
2026-03-18 14:26:03 -04:00
tkattkat
63ee247ac6
update search tool (#1834)
# Why

Add Browserbase Search API as the primary search tool for agents (`POST
/v1/search`), leveraging the Browserbase API key users already have
configured. Brave Search remains fully supported as a backwards
compatible fallback for existing users with `BRAVE_API_KEY` set.

# What Changed

- **Browserbase Search tool**: New search tool powered by the
Browserbase Search API, enabled via `useSearch: true` in
`agent.execute()`.
- **Brave Search (backwards-compatible)**: Existing users with
`BRAVE_API_KEY` in their environment continue to get the search tool
automatically with no code changes required.
- **Priority**: `useSearch: true` with a Browserbase API key takes
precedence. If not set, falls back to Brave if `BRAVE_API_KEY` is
present.
- **Validation**: If `useSearch: true` is set without a valid
Browserbase API key, a clear error is thrown at preparation time (before
the agent loop starts).
- **Separate files**: `browserbaseSearch.ts` and `braveSearch.ts` keep
the implementations cleanly isolated.


```typescript
const agent = stagehand.agent({ mode: "hybrid" });

const result = await agent.execute({
  instruction: "use the search tool to find me the capital of france",
  useSearch: true,
});
```

# Test Plan

- [x] Run agent with `useSearch: true` and a valid `BROWSERBASE_API_KEY`
— Browserbase search tool should return results
- [x] Run agent with `useSearch: true` and no Browserbase API key —
should throw `MissingEnvironmentVariableError`
2026-03-16 16:06:30 -07:00
tkattkat
2402a3c4d5
Add support for passing custom headers in clientOptions (#1817)
# why

Allow users to pass custom headers in their LLM calls

# what changed

Add headers to the model.ts types 

# test plan


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds `headers` support to `ClientOptions` so clients can send custom
HTTP headers with every provider request. Useful for auth tokens or
routing hints without changing global config.

- **New Features**
- Added `headers?: Record<string, string>` to `ClientOptions` in
`packages/core/lib/v3/types/public/model.ts`; headers are sent with each
request.
  - No breaking changes; default behavior is unchanged.

<sup>Written for commit 424dc1af74da82364f752f3976182f8aafc3f6ed.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1817">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-03-12 15:21:00 -07:00
Shrey Pandya
687d54adda
feat(cli): add --context-id and --persist to browse open (#1816)
## Summary
- Adds `--context-id <id>` and `--persist` flags to `browse open` so
agents can load/persist browser state (cookies, localStorage, etc.)
across Browserbase sessions using Contexts
- Validates edge cases: `--persist` requires `--context-id`,
`--context-id` requires remote mode, context change triggers daemon
restart

## Usage
```bash
# Load a context (read-only — state not saved back)
browse open https://app.com --context-id ctx_abc123

# Load and persist changes back on session end
browse open https://app.com --context-id ctx_abc123 --persist
```

## How it works
1. `browse open --context-id` writes context config to
`/tmp/browse-{session}.context`
2. The daemon reads this file during browser initialization and passes
it through as `browserbaseSessionCreateParams.browserSettings.context`
3. If a second `browse open` is called with a different context ID, the
daemon is restarted (context is baked into the BB session at creation
time)

Context config uses a temp file (same pattern as `.mode`) because it's
needed at Browserbase session creation time, before the daemon's command
socket is up.

## Test plan
- [x] `browse open https://example.com --context-id <known-id>
--persist` on remote mode — verify session created with context in BB
dashboard
- [x] `browse stop` then reopen with same context — verify state
persists
- [x] Verify context mismatch triggers daemon restart (open with context
A, then open with context B)
- [x] Same context, second open — verify no unnecessary restart
- [x] `browse open https://example.com --context-id <id>` on local mode
— verify clear error
- [x] `browse open https://example.com --persist` without `--context-id`
— verify clear error
- [x] Plain `browse open` (no context flags) — verify no regression
- [x] `cleanupStaleFiles` removes `.context` file on shutdown
- [x] Stale `.context` file from crashed daemon is cleared on next
`browse open` without `--context-id`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-12 13:25:27 -07:00
tkattkat
7dc35f5e25
default to store false for openai use with agent (#1814)
# Why

OpenAI organizations with Zero Data Retention (ZDR) rejects stored
responses from the Responses API (`store: true` is the default when the
AI SDK auto selects it). This causes agent runs to fail

# What Changed

- Set `openai: { store: false }` in `providerOptions` across
`generateText` / `streamText` calls: `v3AgentHandler.ts` (execute +
stream), `handleDoneToolCall.ts`,
- Simplified the existing Gemini `providerOptions` — removed the
conditional `modelId.includes("gemini-3")` check and always pass
`google: { mediaResolution: "MEDIA_RESOLUTION_HIGH" }` since non-Google
providers ignore it.

# Test Plan

- [ ] Run agent in mode with an OpenAI model to confirm no breaking
changes


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Defaulted agent calls to OpenAI to not store responses, preventing
failures for Zero Data Retention orgs. Also simplified Gemini options by
always sending high media resolution.

- **Bug Fixes**
- Set `providerOptions.openai.store` to `false` for agent `generateText`
and `streamText` calls in `v3AgentHandler` (execute + stream) and
`handleDoneToolCall`, avoiding Responses API rejections in ZDR orgs.

- **Refactors**
- Always pass `google: { mediaResolution: "MEDIA_RESOLUTION_HIGH" }` in
`providerOptions`; non-Google providers ignore it. Added a changeset for
a patch release of `@browserbasehq/stagehand`.

<sup>Written for commit a01d8c07fb15080c264aad2998bf047941113920.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1814">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-03-11 17:18:28 -07:00
Shrey Pandya
f8c773898f
fix: browse env inconsistently updates internal state (#1806)
## Summary
- `browse env` showed stale "local" mode after `browse env remote`
- Root cause: `.mode` file was only written during lazy browser init
(`ensureBrowserInitialized`), not at daemon startup. Between daemon
start and first command, `readCurrentMode()` returned `null` and fell
back to hardcoded `"local"`
- Write `.mode` eagerly in `runDaemon()` at startup so it's immediately
available
- Fall back to `desiredMode` instead of `"local"` in the `env` display
handler as a safety net

## Test plan
- [x] Reproduced bug: `browse env remote` → `browse env` showed
`"mode":"local"`
- [x] Verified fix: `browse env remote` → `browse env` now shows
`"mode":"remote"`
- [x] `mode.test.ts` passes (3/3)


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes `browse env` showing stale "local" after `browse env remote`
(STG-1547). The daemon now writes `.mode` at startup, the display falls
back to `desiredMode` until mode is written, and a patch changeset is
added for `@browserbasehq/browse-cli`.

<sup>Written for commit 9661d92de26f60383a1d77c6c636f43aa95089e4.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1806">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-10 12:24:38 -07:00
Shrey Pandya
2abf5b90f1
Make projectId optional for Browserbase sessions (#1800) 2026-03-09 19:39:05 -07:00
Nick Sweeting
a9424ff2eb
fix(CI): fix changeset reference to stale server package name blocking CI (#1801)
# why

# what changed

# test plan


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Corrects the changeset package reference from
`@browserbasehq/stagehand-server` to
`@browserbasehq/stagehand-server-v3` to unblock CI and ensure the
correct package receives the patch release.

<sup>Written for commit 177bc48b84a442ad4e0d9f85c7dffcfc338720de.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1801">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-03-09 18:24:30 -07:00
Shrey Pandya
e38c13b752
[feat]: add browse CLI package (#1793)
## Summary
- Adds the `@browserbasehq/browse-cli` package (`packages/cli`) to the
stagehand monorepo, open-sourcing browser automation for AI agents
- CLI provides stateful browser control via a daemon architecture —
navigation, clicking, typing, screenshots, accessibility snapshots,
multi-tab, network capture, and env switching (local/remote)
- Uses `@browserbasehq/stagehand` as a workspace dependency (bundled
into the CLI binary via tsup)
- Includes full test suite and documentation

## Changes
- `packages/cli/` — all CLI source code, config, tests, and docs
- `pnpm-workspace.yaml` — added `packages/cli` to workspace
- `.github/workflows/ci.yml` — added CLI path filters and build artifact
uploads
- `.changeset/open-source-browse-cli.md` — changeset for initial release
- `pnpm-lock.yaml` — updated lockfile

## Test plan
- [x] CLI builds successfully (`pnpm --filter @browserbasehq/browse-cli
run build`)
- [x] Full monorepo build passes (`turbo run build` — 9/9 tasks)
- [x] `browse --help` and `browse --version` output correctly
- [x] `browse status` returns valid JSON
- [x] Lint passes clean (`pnpm --filter @browserbasehq/browse-cli run
lint`)
- [x] Source verified identical to stagent-cli (only import path
changed)
- [x] Empirically tested Browserbase credential requirements match core
- [ ] Run `pnpm --filter @browserbasehq/browse-cli run test` (requires
Chrome/browser environment)

## Known issues (pre-existing from stagent-cli, not introduced by this
PR)
- Network capture `response.json` always writes `status: 0` — response
metadata from `responseReceived` CDP event is not persisted to
`loadingFinished` handler
- Ref-based `click` command silently ignores
`--button`/`--count`/`--force` flags (coordinate-based `click_xy`
handles them correctly)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-09 17:56:45 -07:00
tkattkat
7817fcc315
[feat]: add configurable timeout to agent tools (#1766) 2026-03-04 18:56:58 -08:00
Shrey Pandya
2f43ffac11
[feat]: add cdpHeaders option for custom CDP connection headers (#1779)
## Summary
- Adds support for CDP (Chrome DevTools Protocol) extra HTTP headers
when connecting to browser sessions
- Passes `extraHTTPHeaders` from the Stagehand config through to the CDP
connection layer
- Warns when `cdpHeaders` provided without `cdpUrl`
- Includes integration test for the new functionality

Related: #1737

Co-authored-by: aditya-silna <aditya@silnahealth.com>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: aditya-silna <aditya@silnahealth.com>
2026-03-03 17:55:52 -08:00
Sean McGuire
521a10e369
[feat]: add page.setExtraHTTPHeaders() (#1774)
# why
- to allow for setting HTTP headers at the page level
# what changed
- added new function `page.setExtraHTTPHeaders()` , which sets HTTP
headers for the CDP session of the page, and all of its child sessions
(eg, iframes)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds page.setExtraHTTPHeaders() to set per-page HTTP headers on all
requests from the page and its iframes. Applies to pipeline sessions
immediately and replays on newly adopted child sessions. Addresses ST
LaurensG- NB: STG-1316.

<sup>Written for commit cf677c219f48302427af40921f02ce90c2399692.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1774">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-03-03 16:54:01 -08:00
Shrey Pandya
6ba0a1db7f
fix: expose Vertex headers in public model config types (#1764)
## Summary
- expose `headers` on `GoogleVertexProviderSettings` in Stagehand public model types
- add a public API type test proving model configs with headers are accepted for google/openai/anthropic
- add a patch changeset

## Context
Runtime already forwards provider options to `createVertex()`, but TypeScript rejected `headers` in model config. This aligns public types with runtime behavior.

## Validation
- `pnpm -C packages/core run typecheck`
- `pnpm -C packages/core run build:esm`
- `pnpm -C packages/core run test:core -- packages/core/dist/esm/tests/unit/public-api/llm-and-agents.test.js`
- `pnpm -C packages/core run test:core -- packages/core/dist/esm/tests/unit/llm-provider.test.js`

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Expose the headers field on GoogleVertexProviderSettings in the public model config types so custom provider headers (e.g., X-Goog-Priority) are accepted without TypeScript errors. Updated the public API type test to cover Vertex headers and align the model config check with the public API style, keeping types consistent with runtime behavior.

<sup>Written for commit bf4907dcf6ee3e1ec2991527a74d554c72867cc9. Summary will update on new commits. <a href="https://cubic.dev/pr/browserbase/stagehand/pull/1764">Review in cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-03-03 10:30:05 -08:00
Sean McGuire
611f43ac8d
[fix]: rm legacy handlePossibleNavigation() (#1761)
# why
- this function was from legacy stagehand which only operated on one
page
- presently, it was only being used to produce a log which:
- at best, misinformed users on whether the page had actually navigated,
and,
  - at worst, resulted in a noisy error log
- the error log would happen if `clickElement()` triggered page closure.
this means that the frame.evaluate() to get the URL would attempt
`.evaluate()` on a frame that no longer existed
# what changed
- removed `handlePossibleNavigation()`
# test plan
- existing tests are fine here

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Removed the legacy handlePossibleNavigation() that tried to detect
navigation by URL and produced misleading logs. This also prevents
errors when clicks close the page and evaluate runs on a non-existent
frame, reducing log noise.

<sup>Written for commit 1d2c3d68280d8a686e806a3b55bbbbb766a1ea25.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1761">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-02-25 19:38:45 -08:00
Shrey Pandya
505e8c6736
[fix]: Add bedrock to provider enum in Zod schemas and OpenAPI spec (#1759)
## Summary
- Adds `"bedrock"` to the `provider` enum in `ModelConfigObjectSchema` and `AgentConfigSchema` (Zod schemas in `packages/core/lib/v3/types/public/api.ts`)
- Regenerates `packages/server/openapi.v3.yaml` via `pnpm gen:openapi`

## Context
Bedrock was added to `AISDK_PROVIDERS` and `LLMProvider` in PRs #1604 and #1617, but the Zod schemas that feed the OpenAPI spec (and ultimately the Stainless-generated SDKs) were never updated. This means the Python/Go/etc. SDK type definitions don't include `"bedrock"` as a valid provider option.

Companion PR in bb/core: https://github.com/browserbase/core/pull/7668

## Test plan
- [x] `pnpm gen:openapi` produces updated spec with `bedrock` in all 4 provider enum locations
- [ ] Stainless picks up the OpenAPI change and regenerates SDKs with `bedrock` in the `provider` literal type

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Add "bedrock" to provider enums in ModelConfigObjectSchema/AgentConfigSchema and regenerate the OpenAPI spec so SDKs accept it and stay in sync with AISDK_PROVIDERS/LLMProvider. Also update AgentType to include "bedrock" to fix a server build type mismatch, and add a patch changeset to publish and unblock Python/Go SDK type generation.

<sup>Written for commit 88e33724c8a08af594dafb86d90fd3fced952520. Summary will update on new commits. <a href="https://cubic.dev/pr/browserbase/stagehand/pull/1759">Review in cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-02-25 15:03:48 -08:00
Nick Sweeting
73905088c5
[STG-1450] Fix Session init failing when no pages are open, falls back to opening about:blank (#1749)
# why

Stagehand API failures were caused on all routes `/act`, `/observe`,
etc. when session init failed because a page was closed. This adds a
fallback to open about:blank so at least the session remains usable
instead of just crashing on init.

# what changed

# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes session init when connecting to a browser with zero pages by
auto-creating an about:blank tab. Keeps Stagehand routes working after
the last page closes and surfaces lint failures via a dedicated
cancellation job. Addresses STG-1450.

- **Bug Fixes**
- Replace waitForFirstTopLevelPage with ensureFirstTopLevelPage: check
for an existing page, wait with timeout, then create about:blank if
none.
- Simplify errors to a TimeoutError with clearer context; improve
logging and add an integration test for zero-page init.

- **CI**
- Run cancellation in a separate job only when lint fails, so failures
are visible instead of marked skipped.

<sup>Written for commit 45ed6dc059d44f07c338dc8f36e72eb0702a2cfd.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1749">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->

<!-- mintlify-editor-comments:start -->
Mintlify
---
0 threads from 0 users in Mintlify

- No unresolved comments
<!-- mintlify-editor-comments:end -->

<!-- mintlify-comment-->

<a
href="https://dashboard.mintlify.com/browserbase/stagehand/editor/session-init-fixes?source=pr_comment"
target="_blank" rel="noopener noreferrer"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://d3gk2c5xim1je2.cloudfront.net/assets/open-mintlify-editor-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://d3gk2c5xim1je2.cloudfront.net/assets/open-mintlify-editor-light.svg"><img
src="https://d3gk2c5xim1je2.cloudfront.net/assets/open-mintlify-editor-light.svg"
alt="Open in Mintlify Editor"></picture></a>

<!-- /mintlify-comment -->
2026-02-24 17:42:42 -08:00
github-actions[bot]
73fd6722f7
Version Packages (#1598)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and the packages will
be published to npm automatically. If you're not ready to do a release
yet, that's fine, whenever you add more changesets to main, this PR will
be updated.


# Releases
## @browserbasehq/stagehand@3.1.0

### Minor Changes

- [#1681](https://github.com/browserbase/stagehand/pull/1681)
[`e3db9aa`](e3db9aa863)
Thanks [@tkattkat](https://github.com/tkattkat)! - Add cookie management
APIs: `context.addCookies()`, `context.clearCookies()`, &
`context.cookies()`

- [#1672](https://github.com/browserbase/stagehand/pull/1672)
[`b65756e`](b65756e9e8)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - add boolean
keepAlive parameter to allow for configuring whether the browser should
be closed when stagehand.close() is called.

- [#1708](https://github.com/browserbase/stagehand/pull/1708)
[`176d420`](176d42002c)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - add
context.setExtraHTTPHeaders()

- [#1611](https://github.com/browserbase/stagehand/pull/1611)
[`8a3c066`](8a3c06600a)
Thanks [@monadoid](https://github.com/monadoid)! - Using `mode` enum
instead of old `cua` boolean in openapi spec

### Patch Changes

- [#1683](https://github.com/browserbase/stagehand/pull/1683)
[`7584f3e`](7584f3e92e)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix:
include shadow DOM in .count() & .nth() & support xpath predicates

- [#1644](https://github.com/browserbase/stagehand/pull/1644)
[`1e1c9c1`](1e1c9c1577)
Thanks [@monadoid](https://github.com/monadoid)! - Fix unhandled CDP
detaches by returning the original sendCDP promise

- [#1729](https://github.com/browserbase/stagehand/pull/1729)
[`6bef890`](6bef89090e)
Thanks [@shrey150](https://github.com/shrey150)! - fix: support Claude
4.6 (Opus and Sonnet) in CUA mode by using the correct
`computer_20251124` tool version and `computer-use-2025-11-24` beta
header

- [#1647](https://github.com/browserbase/stagehand/pull/1647)
[`ffd4b33`](ffd4b335a8)
Thanks [@tkattkat](https://github.com/tkattkat)! - Fix [Agent] - Address
bug causing issues with continuing a conversation from past messages in
dom mode

- [#1614](https://github.com/browserbase/stagehand/pull/1614)
[`677bff5`](677bff5834)
Thanks [@miguelg719](https://github.com/miguelg719)! - Enforce
<number>-<number> regex validation on act/observe for elementId

- [#1580](https://github.com/browserbase/stagehand/pull/1580)
[`65ff464`](65ff464bc1)
Thanks [@tkattkat](https://github.com/tkattkat)! - Add unified variables
support across act and agent with a single VariableValue type

- [#1666](https://github.com/browserbase/stagehand/pull/1666)
[`101bcf2`](101bcf2da8)
Thanks [@Kylejeong2](https://github.com/Kylejeong2)! - add support for
codex models

- [#1728](https://github.com/browserbase/stagehand/pull/1728)
[`0a94301`](0a94301caa)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - handle
potential race condition on `.close()` when using the Stagehand API

- [#1664](https://github.com/browserbase/stagehand/pull/1664)
[`b27c04d`](b27c04d278)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fixes issue
with context.addInitScript() where scripts were not being applied to out
of process iframes (OOPIFs), and popup pages with same process iframes
(SPIFs)

- [#1632](https://github.com/browserbase/stagehand/pull/1632)
[`afbd08b`](afbd08bb63)
Thanks [@pirate](https://github.com/pirate)! - Remove automatic `.env`
loading via `dotenv`.

If your app relies on `.env` files, install `dotenv` and load it
explicitly in your code:

    ```ts
    import dotenv from "dotenv";
    dotenv.config({ path: ".env" });
    ```

- [#1624](https://github.com/browserbase/stagehand/pull/1624)
[`0e8d569`](0e8d5695f6)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue
where screenshot masks were not being applied to dialog elements

- [#1596](https://github.com/browserbase/stagehand/pull/1596)
[`ff0f979`](ff0f9795f3)
Thanks [@tkattkat](https://github.com/tkattkat)! - Update usage/metrics
handling in agent

- [#1631](https://github.com/browserbase/stagehand/pull/1631)
[`2d89d2b`](2d89d2b35c)
Thanks [@miguelg719](https://github.com/miguelg719)! - Add right and
middle click support to act and observe

- [#1697](https://github.com/browserbase/stagehand/pull/1697)
[`aac9a19`](aac9a19bdf)
Thanks [@shrey150](https://github.com/shrey150)! - fix: support
`<frame>` elements in XPath frame boundary detection so `act()` works on
legacy `<frameset>` pages

- [#1692](https://github.com/browserbase/stagehand/pull/1692)
[`06de50f`](06de50ff37)
Thanks [@shrey150](https://github.com/shrey150)! - fix: skip piercer
injection for chrome-extension:// and other non-HTML targets

- [#1613](https://github.com/browserbase/stagehand/pull/1613)
[`aa4d981`](aa4d981e44)
Thanks [@miguelg719](https://github.com/miguelg719)! -
SupportedUnderstudyAction Enum validation for 'method' on act/observe
inference

- [#1652](https://github.com/browserbase/stagehand/pull/1652)
[`18b1e3b`](18b1e3bd2b)
Thanks [@miguelg719](https://github.com/miguelg719)! - Add support for
gemini 3 flash and pro in hybrid/cua agent

- [#1706](https://github.com/browserbase/stagehand/pull/1706)
[`957d82b`](957d82b984)
Thanks [@chrisreadsf](https://github.com/chrisreadsf)! - Add GLM to
prompt-based JSON fallback for models without native structured output
support

- [#1633](https://github.com/browserbase/stagehand/pull/1633)
[`22e371a`](22e371ae4c)
Thanks [@tkattkat](https://github.com/tkattkat)! - Add warning when
incorrect models are used with agents hybrid mode

- [#1673](https://github.com/browserbase/stagehand/pull/1673)
[`d29b91f`](d29b91fa50)
Thanks [@miguelg719](https://github.com/miguelg719)! - Add multi-region
support for Stagehand API with region-specific endpoints

- [#1695](https://github.com/browserbase/stagehand/pull/1695)
[`7b4f817`](7b4f817caf)
Thanks [@tkattkat](https://github.com/tkattkat)! - Fix: zod bug when
pinning zod to v3 and using structured output in agent

- [#1609](https://github.com/browserbase/stagehand/pull/1609)
[`3f9ca4d`](3f9ca4d9ac)
Thanks [@miguelg719](https://github.com/miguelg719)! - Add
SupportedUnderstudyActions to observe system prompt

- [#1581](https://github.com/browserbase/stagehand/pull/1581)
[`49ead1e`](49ead1e1e8)
Thanks [@sameelarif](https://github.com/sameelarif)! - **Server-side
caching is now available.**

When running `env: "BROWSERBASE"`, Stagehand automatically caches
`act()`, `extract()`, and `observe()` results server-side — repeated
calls with the same inputs return instantly without consuming LLM
tokens.

Caching is enabled by default and can be disabled via `serverCache:
false` on the Stagehand instance or per individual call. Check out the
[browserbase blog](https://www.browserbase.com/blog/stagehand-caching)
for more details.

- [#1642](https://github.com/browserbase/stagehand/pull/1642)
[`3673369`](36733691f9)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue
where scripts added via context.addInitScripts() were not being injected
into new pages that were opened via popups (eg, clicking a link that
opens a new page) and/or calling context.newPage(url)

- [#1735](https://github.com/browserbase/stagehand/pull/1735)
[`c465e87`](c465e87ab4)
Thanks [@monadoid](https://github.com/monadoid)! - Supports request
header authentication with connectToMCPServer

- [#1705](https://github.com/browserbase/stagehand/pull/1705)
[`ae533e4`](ae533e4019)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - include
error cause in UnderstudyCommandException

- [#1636](https://github.com/browserbase/stagehand/pull/1636)
[`ea33052`](ea330520a3)
Thanks [@miguelg719](https://github.com/miguelg719)! - Include
executionModel on the AgentConfigSchema

- [#1679](https://github.com/browserbase/stagehand/pull/1679)
[`5764ede`](5764edee7a)
Thanks [@shrey150](https://github.com/shrey150)! - fix issue where
locator.count() was not working with xpaths that have attribute
predicates

- [#1646](https://github.com/browserbase/stagehand/pull/1646)
[`f09b184`](f09b184cc5)
Thanks [@miguelg719](https://github.com/miguelg719)! - Add user-agent to
CDP connections

- [#1637](https://github.com/browserbase/stagehand/pull/1637)
[`a7d29de`](a7d29decee)
Thanks [@miguelg719](https://github.com/miguelg719)! - Improve error and
warning message for legacy model format

- [#1685](https://github.com/browserbase/stagehand/pull/1685)
[`d334399`](d334399004)
Thanks [@tkattkat](https://github.com/tkattkat)! - Bump ai sdk & google
provider version

- [#1662](https://github.com/browserbase/stagehand/pull/1662)
[`44416da`](44416da7ff)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue
where locator.fill() was not working on elements that require direct
value setting

- [#1612](https://github.com/browserbase/stagehand/pull/1612)
[`bdd8b4e`](bdd8b4ee3c)
Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue
where screenshot mask was only being applied to the first element that
the locator resolved to. masks now apply to all matching elements.

## @browserbasehq/stagehand-server@3.6.0

### Minor Changes

- [#1611](https://github.com/browserbase/stagehand/pull/1611)
[`8a3c066`](8a3c06600a)
Thanks [@monadoid](https://github.com/monadoid)! - Using `mode` enum
instead of old `cua` boolean in openapi spec

### Patch Changes

- [#1604](https://github.com/browserbase/stagehand/pull/1604)
[`4753078`](4753078cc9)
Thanks [@miguelg719](https://github.com/miguelg719)! - Enable bedrock

- [#1636](https://github.com/browserbase/stagehand/pull/1636)
[`ea33052`](ea330520a3)
Thanks [@miguelg719](https://github.com/miguelg719)! - Include
executionModel on the AgentConfigSchema

- [#1602](https://github.com/browserbase/stagehand/pull/1602)
[`22a0502`](22a0502e8b)
Thanks [@miguelg719](https://github.com/miguelg719)! - Include vertex as
a supported provider

- Updated dependencies
\[[`7584f3e`](7584f3e92e),
[`1e1c9c1`](1e1c9c1577),
[`6bef890`](6bef89090e),
[`ffd4b33`](ffd4b335a8),
[`677bff5`](677bff5834),
[`65ff464`](65ff464bc1),
[`101bcf2`](101bcf2da8),
[`0a94301`](0a94301caa),
[`b27c04d`](b27c04d278),
[`afbd08b`](afbd08bb63),
[`e3db9aa`](e3db9aa863),
[`0e8d569`](0e8d5695f6),
[`ff0f979`](ff0f9795f3),
[`2d89d2b`](2d89d2b35c),
[`aac9a19`](aac9a19bdf),
[`06de50f`](06de50ff37),
[`aa4d981`](aa4d981e44),
[`18b1e3b`](18b1e3bd2b),
[`957d82b`](957d82b984),
[`b65756e`](b65756e9e8),
[`22e371a`](22e371ae4c),
[`d29b91f`](d29b91fa50),
[`7b4f817`](7b4f817caf),
[`176d420`](176d42002c),
[`3f9ca4d`](3f9ca4d9ac),
[`8a3c066`](8a3c06600a),
[`49ead1e`](49ead1e1e8),
[`3673369`](36733691f9),
[`c465e87`](c465e87ab4),
[`ae533e4`](ae533e4019),
[`ea33052`](ea330520a3),
[`5764ede`](5764edee7a),
[`f09b184`](f09b184cc5),
[`a7d29de`](a7d29decee),
[`d334399`](d334399004),
[`44416da`](44416da7ff),
[`bdd8b4e`](bdd8b4ee3c)]:
    -   @browserbasehq/stagehand@3.1.0

## @browserbasehq/stagehand-evals@1.1.8

### Patch Changes

- Updated dependencies
\[[`7584f3e`](7584f3e92e),
[`1e1c9c1`](1e1c9c1577),
[`6bef890`](6bef89090e),
[`ffd4b33`](ffd4b335a8),
[`677bff5`](677bff5834),
[`65ff464`](65ff464bc1),
[`101bcf2`](101bcf2da8),
[`0a94301`](0a94301caa),
[`b27c04d`](b27c04d278),
[`afbd08b`](afbd08bb63),
[`e3db9aa`](e3db9aa863),
[`0e8d569`](0e8d5695f6),
[`ff0f979`](ff0f9795f3),
[`2d89d2b`](2d89d2b35c),
[`aac9a19`](aac9a19bdf),
[`06de50f`](06de50ff37),
[`aa4d981`](aa4d981e44),
[`18b1e3b`](18b1e3bd2b),
[`957d82b`](957d82b984),
[`b65756e`](b65756e9e8),
[`22e371a`](22e371ae4c),
[`d29b91f`](d29b91fa50),
[`7b4f817`](7b4f817caf),
[`176d420`](176d42002c),
[`3f9ca4d`](3f9ca4d9ac),
[`8a3c066`](8a3c06600a),
[`49ead1e`](49ead1e1e8),
[`3673369`](36733691f9),
[`c465e87`](c465e87ab4),
[`ae533e4`](ae533e4019),
[`ea33052`](ea330520a3),
[`5764ede`](5764edee7a),
[`f09b184`](f09b184cc5),
[`a7d29de`](a7d29decee),
[`d334399`](d334399004),
[`44416da`](44416da7ff),
[`bdd8b4e`](bdd8b4ee3c)]:
    -   @browserbasehq/stagehand@3.1.0

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-02-24 15:23:27 -08:00
Sameel
49ead1e1e8
[STG-1182] cache config (#1581)
# why
Once API-side caching is deployed, the feature will be opt-out. Users
should have a way to disable the cache from the client.

# what changed
Added a `serverCache` parameter to the constructor which adds the
`x-bb-skip-cache` header to all outbound API requests. This parameter is
also present on act, extract, and observe functions to allow for further
configuration.

# test plan



<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds global and per-request control of server-side caching for
act/extract/observe in Browserbase mode. Caching is on by default; you
can opt out. HIT/MISS is logged, and results include cacheStatus (Linear
STG-1182).

- **New Features**
- Added serverCache to V3Options and act/extract/observe options
(default true). Sends browserbase-cache-bypass when false, reads
browserbase-cache-status and SSE cacheHit, logs HIT/MISS, and sets
cacheStatus on ActResult/ExtractResult/ObserveResult. Observe now
returns ObserveResult (Action[] with optional cacheStatus).
- Updated public types and docs. Expanded tests with server integration
checks for bypass header behavior and cache-status semantics (including
HIT on repeated identical requests), plus ActCache variable-key
handling/replay.

- **Bug Fixes**
- Fixed cache miss logging when variables are missing during ActCache
replay, and suppressed cache status logging when a request explicitly
bypasses the cache.

<sup>Written for commit b35d29ea042f1314e7a9cc0366b87ceb9aa29118.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1581">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->






<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the Browserbase API request/response path (new headers, SSE
parsing behavior, and result type shape), which could affect caching
behavior or backwards compatibility for consumers relying on exact
response objects.
> 
> **Overview**
> Adds **server-side caching support for Browserbase API mode** with a
new `serverCache` flag on `V3Options` (instance default) and per-call
overrides in `act()`, `extract()`, and `observe()`.
> 
> `StagehandAPIClient` now sends `browserbase-cache-bypass: true` when
caching is disabled, reads `browserbase-cache-status` (and SSE
`cacheHit`) to log HIT/MISS, and attaches `cacheStatus?: "HIT" | "MISS"`
onto `ActResult` and `ExtractResult`.
> 
> Updates public types/tests, adds new unit tests for `ActCache`
variable-key behavior, and refreshes docs + changeset to announce
server-side caching and the opt-out mechanism.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
b5ce9172a3c6e8c1adfcddceb42fea628852388f. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-02-24 14:58:30 -08:00
Sam F
c465e87ab4
Contrib/1690 (#1735)
# why
From [1690](https://github.com/browserbase/stagehand/pull/1690/changes)
shoutout @huuyafwww !

This enables agent to connect to MCP servers that require Authorization
headers.

# what changed
connectToMCPServer was modified to accept options for
StreamableHTTPClientTransport as arguments.
# test plan
A public api test was added

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Small additive API change that only affects MCP HTTP connection setup;
minimal behavior change unless callers opt into `requestOptions`.
> 
> **Overview**
> `connectToMCPServer` now accepts `requestOptions` and forwards them to
`StreamableHTTPClientTransport`, enabling HTTP connections to MCP
servers that require request-header auth (e.g., `Authorization`).
> 
> Updates the public API type test to include `requestOptions`, adds
docs showing a header-authenticated connection example, and publishes
patch changesets for `@browserbasehq/stagehand` and
`@browserbasehq/stagehand-docs`.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
657b7d5fb2350ec2d171175b366b72b671a7315e. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Enable header-based auth for MCP HTTP connections. connectToMCPServer
now accepts requestOptions and forwards them to
StreamableHTTPClientTransport.

- **New Features**
- Added requestOptions to connectToMCPServer for HTTP transports to pass
headers like Authorization.
- Updated docs with an authenticated MCP server example, expanded the
public API type test, and limited the changeset bump to
@browserbasehq/stagehand (docs package bump removed).

<sup>Written for commit 6cee1df669b8011ebd54a164e3c7d5aee2b16dcd.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1735">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->

---------

Co-authored-by: huuyafwww <huuya.yamauchi@3-shake.com>
Co-authored-by: ci-test <ci-test@example.com>
2026-02-24 10:10:39 -07:00
Shrey Pandya
aac9a19bdf
[fix]: support <frame> elements in XPath frame detection (#1697)
## Summary
- `IFRAME_STEP_RE` regex only matched `iframe` steps, causing `act()` to
fail on legacy `<frameset>` pages where `observe()` returns XPaths
containing `frame[N]` (e.g.
`/html[1]/frameset[1]/frame[4]/html[1]/body[1]/...`)
- Changed regex from `/^iframe(?:\[\d+])?$/i` to
`/^i?frame(?:\[\d+])?$/i` so both `<iframe>` and `<frame>` are
recognized as frame boundaries
- Consolidated the duplicate `IFRAME_STEP_RE` constant (was defined in
both `deepLocator.ts` and `focusSelectors.ts`) into a single shared
export

## Test plan
- [x] Scratchpad repro confirms current regex misses `frame`,
`frame[4]`, `FRAME` — all pass with fix
- [x] 10 new unit tests added to
`snapshot-focus-selectors-utils.test.ts` covering:
- Regex matches `iframe`, `iframe[N]`, `frame`, `frame[N]`
(case-insensitive)
  - Regex rejects `frameset`, `frameset[N]`, `div`, `body`, `html`
- Full XPath parse + walk for frameset page XPaths detects correct frame
boundary
  - Standard iframe XPaths still detected correctly
  - `frameset` is not false-positive detected as a frame boundary
- [x] All 15 tests pass, build + typecheck pass

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds support for <frame> in XPath frame boundary detection so navigation
works on legacy <frameset> pages. iframe and frame steps are treated as
frame boundaries.

- **Bug Fixes**
- Updated regex from /^iframe(?:\[\d+])?$/i to /^i?frame(?:\[\d+])?$/i
to match iframe and frame (case-insensitive) without matching frameset.
- Added focused tests for iframe/frame and frameset XPaths, including
parse + boundary detection; trimmed low-value cases.
  - Added a changeset for a patch release.

- **Refactors**
- Consolidated IFRAME_STEP_RE into a shared export from focusSelectors
and used it in deepLocator.

<sup>Written for commit 4d09b02364a0b4f4bb745c3423fb210b5e0a733a.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1697">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 12:48:33 -08:00
Shrey Pandya
6bef89090e
fix: support Claude 4.6 CUA tool version (#1729)
## Summary
- Claude Opus 4.6 and Sonnet 4.6 require the newer `computer_20251124`
tool type and `computer-use-2025-11-24` beta header for CUA mode
- The previous hardcoded `computer_20250124` is rejected by the
Anthropic API for these models
- Adds conditional tool version selection in
`AnthropicCUAClient.getAction()` — older models are unaffected
- Adds `claude-sonnet-4-6` to model maps (Opus 4.6 was already present)

## Test plan
- [x] Direct Anthropic API calls confirmed both Opus 4.6 and Sonnet 4.6
work with `computer_20251124`
- [x] Stagehand `env: "LOCAL"` CUA mode tested — both models
successfully completed tasks
- [x] Unit tests pass (18/18 in `llm-and-agents.test.ts`)
- [ ] Verify older models (Sonnet 4, Sonnet 4.5, Haiku 4.5) still work
with `computer_20250124`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds CUA support for Claude Opus 4.6 and Sonnet 4.6 by switching to the
computer_20251124 tool and computer-use-2025-11-24 beta. Older models
continue using computer_20250124 to avoid API rejections.

- **Bug Fixes**
- Select tool/beta per model in AnthropicCUAClient.getAction(),
including prefixed names.
- Use new tool/beta for claude-opus-4-6, claude-sonnet-4-6, and
claude-opus-4-5-20251101.
- Add claude-sonnet-4-6 to modelToAgentProviderMap and
AVAILABLE_CUA_MODELS; update unit tests.

<sup>Written for commit 7c0a52c8021a4cffaefa523e72c8a6071abdb5be.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1729">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-02-21 18:03:18 -08:00
Sean McGuire
0a94301caa
[fix]: handle race in close() when using API (#1728)
# why
when running evals at high concurrency (~30) with the stagehand API
enabled in a region far from the client machine, browser sessions die
and the entire eval run hangs indefinitely. the process never exits
because `v3.close()` awaits a promise that never resolves.

the root cause is a race in the shutdown path between:
- the HTTP round-trip of `apiClient.end()` (client → API → client), and
- the CDP websocket close event arriving from the browser

race sequence:
1. `v3.close()` awaits `apiClient.end()` (HTTP request/response)
2. the API requests release immediately, and the browser closes the CDP
websocket
3. the websocket `"close"` event can reach the client before the HTTP
response returns
4. only after the HTTP response returns do we call `ctx.close()` →
`CdpConnection.close()`

if the close event wins the race and fires before step (4), then
`CdpConnection.close()` attaches its one-shot
`"close"` listener too late (the event already happened), so the promise
never resolves.

far regions make this more likely because the HTTP RTT is longer,
increasing the window where the close event can
beat the response.

two additional issues were found in the same shutdown path:
- inflight CDP calls are never rejected when the websocket closes
unexpectedly. pending `send()` promises hang forever alongside
`close()`, which compounds the original hang
- the `_onCdpClosed` transport handler was still registered when
`apiClient.end()` was called. the server-side websocket close would fire
`_onCdpClosed` -> `_immediateShutdown()` -> `close({ force: true })`,
re-entering the close path while the original `close()` was still in
progress

this bug only reproduced reliably with regions that are far away from
the client machine because:
- `apiClient.end()` awaits a full request/response to the hosted API;
higher client-region latency makes that await longer
- during that longer window, the server-side websocket close can arrive
and be processed before `CdpConnection.close()` is called
- if the client machine is close to the region, the timing often works
out and `close()` registers the `"close"` listener in time
# what changed
in`packages/core/lib/v3/understudy/cdp.ts`:
- updated `close()` to have an early return when `this.ws.readyState ===
WebSocket.CLOSED` so that calling `close()` on an already-closed
websocket resolves immediately instead of hanging.
- added `rejectAllInflight(why)`, which is a private method that
iterates the `inflight` map and rejects every pending CDP call with a
`CdpConnectionClosedError`, then clears the entry. this is called from
both the websocket `"close"` and `"error"` handlers in the constructor
- updated the `"close"` and `"error"` handlers to call
`this.rejectAllInflight(why)` before `this.emitTransportClosed(why)` to
make sure all pending promises are rejected when the ws dies

in `packages/core/lib/v3/v3.ts`:
- updated `v3.close()` such that `offTransportClosed` runs _before_
`apiClient.end()`
- this prevents `_onCdpClosed` from firing during the API teardown and
re-entering `close({ force: true })`
# test plan
- added unit tests in `cdp-connection-close.test.ts` which check that:
- `CdpConnection.close()` resolves when the websocket is already closed
  - inflight `send()` calls reject when the websocket is terminated
- added an e2e test in `cdp-connection-close.spec.ts` which:
- terminates the underlying websocket, then calls `v3.close()` and
asserts it resolves
- terminates the websocket with an inflight CDP call and asserts the
pending promise rejects
- added another e2e test in `cdp-close-api-region.spec.ts` which:
- reproduces the full production trigger chain by creating a stagehand
instance with `disableAPI: false` and `region: "ap-southeast-1"`,
  - calls `v3.close()` and asserts it resolves within 30 seconds


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes a shutdown race that caused eval runs to hang when using the
Stagehand API in non-us-west-2 regions. v3.close() now resolves reliably
and inflight CDP requests reject on socket shutdown, addressing Linear
STG-1422.

- **Bug Fixes**
- CdpConnection.close(): return immediately if the WebSocket is already
CLOSED.
- Reject inflight CDP calls on "close"/"error" via new
CdpConnectionClosedError (exported in public error types).
- Unhook transport-close handler before apiClient.end() to prevent
double-close during API teardown.
- Added unit and e2e tests (incl. ap-southeast-1) verifying close
resolves and inflight requests reject.

<sup>Written for commit 699b48a8a75d0b7d33da83d11f7b133ef5673195.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1728">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-02-20 18:59:58 -08:00
tkattkat
65ff464bc1
add variables to agent (#1580)
# Why

Users need a way to pass sensitive data (passwords, API keys, personal
info) to agent executions without exposing the actual values to the LLM.
This also enables reusable agent scripts where variable values can
change without invalidating cached executions.

## Usage

```typescript
const agent = stagehand.agent({
  model: "google/gemini-3-flash-preview",
  mode: "hybrid"
});

await agent.execute({
  instruction: "Log in to the dashboard",
  variables: {
    username: { value: "john@example.com", description: "The user's email address" },
    password: { value: process.env.USER_PASSWORD, description: "The user's password" },
  },
});
```

# What Changed

- Added `variables` option to `agent.execute()` accepting
`Record<string, { value: string | number | boolean; description: string
}>`
- LLM sees variable names and descriptions in system prompt, uses
`%variableName%` syntax in tool calls
- Variable substitution implemented in `act`, `type`, `fillForm`, and
`fillFormVision` tools
- Sensitive values never returned to LLM in tool outputs
- Cache keys use variable names only (not values) - changing values
won't invalidate cache
- Feature requires `experimental: true`, not supported in CUA mode
- Shared utilities in `agent/utils/variables.ts`

# Test Plan

- [x] Test agent execution with variables for login flow
(username/password)
- [x] Verify LLM correctly uses `%variableName%` syntax in tool calls
- [x] Confirm sensitive values don't appear in LLM responses/tool
outputs
- [x] Test cache hit when variable values change but names stay same
- [x] Verify error thrown when `variables` used without `experimental:
true`
- [x] Verify error thrown when `variables` used with CUA mode

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Add first-class variables to agent.execute and act with a single
VariableValue type. Use %name% placeholders that are swapped at runtime,
never shown to the LLM, and cached by variable names only.

- **New Features**
- Unified API: Variables = Record<string, VariableValue> where
VariableValue = string | number | boolean | { value; description? };
shared utils: resolveVariableValue, substituteVariables,
flattenVariables.
- Prompt/tool UX: System prompt adds a variables section (names,
optional descriptions, usage and example); tool inputs list available
variables; %name% supported in act, type, fillForm, and fillFormVision
(hybrid included).
- Runtime safety: Substitution only during execution; logs/replay keep
original %tokens%; tool outputs never include sensitive values.
- Cache: Keys include variable names only; replay substitutes current
values across act/fillForm steps.
- Guardrails/docs: Requires experimental: true; blocked in CUA mode with
clear errors; docs updated for agent variables and act reference.

<sup>Written for commit 02a9cd584d37dabe20d2f8a624eae88ed044c282.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1580">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->

---------

Co-authored-by: Shrey Pandya <shrey@browserbase.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 14:25:43 -08:00
Sean McGuire
176d42002c
[feat]: add context.setExtraHTTPHeaders() (#1708)
# why
- to enable users to set headers to be included in every request created
by every page within the `context`
# what changed
- added a new function `context.setExtraHTTPHeaders()` which calls the
`Network.setExtraHTTPHeaders` CDP command on all existing sessions
- we also call `Network.setExtraHTTPHeaders` with the user defined
headers whenever we attach to a new target (via `onAttachedToTarget`)
- if there is a rejected promise when headers are being set, a
`StagehandSetExtraHTTPHeadersError` will be thrown
# test plan
- added an e2e test to confirm that headers are being correctly set by
listening to `Network.requestWillBeSent` and inspecting headers
- also added unit tests to confirm that the custom error is being thrown
correctly when promises reject

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds context.setExtraHTTPHeaders() to set default HTTP headers on every
request from all pages in a context. Implements STG-1411; applies to
current sessions and newly attached targets after Network.enable.

- **New Features**
- New API: context.setExtraHTTPHeaders(headers) sends Network.enable
then Network.setExtraHTTPHeaders to each active session; repeats on
attach for new targets.
- Public error: StagehandSetExtraHTTPHeadersError with per-session
failure details.
- Tests: e2e verifies navigation headers; unit tests cover multi-session
send and error reporting; public error type is exported.

<sup>Written for commit 21606892ebf693f7798d3d4fea695c1563caa16f.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1708">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-02-20 13:40:56 -08:00
tkattkat
e3db9aa863
[feat]: add cookie related getters & setters (#1681)
# Why

Browser automation workflows frequently need to manage authentication
state, persist sessions across runs, and handle cookie-based features.
Currently, users have no direct API to read, write, or clear cookies in
Stagehand, forcing workarounds through raw CDP commands or page-level
JavaScript injection.

# What Changed

## Cookie Management APIs

Added cookie management methods that mirror the familiar Playwright
BrowserContext API:

**On `context` instance:**
- `context.cookies(urls?)` — Get all browser cookies, optionally
filtered by URL(s)
- `context.addCookies(cookies)` — Set one or more cookies in the browser
context
- `context.clearCookies(options?)` — Clear all cookies or selectively by
name/domain/path (supports RegExp)

### Types Added
- `Cookie` — Cookie object returned by the browser
- `CookieParam` — Parameters for setting a cookie (supports `url` OR
`domain`+`path`)
- `ClearCookieOptions` — Filter options for selective cookie clearing

# Test Plan

## Cookie Management
- [ ] `context.cookies()` returns all cookies when no URLs provided
- [ ] `context.cookies(url)` filters cookies by single URL
- [ ] `context.cookies([url1, url2])` filters cookies by multiple URLs
- [ ] `context.addCookies([...])` successfully sets cookies
- [ ] `context.addCookies()` validates cookie params (requires url OR
domain+path)
- [ ] `context.addCookies()` rejects `sameSite: "None"` without `secure:
true`
- [ ] `context.addCookies()` throws on browser rejection (checks CDP
success flag)
- [ ] `context.clearCookies()` clears all cookies atomically via single
CDP call
- [ ] `context.clearCookies({ name: "session" })` clears by exact name
- [ ] `context.clearCookies({ domain: /\.example\.com/ })` clears by
regex
- [ ] Selective clear only deletes matching cookies, leaves others
untouched

---------

Co-authored-by: Sean McGuire <seanmcguire1@outlook.com>
2026-02-20 11:06:22 -08:00
Shrey Pandya
06de50ff37
[fix]: skip piercer injection for chrome-extension:// and non-HTML targets (#1692)
## Summary

Navigating to a PDF URL crashes Chrome's built-in PDF viewer because the piercer script gets injected into the PDF viewer's `chrome-extension://` target.

The fix adds an `isNonWebTarget()` predicate (alongside existing `isTopLevelPage()`) that uses an **allowlist** — only `"page"` and `"iframe"` targets receive piercer injection. All other target types (workers, background pages, browser, webviews, worklets, etc.) are resumed but skipped. Additionally, `chrome-extension://` and `chrome://` URLs are always skipped even if the type is `"page"`, since Chrome's PDF viewer reports as `type: "page"` with a `chrome-extension://` URL.

This is future-proof: Chrome currently has [14 target types](https://chromium.googlesource.com/chromium/src/+/main/content/browser/devtools/devtools_agent_host_impl.cc) and adding new ones won't require updating a blocklist.

## Root Cause

`onAttachedToTarget()` only filtered out worker targets. Chrome's PDF viewer (`chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai`) gets auto-attached as a `type: "page"` target — the piercer script patches `Element.prototype.attachShadow` and walks the DOM inside this extension, corrupting the viewer.

## Test plan

- [x] Open a PDF URL (e.g. `https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf`) with Stagehand — verify it loads without error
- [x] Verify normal page navigation still works after viewing a PDF
- [x] Verify OOPIF (cross-origin iframe) targets still get piercer injection
- [x] Verify shadow DOM piercing works (open + closed shadow roots tracked and accessible)

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-02-20 00:11:44 -05:00
Miguel
d29b91fa50
Multi-region stagehand api support (#1673)
# why
Server-side multi-region support enabled for all Browserbase regions:
- `us-west-2` (default)
- `us-east-1`
- `eu-central-1`
- `ap-southeast-1`

# what changed
Added multi-region routing to the Stagehand API client so requests use
the endpoint that matches the Browserbase session’s region. Updates
OpenAPI and docs, adds tests, and fixes STAGEHAND_API_URL handling.
### **New Features**
- Route API calls by session region via
REGION_API_URLS/getApiUrlForRegion; supports us‑west‑2 (default),
us‑east‑1, eu‑central‑1, ap‑southeast‑1.
- Store the session region in the client; remove the non–us‑west‑2
restriction.
- Add BrowserbaseRegion schema/type; unit tests for region→URL and /v1
suffix; integration tests verify non‑default regions return available:
true.
  - OpenAPI adds regional servers and shared BrowserbaseRegion schema.
- Docs: add region/endpoint table, setup examples, mismatch error
guidance, and the disableAPI option.

### **Bug Fixes**
  - Ensure STAGEHAND_API_URL resolves to exactly one /v1.
  - Update SDK error messages to reference disableAPI.
- Fix OpenAPI table rendering by removing blank lines between markdown
table rows.

# test plan


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds multi-region routing to the Stagehand API client so requests use
the API that matches the Browserbase session’s region. Updates v3
OpenAPI/docs and tests; honors and normalizes STAGEHAND_API_URL; v2 docs
changes remain reverted.

- New Features
- Route API calls by session region (us-west-2 default, us-east-1,
eu-central-1, ap-southeast-1); removed the us‑west‑2‑only restriction.
- Add REGION_API_URLS/getApiUrlForRegion and store session region; v3
OpenAPI adds regional servers and a shared BrowserbaseRegion schema;
docs add region table, mismatch guidance, and disableAPI examples.

- Bug Fixes
- Normalize STAGEHAND_API_URL to include exactly one /v1;
getApiUrlForRegion always returns a /v1 URL; SDK error text references
disableAPI.
- Fix OpenAPI rendering (literal scalar description, quoted versions)
and preserve table formatting in generated YAML.
- Tests: add unit and integration coverage for regions; use try/finally
to prevent session leaks; remove unused env scaffolding; use
LOCAL_BROWSER_BODY in multiRegion tests for CI stability.

<sup>Written for commit cbdaf178fb35d1658b56a00697c2b06cb953a295.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1673">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->

---------

Co-authored-by: Chromie <miguel@browserbase.com>
Co-authored-by: Chromie Bot <chromie@browserbase.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-19 12:28:33 -08:00
Chris Read
957d82b984
[fix]: Add GLM to prompt-based JSON fallback for structured outputs (#1706)
GLM-4-Flash (Zhipu AI) doesn't support OpenAI's native structured
outputs, causing 500s on extract. Refactors the per-model boolean checks
into an extensible pattern list and adds "glm" to it.

# why

# what changed

# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Added GLM models to the prompt-based JSON fallback for structured
outputs to prevent 500s on extract for GLM-4-Flash. Addresses STG-1470
and includes a changeset for a patch release.

- **Refactors**
- Replace per-model flags with an extensible pattern list (deepseek,
kimi, glm) to trigger prompt-based JSON fallback when response_model is
used.

<sup>Written for commit 9ac8d7f991575e0d1a4bbea85b40dd86d621ff4b.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1706">Review in
cubic</a></sup>

<!-- End of auto-generated description by cubic. -->
2026-02-18 20:28:03 -08:00