343 Commits

Author SHA1 Message Date
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
Sean McGuire
93bbf026e9
[chore]: add error cause lint rule (#1745)
# why
- to enforce best practices in error handling by requiring the cause of
a given error to be included in the error that gets thrown
# what changed
- added the `preserve-caught-error` lint rule
- updated calls that were not preserving caught errors
- also bumped eslint version & typescript eslint for compatibility with
the new rule

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds an ESLint rule to require preserving the original error when
rethrowing, updates code to pass error causes, and fixes related linting
issues. This improves debugging by linking errors via the cause option.

- **Dependencies**
  - ESLint → 10.0.2
  - @eslint/js → 10.0.1
  - typescript-eslint → 8.56.1

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

<!-- End of auto-generated description by cubic. -->
2026-02-24 14:03:33 -08:00
Sean McGuire
1e7b7e98e5
[docs]: revert openapi spec gen changes (#1746)
# why
- correctly implements what #1739 aimed to do

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Reverts the OpenAPI multi-region changes and returns the spec to a
single API endpoint. Cleans up generator logic and YAML formatting with
no runtime impact.

- **Refactors**
- Remove regional server URLs; keep only
https://api.stagehand.browserbase.com.
- Delete multi-region docs and markdown table from the OpenAPI
description.
- Drop table-formatting regex in the generator; keep version quoting
only.
  - Normalize long YAML descriptions to single-line strings.

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

<!-- End of auto-generated description by cubic. -->
2026-02-24 12:35:17 -08:00
tkattkat
6b255e4c41
Update docs to remove zod pinning (#1743)
# why

we recommend people pin their zod version in docs which is no longer
necessary

# what changed

removed v3 pinning from zod imports in docs 
update tool import to import from stagehand 
# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Remove zod v3 pinning across docs and examples by importing from zod.
Switch tool imports to @browserbasehq/stagehand and update .cursorrules
and claude.md examples to match the current API.

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

<!-- End of auto-generated description by cubic. -->
2026-02-24 10:46:04 -08:00
Nick Sweeting
4f8d2d5d85
Fix Windows SEA build (#1734)
# why

# what changed

# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes the Windows SEA build and cross‑platform path resolution
(including when run via tsx). CI builds, launches, and smoke‑tests
Linux, macOS, and Windows binaries (x64/arm64); CJS/ESM outputs are
stable.

- Bug Fixes
- Reusable SEA build workflow with a full OS/arch matrix (incl. Ubuntu
24.04 ARM and Windows 11 ARM), same‑arch launch check against /healthz,
selective artifact upload, and an include_sourcemaps toggle (dev/test
only; releases exclude sourcemaps).
- Centralized runtimePaths helpers across core/server/evals/docs to
replace import.meta/fileURLToPath, fix tsx path resolution, normalize
absolute paths, and correct supervisorClient CLI resolution and Windows
spawning.
- Tooling: split DOM script builds into four Turbo tasks for Windows;
switch to in‑process esbuild and Node‑invoked turbo/postject; stabilize
CJS/ESM via tsc emits plus small CJS wrappers; refine tsconfig includes;
add default NODE_ENV/BB_ENV in server env.

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

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches build/CI and packaging code (SEA generation, path resolution)
across multiple packages, so failures could break releases or CI on
specific platforms despite being largely tooling-focused.
> 
> **Overview**
> Fixes cross-platform SEA building by moving `build-server-sea` to a
reusable workflow with a multi-OS/arch matrix (including ARM runners),
optional artifact/caching inputs, selective artifact upload, and a
same-arch smoke test that boots each binary and hits `/healthz`.
> 
> Standardizes path/root resolution via new `runtimePaths` helpers
(core/server/evals/docs) and replaces ad-hoc
`fileURLToPath(import.meta.url)`/`__dirname` usage across scripts,
tests, and `supervisorClient` (also tightening CLI resolution and SEA
detection).
> 
> Simplifies build/tooling: core CJS/ESM builds now rely on `tsc` emits
plus small CJS wrapper entrypoints (dropping esbuild bundling of
core/tests), DOM script generation is split into separate Turbo tasks,
server SEA build switches to in-process `esbuild` and Node-invoked
`turbo`/`postject`, and server env config now provides default
`NODE_ENV`/`BB_ENV` values.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
2e4a07a6d0b54eddb7fea10d079c8062ecba1d6b. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-02-24 10:39:45 -08:00
Sameel
00898af83b
[STG-1447] stagehand caching doc (#1742)
# why

# what changed

# test plan


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Added a Note to the caching best-practices doc explaining server-side
caching when running env: "BROWSERBASE" (STG-1447). It’s enabled by
default for act(), extract(), and observe(); repeated calls with the
same inputs return instantly, and you can disable it via serverCache:
false or per call, with a blog link for details.

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

<!-- End of auto-generated description by cubic. -->
2026-02-24 09:42:29 -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
Chromie
33ca51d465
Revert OpenAPI spec documentation changes from #1673 (#1739)
Reverts the documentation-related changes to the OpenAPI spec from PR
#1673, while preserving the functional multi-region server endpoints.

Changes reverted:
- Restored the info.description to the original format
- Simplified server descriptions back to "Production Browserbase Cloud
API"
- Removed multi-region documentation from the spec description

# why

# what changed

# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Reverts the OpenAPI spec docs changes from #1673 to restore a concise
info.description and simpler server labels, with no endpoint or behavior
changes.

- **Refactors**
- Removed the multi-region docs section and the local `disableAPI` note;
kept brief auth/SSE guidance.
- Simplified the default server description to "Production Browserbase
Cloud API"; regional servers remain labeled by region.
- No functional changes; multi-region endpoints and routing remain the
same.

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

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

---------

Co-authored-by: Chromie Bot <chromie@browserbase.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Miguel <36487034+miguelg719@users.noreply.github.com>
2026-02-23 22:29:30 -08:00
Sean McGuire
f023257f97
[chore]: rm noisy debug log (#1731)
# why
- these logs dont add much value if any
- they also didn't use the correct logging context, so they get logged
no matter what `verbose` level is defined in the stagehand constructor
# what changed
- removed the noisy logs


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Removed noisy debug logs in deepLocator that ignored the configured
verbose level. This reduces log spam during frame resolution with no
behavior changes.

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

<!-- End of auto-generated description by cubic. -->
2026-02-22 12:50:15 -08: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
Miguel
73bd741cee
chore: consolidate test directories in packages/core (#1723) 2026-02-20 17:55:07 -08:00
Nick Sweeting
6329982da2
Fix typechecking for core/tests, fix SEA build for windows, speed up CI (#1721)
# why

# what changed

# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes TypeScript across core tests/scripts, finalizes the default
export/CLI, and makes the SEA build reliable on Windows. CI splits build
and lint, OpenAPI generation no longer runs Prettier, and builds run in
parallel across packages for faster pipelines.

- **Bug Fixes**
- Stricter TS across tests/scripts (tsconfig includes tests + CLI, added
@types/jsdom, switched to playwright-core); tightened types (child-frame
probes, DocumentReadyState, model utils, source-map Raw types); fixed
OpenAPI typing; removed cross-package imports in server tests; added
default-export parity test.
- Default export and CLI fixed: introduced StagehandDefault mirroring
named exports; ESM/CJS indices now export default; corrected
package.json CLI paths/types.
- SEA build works on Windows: build scripts use pnpm.cmd with better
spawn error handling.
- List parsing now works from raw source across core/server/evals and
maps cleanly to dist outputs.

- **Refactors**
- CI split into separate Build and Lint jobs; lint cancels the workflow
on failure; optional Turbo cache restore; discovery/runner steps no
longer depend on the build job.
- Parallelized builds: DOM script generators run concurrently; ESM/CJS
builds and server/evals build tasks run in parallel; tuned Turbo inputs
to reduce noisy rebuilds and improve caching.

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

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

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2026-02-20 17:09:39 -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
ef58a017d7
[docs]: add Google Vertex AI configuration (#1696)
## Summary
- Adds a **Google Vertex** tab to the First Class Models section in the v3 models docs
- Documents the `experimental: true` requirement, model object format (`project`, `location`, `googleAuthOptions`), and service account credentials setup
- Adds Google Vertex to the API key troubleshooting table

This was requested in Discord — the `vertex/` provider is fully supported in code but was missing from documentation.

## Test plan
- [ ] Verify the new tab renders correctly on the docs site
- [ ] Confirm code snippet matches the accepted `GoogleVertexProviderSettings` type

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

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Added Google Vertex configuration to v3 models docs. New tab with TS example using vertex/gemini-3-flash-preview, service account setup, and required fields (project, location, googleAuthOptions) with experimental: true; updated troubleshooting to say “Vertex” and point to service account credentials.

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

<!-- End of auto-generated description by cubic. -->
2026-02-20 13:37:14 -05: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
Nick Sweeting
2e9e59c377
Add proper logging messages for shutdown supervisor (#1717)
# why

# what changed

# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Add clear shutdown logs to the supervisor and pass reason strings
through all cleanup paths. Stderr is now inherited so logs are visible
for local Chrome and Browserbase sessions.

- **New Features**
- Pass and log cleanup reasons for local Chrome and Browserbase
(lifeline complete vs crash/killed, PID polling).
  - Log deletingUserDataDir in local shutdown.
  - Inherit supervisor stderr to surface crash/cleanup messages.

- **Refactors**
  - Broaden .prettierignore to exclude all openapi.*.yaml files.

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

<!-- End of auto-generated description by cubic. -->
2026-02-19 16:22:39 -08:00
Nick Sweeting
f646d9b576
Evals pathfix (#1716)
# why

# what changed

# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixed WebTailBench evals to resolve dataset paths under ESM by deriving
the module directory from import.meta.url when __dirname isn’t
available. Also tightened .prettierignore to only exclude
packages/server/openapi.v3.yaml for consistent formatting.

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

<!-- End of auto-generated description by cubic. -->
2026-02-19 16:02:55 -08:00
Nick Sweeting
12cef0b1cf
lint fixes (#1715)
# why

# what changed

# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixed lint and formatting in the ESM build script and the server OpenAPI
spec to match project style rules. No runtime or API changes.

- **Refactors**
- Indented import/export lines in build-esm.ts for the generated
index.d.ts.
- Normalized formatting in packages/server/openapi.v3.yaml (folded
descriptions, spacing).

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

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

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-02-19 15:43:08 -08:00
Nick Sweeting
50a6f574a3
Speed up turbo, package.json scripts, and CI configuration (#1712)
# why

# what changed

# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Speed up builds and tests by upgrading Turborepo, tightening cache keys,
and refactoring scripts to run from compiled dist (ESM/CJS). CI is
faster and more reliable, with ESM-first SEA builds for the server.

- **Refactors**
- Upgrade Turborepo to 2.8.10 and rewrite turbo.json with explicit
inputs/outputs for better caching.
- Stronger Turbo cache keys in CI (lockfiles + workspace + package.json
+ turbo.json + commit), workflow-scoped concurrency, and a 60s session
create timeout.
- Standardized CI via a composite setup action; build now runs before
lint.
- Build/test scripts resolve the repo root via fileURLToPath; tests run
from compiled dist; add Vitest config for CJS; CJS builds include
sourcemaps.
- Server: ESM-first SEA build and split server build into dist vs SEA
steps with a new build:server:dist script.
- Unified test scripts across packages; top-level test runs all suites,
and evals tests support source or dist CLI via --cli.

- **Migration**
  - Use Node 20.19+ or 22.12+ (enforced in core).
  - Run pnpm install to pick up the Turbo upgrade.
- Build before tests: pnpm -w build. For SEA tests, also run pnpm -w
--filter=@browserbasehq/stagehand-server run build:sea:esm.

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

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

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2026-02-19 15:35:37 -08:00
Nick Sweeting
d1ca2c64b6
Fix supervisor and supervisorClient behavior to support usage in SEA binary (#1711)
# why

# what changed

# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Make the shutdown supervisor work inside the SEA server binary and
improve cleanup reliability. Use a stdin lifeline and a CLI/SEA
entrypoint so local Chrome and Browserbase sessions are cleaned up when
the parent dies or Chrome exits.

- **Bug Fixes**
- Supervisor uses stdin as the lifeline; no IPC or “ready” handshake;
idempotent cleanup.
- Added Stagehand CLI and SEA entrypoint to run the supervisor via
--supervisor and a single --supervisor-config JSON arg (includes
parentPid).
- SupervisorClient re-execs the SEA binary in SEA or uses the CLI
outside SEA; spawns with stdin as the lifeline.
- Safer kill flow: SIGTERM then SIGKILL (7s), treat only ESRCH as
“gone,” and never re-kill once confirmed dead; PID polling triggers
cleanup when Chrome exits.
  - Browserbase cleanup requests session release on shutdown when used.
- Added SEA integration tests covering local Chrome cleanup, supervisor
lifecycle, and Browserbase session release.

- **Migration**
- Removed keepAlive from ShutdownSupervisorConfig; only start the
supervisor when keepAlive=false.
- ShutdownSupervisorHandle no longer exposes ready; there is no
handshake—start and continue.

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

<!-- End of auto-generated description by cubic. -->
2026-02-19 15:29:26 -08:00
Nick Sweeting
11cd018595
Fix flaky tests and library timing behavior (#1713)
# why

# what changed

# test plan


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Stabilizes multi-click and iframe tests and hardens timing in the
library. Uses event-based double-click checks, increases CI timeouts,
and simplifies the Playwright config.

- **Bug Fixes**
- Double-click tests use an inline data-URL fixture and verify
click/dblclick with detail=2 for determinism.
- waitForChildFrame matches the expected child URL and probes frames
(href + readyState) with clearer debug and errors.
- Click events are dispatched in a pipelined burst to reduce inter-click
jitter for multi-clicks.
- First top-level page wait is 5s locally and 30s in CI (override via
STAGEHAND_FIRST_TOP_LEVEL_PAGE_TIMEOUT_MS).

- **Refactors**
- Simplified Playwright testDir resolution with import.meta.url and
removed the env reporter.
- Example script adds explicit 30s action timeout and ensures Stagehand
closes in a finally block.

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

<!-- End of auto-generated description by cubic. -->
2026-02-19 14:51:53 -08: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
Miguel
39d38f7a65
Fix executionModel propagation on agent (#1698)
# why
When passing an `executionModel` to agent (for LLM-powered tools -- act,
extract...) from a different provider than the one for the model
provided in the Stagehand constructor, or in the `AgentConfig`, API keys
are not propagating properly and causing errors in non-local
environments

The root cause is the execution model was being passed as a string, and
its respective API key doesn't propagate if explicitly defined.
Unnoticeable if the API key for each provider is exported or in `.env`,
since we automatically pull when none is specified. This issue doesn't
express itself if the different models share the same provider.

# what changed

# test plan



<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fix executionModel propagation by accepting either a string or
AgentModelConfig across agent tools and the handler, and normalizing
model names for correct resolution, API key usage, and telemetry.

- **Refactors**
- Added extractModelName; used in resolveModel and telemetry model
logging.
- Updated act, extract, fillForm tools, tool options, and V3AgentHandler
to accept executionModel: string | AgentModelConfig.
- In V3, pass executionModel (or fallback to model) directly to the
handler and use extractModelName for the logged model.
- Added tests covering tool propagation, fallback logic, and model utils
(extractModelName, resolveModel).

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

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

---------

Co-authored-by: tkattkat <tkat@tkat.net>
2026-02-19 10:41:34 -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
Miguel
51764e9145
Add webtailbench to external benchmarks (#1688) 2026-02-18 20:20:53 -08:00
Sean McGuire
ae533e4019
[fix]: expose error cause in UnderstudyCommandException (#1705)
# why
- to make the error more informative & actionable
# what changed
- moved `UnderstudyCommandException` into `sdkErrors.ts`
- added `cause` param
- updated callsites in `actHandlerUtils.ts` to include cause   
# test plan
- added unit tests in `understudy-command-exception.test.ts`

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Expose the original error as the cause in UnderstudyCommandException to
preserve stack traces and context during Understudy actions, with
type-safe handling for non-Error values. Addresses Linear STG-1310.

- **Bug Fixes**
  - Add cause to UnderstudyCommandException (extends StagehandError).
- Pass original error as cause across handlers; safely compute
message/stack for non-Error values.
- Prevent double-wrapping by rethrowing existing
UnderstudyCommandException in performUnderstudyMethod.
- Expose UnderstudyCommandException in the public API and add unit tests
for name, message, cause, and stack.

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

<!-- End of auto-generated description by cubic. -->
2026-02-18 18:09:39 -08:00
Sean McGuire
04da404f21
[fix]: resolve supervisor.js via import.meta.url (#1702)
# why
- the `supervisorClient` was unable to find the `supervisor.js` file
after we migrated to esm
- the old code preferred `__dirname` over `import.meta.url`, but tsx
polyfills `__dirname` in esm mode and it can resolve to the wrong
directory
# what changed
- use `import.meta.url` instead of `__dirname`


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes supervisor script resolution in ESM by using import.meta.url,
preventing failures when __dirname is polyfilled by tsx.

- **Bug Fixes**
  - Resolve supervisor.js using import.meta.url instead of __dirname.
- Improve missing-script error message to include the searched
directory.

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

<!-- End of auto-generated description by cubic. -->
2026-02-18 13:38:39 -08:00
Nick Sweeting
a091affd2c
[chore]: add .js to the end of all imports (#1700)
# why

- removes the need to append .js to all imports during esm build process
- aligns us with the default standard for esm / esbuild js projects that
also need to support cjs
- this allows us to seamlessly support ESM, CJS, and TSX with no
remapping needed

# what changed

# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Standardized all internal imports and re-exports to include .js
extensions to enable native ESM resolution, while keeping CJS and TS
working without path remapping. Updated examples to use explicit
index.js entrypoints and environment-driven config for easier local
runs.

- **Refactors**
- Appended .js to all relative imports and barrel exports across core,
v3 agent, DOM runtimes/locator scripts, caches, handlers, external
clients, and index files.
- Switched examples to ../lib/v3/index.js, fixed nested re-export paths,
and added env-based config (BROWSERBASE_API_KEY, BROWSERBASE_PROJECT_ID,
MODEL_API_KEY) passed into Stagehand/model.
  - Updated dotenv to ^17.3.1 in dev deps. No public API changes.

- **Migration**
  - Most users importing from package entry points: no changes.
- If importing internal files locally (e.g., examples or custom
integrations), include .js in paths and prefer index.js for directories.

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

<!-- End of auto-generated description by cubic. -->
2026-02-18 12:19:15 -08:00
tkattkat
7b4f817caf
Fix: undefined def when using structured outputs in agent with zod pi… (#1695)
# why

There is currently a bug isolated specifically to people using zod
pinned to v3 with structured output in agent resulting in a zod error
"undefined def"

# what changed

We now ensure any output schema passed in is correctly normalized to v3
or v4 depending on what version is being used through our zodcompat
factory

# test plan

tested the failing scenario to make sure it is addressed 

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes the “undefined def” error when agents use structured outputs with
Zod pinned to v3 by building the “done” tool schema with the same Zod
version as the user’s schema.

- **Bug Fixes**
- Use getZFactory to create schemas with the user’s Zod version (v3 or
v4).
- Build the base done schema via the factory and safely extend with
outputSchema.
- Generate output instructions using StagehandZodSchema types to avoid
v3/v4 mixing.
  - Add changeset to publish a patch release.

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

<!-- End of auto-generated description by cubic. -->
2026-02-18 12:00:06 -08:00
Shrey Pandya
21e1db5745
[docs]: add missing CUA models to docs (#1693)
## Summary
- Added 5 missing CUA models to all documentation pages: `anthropic/claude-opus-4-5-20251101`, `anthropic/claude-opus-4-6`, `google/gemini-3-flash-preview`, `google/gemini-3-pro-preview`, and `microsoft/fara-7b`
- Updated provider mentions from "Google, Anthropic, and OpenAI" to include Microsoft across all CUA-related docs
- Organized model lists alphabetically by provider for consistency

The codebase (`AVAILABLE_CUA_MODELS` in `agent.ts`) supports 12 CUA models but the docs only listed 7. This brings the docs in sync with the source of truth.

## Test plan
- [ ] Verify the models page renders the updated accordion table correctly
- [ ] Verify the agent reference page lists all 12 models
- [ ] Verify the computer-use best practices page mentions Microsoft
- [ ] Verify the agent basics page mentions Microsoft

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

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Added five missing CUA models—anthropic/claude-opus-4-5-20251101, anthropic/claude-opus-4-6, google/gemini-3-flash-preview, google/gemini-3-pro-preview, and microsoft/fara-7b—and updated provider mentions to include Microsoft. This syncs all CUA docs with the 12 models supported in the codebase and alphabetizes lists by provider.

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

<!-- End of auto-generated description by cubic. -->
2026-02-18 14:55:26 -05:00
Nick Sweeting
afbd08bb63
[STG-1232] Speed up PR Github Actions checks, add code coverage, fix e2e bb tests running not running in bb mode, remove tsup, generate unified re-used ESM and CJS builds with sourcemaps and types, switch CI to new Evals CLI (#1632)
# why

- unit tests, e2e integration tests, and evals were taking 10~15 minutes
per pr
- finding the specific failing eval or test was tedious and required
reading tons of log output
- we weren't leveraging pnpm or turbo caches or github action's native
chromium install
- tests were flaky because CDP would randomly fail to connect when
github actions runner was overloaded
- e2e bb tests were not actually running against bb, so it was
previously just double-running e2e:local and reporting it as bb
- tsup has been deprecated for a while and should be replaced by esbuild

# what changed

- parallelized all CI tests and broke out evals and tests into
individual matrix jobs
- created unified node+pnpm+turbo setup action that all other actions
call
- verified vanilla chromium is able to launch inside all the e2e local
jobs before running any of our own code to catch resource contention
flakyness
- add proper esm and csj builds with sourcemaps and types for aligned
coverage
- remove tsup dependency
- switch to new evals cli
- add coverage reporting
- fix some flaky tests needed to get everything passing reliably

<img width="1635" height="609" alt="Screenshot 2026-01-26 at 1 04 04 PM"
src="https://github.com/user-attachments/assets/24bb2ea9-e182-4cb3-9856-6a77efe921b7"
/>



<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Speeds up CI and makes tests stable by running Vitest/Playwright/Evals
on the built ESM dist with cached artifacts, verified runner Chromium,
weighted Browserbase routing, and merged coverage. Publishes a unified
ESM+CJS SDK with sourcemaps/types and SEA binaries from ESM; fixes
Browserbase e2e, switches to the new Evals CLI, and adds flaky‑test
reporting, addressing Linear STG‑1232.

- **New Features**
- CI: split pnpm/Turbo caches; composite actions (setup/caches, Chromium
launch check, region selection, CTRF/V8 uploads); reuse artifacts; use
Actions Chromium via CHROME_PATH with --no-sandbox; unique CTRF reports;
V8 coverage normalization/merge with cancellation safety; push triggers
enabled.
- Tests: run from dist/esm; env reporter; true Browserbase runs with
weighted/randomized regions; hard timeouts for LLM and session
create/CDP connect; faster multi‑click dispatch; higher timeouts and
targeted skips; cleanup helpers; fixes for init‑script,
wait‑for‑selector, and screenshot reliability.
- Build/SDK/SEA: export map (ESM import + CJS require) with
sourcemaps/types; SEA binaries built from ESM with sourcemaps and plain
logs in CI; removed tsup and dotenv; AISdk/CustomOpenAI moved to lib and
exported; getAISDKLanguageModel added; replay metrics now include
method/parameters/result/timestamps/cost.

- **Migration**
- Set STAGEHAND_BROWSER_TARGET=local|browserbase, STAGEHAND_ENV
(replaces TEST_ENV), CHROME_PATH; tune LLM_MAX_MS,
BROWSERBASE_SESSION_CREATE_MAX_MS, BROWSERBASE_CDP_CONNECT_MAX_MS;
optionally set BROWSERBASE_REGION_DISTRIBUTION.
- Remove dotenv; set env vars directly and import
@browserbasehq/stagehand via the export map (avoid dist paths).

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

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







<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Ships an ESM‑first SDK with a CJS entry, unified sourcemaps, and types.
CI runs Vitest/Playwright and the new Evals CLI against the built ESM
dist using the runner’s Chromium (launch‑verified), with region‑weighted
Browserbase routing, normalized V8 coverage, unique CTRF artifacts, and
more stable tests (timeouts, Browserbase skips, understudy click/API
fixes).

Speed up CI by running Vitest and Playwright tests in parallel matrices,
add V8/CTRF coverage, and stabilize Browserbase/LLM flows with hard
timeouts and better cleanup. Server integration tests now use the
runner’s Chromium for reliability and are folded into the main CI.

- **Refactors**
- Parallelized core unit tests via discover-core-tests/core-unit-tests
(Vitest matrix, fail-fast).
- Parallelized E2E via discover-e2e-tests (Playwright local +
Browserbase) gated on core changes; weighted Browserbase region
selection; verify Chromium/CDP before tests; local uses runner Chromium
via CHROME_PATH and --no-sandbox; Playwright can emit JUnit when
CTRF_JUNIT_PATH is set.
- Unified Lint & Build with Turbo caching and shared artifacts;
tests/evals download and reuse; prepare script skips build in CI; SEA
builds support sourcemaps.
- Enforced configurable timeouts and parallelism via env (LLM_MAX_MS,
BROWSERBASE_CDP_CONNECT_MAX_MS, BROWSERBASE_SESSION_CREATE_MAX_MS,
LOCAL_SESSION_LIMIT_PER_E2E_TEST,
BROWSERBASE_SESSION_LIMIT_PER_E2E_TEST, EVAL_*); added LLM and
Browserbase hard timeouts; improved click event dispatch to reduce
remote flakiness.
- Explicitly close Browserbase sessions in tests and evals to free
capacity.
- Added composite actions: setup-node-pnpm-turbo,
verify-chromium-launch, select-browserbase-region, publish-ctrf-report
(JUnit→CTRF and evals), upload-v8-coverage.
- Renamed TEST_ENV to STAGEHAND_ENV across E2E; added an env reporter
for CI logs; removed the standalone stagehand-server tests workflow and
ran server tests in the unified CI with Node’s test runner and GitHub
Actions Chromium.


- **New Features**
- Build/Exports: ESM in dist/esm and CJS in dist/cjs via export map;
types from ESM; SEA binaries built from dist with sourcemaps; server SEA
job targets CJS; new build/test/coverage scripts; Node loader maps
package imports to dist/esm; ESM‑safe pathing (fileURLToPath);
ESLint/Prettier tweaks; dotenv removed.
- CI: Composite actions (setup-node-pnpm-turbo, verify-chromium-launch,
select-browserbase-region, upload-ctrf-report, upload-v8-coverage); uses
runner Chromium via CHROME_PATH with --no-sandbox and launch checks;
weighted Browserbase region selection; unique CTRF artifacts; V8
coverage normalized/merged with debug logs and graceful cancellation;
Playwright/Vitest discover tests in dist/esm; push/PR triggers enabled.
- Tests & API: Vitest/Playwright run on dist/esm; new env reporter and
closeV3 helper; tighter multi‑click CDP dispatch; higher timeouts and
targeted skips (e.g., console on Browserbase) reduce flakiness; local
launches honor CHROME_PATH; replay metrics now include
parameters/result/timestamps/cost with parser fixes; AISdk/CustomOpenAI
clients moved to lib/v3/external_clients and exported; env‑driven hard
timeouts for LLM ops and Browserbase session create/CDP connect;
understudy API usage fixes.

- **Migration**
- Set STAGEHAND_BROWSER_TARGET=local|browserbase and CHROME_PATH; tune
LLM_MAX_MS, BROWSERBASE_SESSION_CREATE_MAX_MS, and
BROWSERBASE_CDP_CONNECT_MAX_MS; optionally set
BROWSERBASE_REGION_DISTRIBUTION.
  - dotenv support is removed; set env vars explicitly in dev and CI.
- Import @browserbasehq/stagehand via the export map; do not reference
dist paths or prior tsup outputs.

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

<!-- End of auto-generated description by cubic. -->
2026-02-17 17:45:49 -08:00
Shrey Pandya
ed37332970
[docs]: correct Python dict syntax for cdp_url in browser config (#1684)
## Summary
- Fixes invalid Python syntax in the "Connecting to your local browser"
docs example
- The `cdp_url` was written using keyword argument syntax
(`cdp_url="..."`) inside a dictionary literal `{}`, which is a syntax
error in Python
- Changed to proper dictionary syntax (`"cdp_url": "..."`)

Fixes #1288

## Test plan
- [x] Verify the corrected code example is valid Python syntax

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

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes invalid Python dictionary syntax in the local browser
configuration docs by changing cdp_url="..." to "cdp_url": "...". This
removes the syntax error so the example runs when copy-pasted.

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

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 10:44:02 -08:00
Sean McGuire
b65756e9e8
[feat]: add keepAlive param (#1672)
# why
- to give users the freedom to decide whether the browser should be kept
open or "alive" when their stagehand instance is killed
- to follow best practices by avoiding usage of global signal handlers
inside library code
# what changed
new `keepAlive` option:
- added an optional, boolean `keepAlive` parameter in the stagehand
constructor params. `keepAlive` defaults to `false`
- `keepAlive` on the constructor overrides
`browserbaseSessionCreateParams.keepAlive` when both are provided
out-of-process shutdown supervisor (`packages/core/lib/v3/shutdown/`):
- replaced the old in-process global signal handlers
(process.once("SIGINT"), etc.) with a detached supervisor process that
watches a lifeline (stdin pipe + IPC channel) to the parent
- when `keepAlive` is set to `false`, the supervisor is spawned during
`init()` and performs best-effort cleanup if the parent dies
unexpectedly:
- if `env` is `"LOCAL"` the supervisor kills the Chrome PID (with
SIGTERM → SIGKILL escalation) and removes any temp user-data directory
- if `env` is `"BROWSERBASE"` & using the stagehand API, the supervisor
sends `REQUEST_RELEASE` to the browserbase API
- the supervisor also includes PID polling to guard against process
reuse (killing a recycled PID
- when `keepAlive` is set to `true`, no supervisor is spawned, & the
browser is left running
- when `disableAPI` is set to `true` (direct WS to Browserbase), no
supervisor is spawned since the browser will auto release when the WS is
dropped

refactored `close()` into helpers:
- pulled browser teardown logic into `shutdown/shutdownBrowser.ts`
(`shutdownBrowserSession`, `shutdownLocalBrowser`)
- pulled stagehand internal state cleanup into
`shutdown/shutdownStagehand.ts` (`shutdownStagehandResources`,
`finalizeStagehandShutdown`)
-`.close()` now skips `apiClient.end()` when `keepAlive: true`

local browser launch changes:
- updated local launch to pass chrome launcher’s `handleSIGINT` based on
`keepAlive` in `packages/core/lib/v3/v3.ts` and
`packages/core/lib/v3/launch/local.ts`. this prevents chrome from
getting killed on Ctrl+C when `keepAlive: true`
- updated local launch so that we `unref()` the chrome child process
after launch so Node can exit while chrome stays open
(`packages/core/lib/v3/v3.ts`)
### behaviour notes:
- setting `keepAlive: true` will keep the browser alive in the following
scenarios:
- stagehand instance gets killed because of an uncaught error (eg,
`unhandledRejection`, `unhandledException`)
  - stagehand instance gets killed because of a `SIGTERM` or `SIGINT`
- stagehand instance gets killed with an explicit call to
`stagehand.close()`
# test plan
- added tests in `keep-alive.spec.ts` that validate expected behaviour
across the following scenarios:
  - `unhandledRejection`/`unhandledException`, 
  - `SIGTERM`/`SIGINT`, 
  - `stagehand.close()`
- each scenario is validated in each of the following browser
configurations:
  - using a local browser launched by stagehand
  - using a browserbase browser, connected directly over the WS
  - using a browserbase browser + the stagehand API


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds a keepAlive option to Stagehand V3 so you control whether the
browser/session stays up after stagehand.close(), signals, or uncaught
errors. Replaces global process handlers with a per‑instance crash‑only
supervisor with a ready handshake and PID polling to avoid race
conditions (STG‑1338).

- **New Features**
- keepAlive?: boolean (default false) on the V3 constructor; overrides
browserbaseSessionCreateParams.keepAlive when set.
- Local: set handleSIGINT based on keepAlive and unref Chrome when true;
when false, a detached supervisor watches a stdin/IPC lifeline and on
parent crash/error SIGTERM→SIGKILLs Chrome and removes the temp profile
(with PID polling). A shared cleanup helper is used by both close() and
the supervisor for consistent local teardown.
- Browserbase: propagate keepAlive to session creation; when keepAlive
is true, close() skips apiClient.end() so the session stays RUNNING;
when false (and API enabled), the supervisor requests REQUEST_RELEASE on
crash/error; when disableAPI is true (direct WS), no supervisor is
spawned and the session ends when the WS drops.

- **Migration**
- Set keepAlive: true in the V3 constructor to keep the browser/session
open on errors, signals, or stagehand.close(); this overrides any value
in browserbaseSessionCreateParams.
- When keepAlive is true, close resources yourself when done (Local:
send Browser.close; Browserbase: request release/end the session).

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

<!-- End of auto-generated description by cubic. -->
2026-02-13 17:41:05 -08:00
Sean McGuire
f7275789e9
[chore]: rm noisy debug log (#1686)
# why
- this log was unhelpful, & also did not respect the global verbosity
level
# what changed
- removed the log

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Removed the noisy "xpath main-world" debug log from
FrameSelectorResolver to reduce console noise and respect global
verbosity settings.

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

<!-- End of auto-generated description by cubic. -->
2026-02-13 17:39:20 -08:00
tkattkat
d334399004
bump ai sdk + google providers version (#1685)
# why
fix 1/2 ai sdk google thought signature buts 

The version of google provider + ai sdk we currently use has a bug
resulting in errors with google thought signatures

They are in the process of releasing a fix for bug #2 but it is not yet
released - w ewill need to bump again when that is live

# what changed

bumped ai sdk + google providers versions 

# test plan


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Bumped AI SDK and @ai-sdk/google to pick up the fix for Google “thought
signature” errors. A second upstream fix is pending and will require
another bump later.

- **Dependencies**
  - ai: ^5.0.0 -> ^5.0.133 (core, evals)
  - @ai-sdk/google: ^2.0.23 -> ^2.0.53 (core)
- Updated lockfile and added changeset for @browserbasehq/stagehand
(patch)

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

<!-- End of auto-generated description by cubic. -->
2026-02-13 17:08:41 -08:00
Kyle Jeong
101bcf2da8
feat: enable codex models (#1666)
# why
people want to try codex models in Stagehand (also see benchmarks)

# what changed
Codex needs a text verbosity and reasoning effort of medium (not low) so
we set this using a conditional operator.

# test plan
Ran evals

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Enable Codex models in Stagehand via the AI SDK with the right OpenAI
provider options. Addresses STG-1324: Codex uses medium text verbosity
and reasoning effort; non-Codex gpt-5 defaults stay the same.

- **New Features**
- Detects Codex models (modelId includes "codex") and sets
textVerbosity: "medium" and reasoningEffort: "medium".
- Updates AISdkClient and AISdkClientWrapped to apply low/minimal
reasoning defaults to gpt-5.1/5.2 only when not Codex.

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

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

---------

Co-authored-by: Sean McGuire <seanmcguire1@outlook.com>
2026-02-13 17:05:31 -08:00
Sean McGuire
7584f3e92e
[fix]: extend support for xpaths containing predicates (#1683)
# why
- to make sure `.count()`/`.nth()` include shadow DOM matches 
- make sure common predicates work in shadow DOM selectors (beyond just
attribute predicates)
- also to unify xpath resolution into one shared resolver, building off
of [this](https://github.com/browserbase/stagehand/pull/1679) PR
# what changed
- added shared resolver policy in
`packages/core/lib/v3/dom/locatorScripts/xpathResolver.ts`
- expanded composed predicate parsing/evaluation in
`packages/core/lib/v3/dom/locatorScripts/xpathParser.ts` (attr
existence, contains/starts-with, text(), normalize-space, and/or/not)
- routed xpath entrypoints through the resolver:
- `packages/core/lib/v3/dom/locatorScripts/selectors.ts`
(`resolveXPathMainWorld`)
- `packages/core/lib/v3/dom/locatorScripts/counts.ts`
(`countXPathMatchesMainWorld`)
- `packages/core/lib/v3/dom/locatorScripts/waitForSelector.ts` (xpath
path now uses resolver)
- also removed unused injected helper `resolveSimpleXPath` from
`packages/core/lib/v3/dom/piercer.runtime.ts` & updated
`packages/core/lib/v3/dom/global.d.ts`
# test plan
- `packages/core/tests/xpath-parser.test.ts` (expanded predicate parsing
+ evaluation coverage)
- `packages/core/tests/xpath-resolver.test.ts` (shadow-inclusive
count/nth ordering across composed tree)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Extended XPath support for predicates and shadow DOM, unified behind a
shared resolver. Fixes .count() and .nth() with document-order DFS
across light and shadow DOM, aligning with Linear STG-1373.

- **New Features**
- Predicate support: attr exists/equals/contains/starts-with;
text()/normalize-space; and/or/not; positional [n].
- Shadow-piercing resolution for selectors, count, and waitForSelector
with native document.evaluate fallback and DFS indexing.

- **Refactors**
- Routed all XPath entry points to the shared resolver; removed legacy
traversal and the piercer’s resolveSimpleXPath backdoor.
- Expanded parser/resolver tests and added jsdom; cleaned dead code in
selectors/counts/waitForSelector.

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

<!-- End of auto-generated description by cubic. -->
2026-02-13 14:04:33 -08:00
Shrey Pandya
5764edee7a
[fix]: .count() not working on xpaths with attribute predicates (#1679)
## Summary

- Fix `locator.count()` returning 0 for XPath selectors containing attribute predicates (e.g. `//img[@alt='Stagehand']`)
- Consolidate all four copies of the XPath step parser into a single shared module with unit tests

## Root Cause

Stagehand has two ways to evaluate XPath expressions:

1. **Native browser XPath** (`document.evaluate()`) — understands the full XPath spec, including attribute filters like `[@alt='Stagehand']`, but cannot see into shadow DOM
2. **Custom XPath parser** — a hand-written DOM traversal that walks the composed tree (including shadow roots), but only understood simple patterns like `//div` or `//div[2]`, not attribute predicates

The `isVisible()` code path (via `resolveXPathMainWorld`) tried native browser XPath first and fell back to the custom parser. But the `count()` code path (`countXPathMatchesMainWorld`) went straight to the custom parser. The custom parser's regex only recognized numeric positional indices (`[1]`, `[2]`), so `[@alt='Stagehand']` was treated as part of the tag name, matching nothing.

## Fix

### 1. Extract shared parser (`xpathParser.ts`)
The XPath step parser was duplicated four times across `counts.ts`, `selectors.ts`, `piercer.runtime.ts`, and `waitForSelector.ts`. All four are consolidated into a single `xpathParser.ts` module exporting `parseXPathSteps()` and `elementMatchesStep()`.

### 2. Add attribute predicate parsing
The parser now handles `[@attr='value']` predicates (single and double quotes, multiple predicates, combined with positional indices). Attribute predicate XPaths work correctly **including inside shadow DOM**.

### 3. Fix forward slash splitting in predicates
The step splitter now tracks bracket depth so `/` inside attribute values (e.g. `[@href='/api/endpoint']`) no longer incorrectly splits the step. This was a pre-existing bug in three of the four copies; `waitForSelector.ts` had independently fixed it.

### 4. Document supported XPath subset
The parser docstring explicitly lists what's supported and what isn't, so future contributors know the scope.

## Files changed
- `xpathParser.ts` (new) — shared parser with `parseXPathSteps()` and `elementMatchesStep()`
- `counts.ts` — uses shared parser (removed ~40 lines of inline parser)
- `selectors.ts` — uses shared parser (removed ~40 lines of inline parser)
- `piercer.runtime.ts` — uses shared parser (removed ~40 lines of inline parser)
- `waitForSelector.ts` — uses shared parser (removed ~50 lines of inline parser + matching)
- `global.d.ts` — updated docstring
- `xpath-parser.test.ts` (new) — 25 vitest unit tests

## Test plan

### Unit tests (25 vitest tests in `xpath-parser.test.ts`)
- [x] Basic tag parsing and case normalization
- [x] Child vs descendant axes
- [x] Positional indices (including clamping)
- [x] Attribute predicates: single quotes, double quotes, multiple predicates, combined with index, hyphenated names, empty values
- [x] Multi-step paths with mixed predicates
- [x] Forward slashes inside attribute values (`[@href='/api/endpoint']`)
- [x] URL attribute values (`[@data-url='http://example.com/path/to/page']`)
- [x] Edge cases: empty input, `xpath=` prefix, whitespace
- [x] Element matching: tag name, wildcard, attribute filtering, multiple attributes, tag+attribute combination

### Integration tests (verified manually)
- [x] `page.locator("//img[@alt='Stagehand']").count()` returns correct count (was 0, now 3) on https://www.stagehand.dev/
- [x] `page.locator("//img[@alt='Stagehand']").isVisible()` still returns `true`
- [x] Simple XPath `//div` returns correct count
- [x] CSS selectors unaffected
- [x] Non-existent XPath returns 0
- [x] `//div` on page with shadow DOM counts all elements (light + shadow = 6)
- [x] `//div[@class='test-item']` on page with shadow DOM counts all elements (light + shadow = 5)

Fixes #1668

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-02-12 21:05:42 -05:00
tkattkat
ca815503cc
remove unncessary type casting (#1674)
# why

we have types casted that do not need to be 

# what changed

removed unnecessary type casts

# test plan


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Removed unnecessary type casts in StagehandAPIClient for model and
executionModel configuration. Simplifies the code and improves type
clarity with no functional changes.

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

<!-- End of auto-generated description by cubic. -->
2026-02-12 10:28:00 -08:00
Shrey Pandya
244a760037
[docs]: add Convex integration documentation (#1658)
## Summary
- Add documentation for using Stagehand with Convex applications
- Include installation, configuration, and usage examples for extract, act, observe, and agent APIs
- Add Convex to the docs navigation under Integrations (v3 only)

## Test plan
- [ ] Verify docs build successfully
- [ ] Check navigation shows Convex integration
- [ ] Confirm redirect works for `/integrations/convex/`

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

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds Convex integration docs with install, env vars, session management, model config, and usage examples (extract, act, observe, agent). Updates docs nav and redirects, and fixes example import paths and required constructor config; standardizes zod imports.

- **New Features**
  - Added v3 pages: integrations/convex/introduction and integrations/convex/configuration.
  - Added “Convex” to Integrations nav.
  - Added redirect /integrations/convex/* -> /v3/integrations/convex/*.

- **Bug Fixes**
  - Corrected package usage and import paths to @browserbasehq/convex-stagehand in all examples.
  - Fixed Stagehand constructor and model config examples to include required keys: browserbaseApiKey, browserbaseProjectId, modelApiKey.
  - Added zod to install and standardized imports to zod; updated model example to anthropic/claude-sonnet-4-5.

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

<!-- End of auto-generated description by cubic. -->
2026-02-11 13:31:01 -05:00
tkattkat
0783d3f5a8
add agent structured output feature to docs (#1676)
# why

We do not currently have documentation on the structured output feature
within agent

# what changed

added documentation for usign structured output with aget 

# test plan
ran mintlify dev, and looked at docs 

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds documentation for the Agent structured output feature, showing how
to define a Zod schema via the output option and read data from
result.output. Clarifies availability (non-CUA agents) and the need for
experimental: true.

- **New Features**
  - Added “Structured Output” guides to basics and reference docs.
- Documented output in AgentExecuteOptions/AgentStreamExecuteOptions and
result.output in AgentResult/AgentStreamResult.
- Included examples: basic extraction, complex arrays, and streaming,
with notes on non-CUA and experimental requirement.

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

<!-- End of auto-generated description by cubic. -->
2026-02-10 16:04:21 -08:00
Kyle Jeong
b73ba76683
feat: adding Opus 4.6 to model list for computer use (#1665)
# why

opus 4.6 is sota on os world for computer use 

# what changed

enabled it on list of models 

# test plan


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Added Claude Opus 4.6 to the computer use model list to make it
available for agents. Mapped it to the Anthropic provider and updated
public API types and tests.

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

<!-- End of auto-generated description by cubic. -->
2026-02-10 12:00:15 -08:00
Kyle Jeong
5c38f99d6d
feat: adding AI Gateway support (#1627)
# why

New open source models are released, and don't necessarily have a great
inference provider at all times. Seeing as we're already using the
AI-SDK, it makes sense to add support for the AI Gateway.

# what changed
Added Vercel AI Gateway as a provider to the llm providers list. 

# test plan
Testing with Evals

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds Vercel AI Gateway as a provider to route model calls across vendors
with a single API key; docs now cover gateway/{provider}/{model} usage,
AI_GATEWAY_API_KEY setup, examples for Anthropic/Google, and optional
baseURL config.

Also enforces JSON outputs for Kimi and DeepSeek, sets Kimi
temperature=1, and fixes eval parsing by using the first slash in
provider/model strings.

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

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

---------

Co-authored-by: Miguel <36487034+miguelg719@users.noreply.github.com>
2026-02-10 11:48:07 -08:00
tkattkat
0e4a144832
add anthropic caching to system prompt in agent (#1655)
# Add Anthropic Prompt Caching for Agent System Prompts

## Summary

Added Anthropic's ephemeral cache control to system prompts in
`v3AgentHandler.ts`. Refactored into a single `prependSystemMessage()`
function used by both `execute()` and `stream()`.

## Why

Reduces token costs and latency for Claude models by caching the system
prompt server-side. The `providerOptions` are ignored by non-Anthropic
models, so this is safe for all providers.

## Limitations

Currently limited to the system prompt only. Extending to conversation
messages requires restructuring message processing to insert cache
breakpoints at stable boundaries.

## Test Plan

- [x] Verify agent works with Claude and non Anthropic models
- [x] Confirm `cached_input_tokens` appears in usage metrics with Claude


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Added Anthropic ephemeral caching to the agent’s system prompt to lower
Claude token usage and reduce latency. Safe for non-Anthropic models;
the options are ignored.

- **New Features**
- System messages now include Anthropic providerOptions with
cacheControl: ephemeral.

- **Refactors**
- Introduced prependSystemMessage() and used it in both text generation
and streaming to centralize system prompt handling.

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

<!-- End of auto-generated description by cubic. -->
2026-02-06 12:51:38 -08:00
Sean McGuire
b27c04d278
[fix]: ctx.addInitScript() iframe issues (#1664) 2026-02-05 18:43:50 -08:00