418 Commits

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 13:06:28 -07:00
github-actions[bot]
041ccccd45
[Claimed #1844] Refactor model ID checks for GPT 5.x model family (#1852)
Mirrored from external contributor PR #1844 after approval by
@miguelg719.

Original author: @praveentcom
Original PR: https://github.com/browserbase/stagehand/pull/1844
Approved source head SHA: `a637dc329bfc5426bb71c8551c812191ed631527`

@praveentcom, please continue any follow-up discussion on this mirrored
PR. When the external PR gets new commits, this same internal PR will be
marked stale until the latest external commit is approved and refreshed
here.

## Original description
All GPT-5.x series models don't support `minimal` as the
`reasoningEffort`. Currently, it is enabled only for GPT-5.1 and GPT-5.2
models to set the reasoningEffort as `low`. This would start throwing
errors like these.

`Unsupported value: 'minimal' is not supported with the 'gpt-5.4' model.
Supported values are: 'none', 'low', 'medium', 'high', and 'xhigh'.`

This PR fixes the behavior to set the reasoning effort as low for all
GPT-5.x series models so that we don't need to manually patch it every
time when a new SOTA model is released.

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Default `reasoningEffort` to "none" for all `gpt-5.*` models (excluding
`codex`) to avoid unsupported "minimal" errors, with an override via
`ClientOptions.reasoningEffort`, and default GPT-5 `textVerbosity` set
to "low".
Also plumbs `clientOptions` into both `AISdkClient` and
`AISdkClientWrapped` and applies the same reasoning/text-verbosity
behavior (`codex` stays "medium").

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

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

<!-- external-contributor-pr:owned source-pr=1844
source-sha=a637dc329bfc5426bb71c8551c812191ed631527 claimer=miguelg719
-->

---------

Co-authored-by: Praveen Thirumurugan <mail@praveent.com>
Co-authored-by: miguel <miguelg71921@gmail.com>
2026-03-31 12:10:32 -07:00
tkattkat
d3c3736c57
Add support for LLM middleware (#1872)
# why

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

# what changed

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

# test plan

- wrote tests 
- tested locally with own middleware 

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

---------

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

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

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

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

<!-- End of auto-generated description by cubic. -->
2026-03-30 17:20:02 -07:00
Sean McGuire
555805adf0
[fix]: harden act variables prompt (#1922)
# why
- models would sometimes respond with the variable name without wrapping
it in percentage signs.
- when this happens, the regex would fail to replace the variable name
with the actual variable value
# what changed
- adjusted the prompting for the condition when `variables` are provided
by the user
- the updated prompting is more specific around what the variables are
used for, and the required return shape.
# test plan
- existing act evals

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Hardened the act variables prompt so models always return argument
placeholders as %variableName%, preventing failed variable substitution.
Also clarified the element ID format with concrete examples.

- **Bug Fixes**
- Added explicit, repeated guidance to use %variableName% in the
`arguments` array when variables are provided.
- Improved element ID schema description with examples like '0-76' and
'16-21'.

- **Refactors**
- Introduced `buildActVariablesPrompt()` and reused it in both act and
step-two prompts to keep messaging consistent and avoid duplication.

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

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

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

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


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

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

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

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

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

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-30 16:17:16 -07:00
Shrey Pandya
79f55cda47
chore: switch browse-cli to merge-first release flow (#1921)
## Summary
Move browse-cli to a merge-first release flow so `main` becomes the
source of truth before npm is mutated.

## New release flow
1. Merge normal feature PRs into `main`, with browse-cli changesets as
usual.
2. Trigger `Prepare CLI Release` when browse-cli is ready to ship.
3. That workflow versions only `@browserbasehq/browse-cli` and opens or
updates a release PR.
4. Merge the release PR.
5. The existing `Release` workflow on `main` detects the browse-cli
version bump, publishes a packed tarball to npm with provenance, and
tags the merge commit.

## What changed
- rewired `release-cli.yml` into a prepare-only workflow that creates or
updates a release PR instead of publishing directly
- moved browse-cli publishing into `release.yml`, gated on an actual
version bump landing on `main`
- kept the `pnpm pack` -> `npm publish --provenance` path so workspace
dependencies are resolved in the published tarball
- made the main-branch publish path idempotent when that browse-cli
version is already on npm
- kept browse-cli tagging on the merge commit instead of trying to tag
from the manual workflow
- synced `packages/cli/package.json` to `0.3.0` and documented npm
`0.3.0` as a broken publish in the CLI changelog

## Why this is better
The previous standalone release design could succeed at publishing to
npm and then fail while trying to sync `main`, which left npm ahead of
git. That is the hard failure mode because npm versions are immutable.

This PR flips the order:
- git changes land first through a normal PR
- npm publish happens afterward from the exact merged commit

That removes the whole class of "published version is not reflected on
`main`" failures and makes reruns much safer.

## Validation
- `pnpm exec prettier --check .github/workflows/release.yml
.github/workflows/release-cli.yml packages/cli/package.json
packages/cli/CHANGELOG.md`
- packed `packages/cli` locally and verified the tarball manifest
resolves `@browserbasehq/stagehand` to `3.2.0`
- confirmed the currently published npm `0.3.0` manifest still contains
the broken `workspace:*` dependency
- simulated the prepare flow in a throwaway worktree and confirmed it
would cut `0.4.0` from the current 2 minor + 2 patch browse-cli
changesets
2026-03-30 14:10:30 -07:00
Sam F
206fb14ac0
Recover server-v4 drizzle stack onto main (#1917)
## Why
The original server-v4 stacked PRs merged into each other after
`STG-1614` had already merged into `main`, so the env/test-harness work,
Drizzle foundation, and Drizzle schema/controller flow never actually
reached `main`.

This PR recovers that full stack onto current `main` in one branch.

## What Changed
- cherry-picked the three stacked squash-merge commits from `#1896`,
`#1897`, and `#1898` onto fresh `main`
- preserved the full `server-v4` env/test harness cleanup, Drizzle
foundation, DB smoke tests, schema/migration work, and `/v4/llms`
controller/service/repo flow
- added one small follow-up commit to normalize `pnpm-lock.yaml` against
current `main` after applying the recovered stack

## Test Plan
- `pnpm install`
- `pnpm --filter @browserbasehq/stagehand-server-v4 run lint`
- `pnpm --filter @browserbasehq/stagehand-server-v4 run test:unit`
- `pnpm --filter @browserbasehq/stagehand-server-v4 run build`
- `pnpm --filter @browserbasehq/stagehand-server-v4 run gen:openapi`

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Recovers the server‑v4 Drizzle stack onto `main`, restoring DB‑backed
`/v4/llms` and switching the public `LLMId` to UUID. Adds a typed env,
clean app bootstrap, and a local `pglite`/Postgres runtime with
migrations, tests, and a simpler source‑based test harness.

- **New Features**
- Drizzle foundation with `pglite` default and Postgres option; new
`db:*` scripts via `drizzle-kit`.
- Fastify `databasePlugin` and unified DB client; `app.ts` bootstrap
with health/readiness and Swagger/OpenAPI; env via `@t3-oss/env-core`.
- Tables/relations for LLMs and Stagehand; DB‑derived Zod schemas; first
migration; OpenAPI updated for UUID `LLMId` with strict format and
pattern.
- LLM module (repo/service/controller) backing `/v4/llms`; routes now
delegate to the controller; browser session create uses the service and
auto‑creates a system default LLM when `llmId` is missing.
- Tests run from source via `tsx`; test server script simplified;
`turbo` tasks cleaned up; schema cleanup (`z.url()`).

- **Migration**
  - Run: `pnpm --filter @browserbasehq/stagehand-server-v4 db:migrate`.
- Local dev uses `pglite` at `~/.stagehand/db/stagehand-v4`. For
Postgres set `STAGEHAND_DB_MODE=postgres` and `DATABASE_URL`.
- Update clients to treat `LLMId` as a UUID and regenerate from
`openapi.v4.yaml` if needed.

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

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

---------

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


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

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

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

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

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

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

## Test plan

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

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

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 16:13:51 -07:00
Sean McGuire
da6b40fc67
[v4]: more page route stubs for locator functions (#1882)
# why
- to add page routes for more of the locator functions 
# what changed
- added the following route stubs:
  - `/fill`
  - `/highlight`
  - `/selectOption`
  - `/setInputFiles`
- each of the above optionally returns a selector object if
`returnSelector: true`
- aligned existing `/click`, `/hover`, and `/dragAndDrop` routes to
default `returnSelector` to `false`

### screenshot:
<img width="606" height="925" alt="Screenshot 2026-03-24 at 1 25 11 PM"
src="https://github.com/user-attachments/assets/a7ec4602-2ad1-44e9-81be-54208021bc43"
/>

# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds v4 page route stubs for locator actions: /v4/page/fill,
/v4/page/highlight, /v4/page/selectOption, and /v4/page/setInputFiles.
Addresses STG-1646 with OpenAPI and schema updates; routes return
placeholder results with optional selector output.

- **New Features**
- Added POST endpoints: /v4/page/fill, /v4/page/highlight,
/v4/page/selectOption, /v4/page/setInputFiles (wired into router and
documented). Each supports returnSelector (default false) and returns
placeholder results.

- **Refactors**
- Default returnSelector is now false for /click, /hover, and
/dragAndDrop.
  - ResultSelector is now required in result schemas.

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

<!-- End of auto-generated description by cubic. -->
2026-03-27 14:09:59 -07:00
Sean McGuire
d8ce245a7c
[v4]: add /elementInfo route stub (#1877)
# why
- to add a single `/elementInfo` route which encapsulates multiple
`locator` functions
# what changed
- added an `/elementInfo` route, which accepts a `Selector`, and returns
the following info:
  - `count`
  - `isVisible`
  - `isChecked`
  - `inputValue`
  - `textContent`
  - `innerHTML`
  - `innerText`
  - `centroid`

### screenshot:
<img width="538" height="693" alt="Screenshot 2026-03-23 at 5 10 55 PM"
src="https://github.com/user-attachments/assets/75d7cab4-5f47-40fc-bebb-8b0fb6a8b192"
/>



# test plan
- added a test which verifies that the `/elementInfo` route accepts a
request


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds the v4 `page.elementInfo` endpoint (`POST /v4/page/elementInfo`) to
fetch common element details in one call. The handler is a stub that
returns defaulted fields to unblock client work.

- **New Features**
- Implemented `page.elementInfo` route that accepts a `Selector` and
optional `fields` filter; returns: `count`, `selector`, `tagName`,
`backendNodeId`, `visibility`, `domRects`, `content`, and optional
`inputInfo`, `ariaInfo`, `attributes`, `styles`.
- Wired the route into v4 page routes, added
request/action/result/response schemas to OpenAPI, and added an
integration test posting an XPath selector to assert a successful
action.

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

<!-- End of auto-generated description by cubic. -->
2026-03-27 12:07:07 -07:00
Sean McGuire
c50a5d87b9
[v4]: update /scroll route stub (#1875)
# why
- the existing /page/scroll endpoint had an awkward union of
`PageScrollElementParams` (element selector + percentage) and
`PageScrollCoordinateParams` (coordinate selector + deltaX/deltaY).
- these two modes were hard to distinguish and didn't cover common
scrolling patterns like "scroll N pages" or "scroll until this element
is visible"
# what changed
- replaced the two old scroll param schemas with a cleaner 3-way
discriminated union:
- `PageScrollByOffsetParams`: scroll by pixel delta (`{ cursorPosition?,
offset: {x, y} }`)
- `PageScrollByPagesParams`: scroll by viewport heights (`{
cursorPosition?, pages: number, delayBetweenMs? }`)
- `PageScrollToTargetParams`: scroll until a target is visible (`{
target: Selector }`)
- `cursorPosition` is an optional `Selector` that determines where the
mouse cursor is placed before scrolling. this controls which scrollable
container receives the event.
# test plan
- updated the route stub and integration test to match the new schema

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Refactors the v4 `/page/scroll` route into a simple 3‑mode API and
updates OpenAPI to return a typed `PageScrollActionOutput`. The stub now
returns `{x: 0, y: 0}`; adds `position` for target scrolls and
`delayBetweenMs` for page scrolling, aligning with Linear STG-1644.

- **Refactors**
- Replaced old params with 3 modes: by offset `{offset:{x,y}}`, by pages
`{pages, delayBetweenMs?}`, or to target `{target, position?}`; optional
`{cursorPosition}` selects the scroll container.
- OpenAPI now uses `PageScrollActionOutput` and
`PageScroll*ParamsOutput` (defaults resolved, stricter requireds) and
wires it into the `PageAction` union.
  - Route stub execution simplified to always return `{x: 0, y: 0}`.

- **Migration**
  - Stop using `selector + percentage` and `selector + deltaX/deltaY`.
- Send one of: `{offset:{x,y}}`, `{pages, delayBetweenMs?,
cursorPosition?}`, or `{target, position?}`.
- Expect `{x,y}` in the result; the action shape is now
`PageScrollActionOutput`.

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

<!-- End of auto-generated description by cubic. -->
2026-03-27 12:05:05 -07:00
Sam F
a17deb960e
STG-1614: add v4 llm stubs and internal schemas (#1881)
Adds the v4 `/llms` stubs, and the internal zod entities we will map to
drizzle DB objects later.

Note: An internal `LLMSession` is not the full accumulated history of an
entire browser session. It is the container for the LLM thread involved
in a single logical Stagehand operation, which today is usually very
small. For example, an `act()` call may create one `LLMSession` with one
`LLMCall`; `extract()` may create one `LLMSession` with two `LLMCall`
rows. It is **not** a giant transcript of every LLM call across the
whole browser session.

### Public:
- `/v4/llms` for reusable LLM configs
- `BrowserSession.llmId` as the primary/default LLM config reference,
plus `actLlmId`, `observeLlmId`, and `extractLlmId` as public
per-operation override references

### Internal only (for now):
- `LLMSession`
- `LLMCall`
- `StagehandStep`
- the browser-session-to-llm-session/call relationships shown in the
diagram below

We are intentionally not exposing `LLMSession` / `LLMCall` history in
this PR. That data can still be surfaced through logs/streaming work,
and we can decide later whether we want a first-class public API for it.

### Sequence Example
1. User creates a browser session.
2. If they do not pass `llmId`, the server materializes a real default
LLM config with `source = "system-default"` and attaches it to the
session.
3. If they want custom behavior up front, they can `POST /v4/llms` first
and then create the browser session with `llmId`.
4. If they want different defaults for specific operations, they can set
`actLlmId`, `observeLlmId`, and/or `extractLlmId` on the browser
session.
5. When an `act` / `observe` / `extract` call runs, Stagehand resolves
the template config from the per-operation override or falls back to
`llmId`, creates a dedicated `LLMSession` for that operation, and
records one or more `LLMCall` rows under it.
6. Updating an LLM config changes that reusable config resource;
updating a browser session changes which config ids future steps resolve
from.

```mermaid
classDiagram
  class BrowserSession {
    id: uuid
    projectId: uuid
    env: BrowserSessionEnv
    status: BrowserSessionStatus
    browserbaseSessionId: uuid?
    cdpUrl: string?
    llmId: uuid
    actLlmId: uuid?
    observeLlmId: uuid?
    extractLlmId: uuid?
    createdAt: datetime
    updatedAt: datetime
    endedAt: datetime?
  }

  class LLMSession {
    id: uuid
    copiedTemplateId: uuid?
    forkedSessionId: uuid?
    projectId: uuid
    browserSessionId: uuid
    createdAt: datetime
    updatedAt: datetime
    connectedAt: datetime?
    disconnectedAt: datetime?
    lastRequestAt: datetime?
    lastResponseAt: datetime?
    lastErrorAt: datetime?
    lastErrorMessage: string?
    status: LLMSessionStatus
    model: string
    baseUrl: string?
    options: json?
    extraHttpHeaders: json?
    systemPrompt: string?
    tokensInput: int
    tokensOutput: int
    tokensReasoning: int
    tokensCachedInput: int
    tokensTotal: int
  }

  class LLMCall {
    id: uuid
    llmSessionId: uuid
    sentAt: datetime
    receivedAt: datetime?
    prompt: string
    expectedResponseSchema: json?
    response: json?
    error: json?
    usage: json?
    model: string
  }

  class StagehandStep {
    id: uuid
    stagehandBrowserSessionId: uuid
    operation: StagehandStepOperation
    llmTemplateId: uuid
    llmSessionId: uuid?
    params: json
    result: json?
  }

  class LLMConfig {
    id: uuid
    projectId: uuid
    source: LLMSource
    displayName: string?
    modelName: string
    baseUrl: string?
    systemPrompt: string?
    providerOptions: LLMProviderOptions?
    createdAt: datetime
    updatedAt: datetime
  }

  BrowserSession "1" <-- "*" LLMSession : has many
  LLMSession "1" --> "*" LLMCall : has many
  BrowserSession "1" --> "*" StagehandStep : has many
  StagehandStep "1" --> "0..1" LLMSession : resolves to
  LLMConfig "1" <-- "*" BrowserSession : is referenced by many
```

Implementation notes
- Auto-created default configs are real `/llms` resources and appear in
`GET /v4/llms`.
- Defaults should be treated as versioned server presets in
implementation, not just implicit column defaults.
- Persisted public `LLM` configs remain non-secret; request auth still
stays out of the public config resource.
- Internally, `LLMSession` is the config-bearing per-operation thread
and `LLMCall` is the append-friendly log of provider exchanges under
that thread.
2026-03-27 20:04:02 +01:00
Sean McGuire
28f40be2be
[v4]: add method arg to /click route stub (#1884)
# why
- to group two types of clicking into a single route. ie, we don't need
to add a separate `/sendClickEvent` route
# what changed
- added an optional `synthetic` parameter to the `/click` schema, which
we will internally route to `.sendClickEvent()`

### screenshot:
<img width="436" height="693" alt="Screenshot 2026-03-24 at 3 58 50 PM"
src="https://github.com/user-attachments/assets/75a35a09-3f92-4b25-bfcb-8dc36a328088"
/>

# test plan
- added a test to verify passing `synthetic: true` passes validation

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Add a `method` param to the v4 `/click` route to support both
coordinate-based and JS event clicks in one endpoint, defaulting to `xy`
for backward compatibility. Caps `clickCount` at 3 and updates the
OpenAPI/action output. Addresses Linear STG-1659.

- **New Features**
- Adds `method: 'xy' | 'jsevent'` (default `xy`) to `/click` params;
action output now includes and requires `method` via
`PageClickParamsOutput`.
- Limits `clickCount` to 1–3 in schema and OpenAPI in
`packages/server-v4`.
- Adds integration tests for coordinate clicks and `method: "jsevent"`
selector clicks.

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

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

---------

Co-authored-by: Nick Sweeting <github@sweeting.me>
2026-03-27 11:59:05 -07:00
tkattkat
6dc2276144
Fix OpenAI cua agent (#1899)
# why

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

# what changed

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

# test plan

- tested locally using operator-example script 

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

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

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

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

<!-- End of auto-generated description by cubic. -->
2026-03-27 11:40:39 -07:00
Shrey Pandya
e81dde7157
STG-1672: Add --connect flag to browse CLI for existing Browserbase sessions (#1889)
## Summary

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

## Test procedure

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

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

## Tests completed

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

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

Fixes STG-1672


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

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

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

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

---------

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

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

## Test plan

**Regression test added to PR is illustrative** 

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

## Verified test results

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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


# test plan

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

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

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

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

# what changed
Added headers to ModelConfig

# test plan



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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

<!-- End of auto-generated description by cubic. -->
2026-03-24 18:20:43 +01:00
Kyle Jeong
4f5de70762
docs: update docs theme to fix our previous sunset theme (#1879)
# why

the previous docs theme was sunset and changed 

# what changed

# test plan
2026-03-23 17:15:14 -07:00
Filip Michalsky
4b835b7fc9
variables for observe (#1808)
# why

`act()` already supports variables, but `observe()` did not. That made
safety-sensitive flows like login automation harder to use correctly:
callers could inspect `observe()`
results before executing them, but then had to guess which returned
action should receive each secret value before calling `act()`.

This change brings variable support to `observe()` so it can return
placeholder-backed actions like `%username%` and `%password%`. That
preserves the existing safe pattern of:

  1. `observe()` candidate actions
  2. validate the returned actions
3. `act()` the validated actions with real variable values at execution
time

  # what changed

- Added `variables?: Variables` support to `observe()` in the public SDK
types and internal handler params.
- Threaded `observe` variables through the local SDK path, inference
layer, and prompt builder.
- Updated the observe prompt so the model sees available variable names
and returns `%variableName%` placeholders in action arguments instead of
literal sensitive values.
- Added observe variable support to the hosted/API path, including
schema updates and flattening rich variable values to the existing wire
format.
- Updated the internal `fillForm` tool to pass variables into
`observe()` as well as `act()`.
- Added docs for `observe({ variables })` and the validate-then-act
login flow.
- Added a dedicated example at
`packages/core/examples/observe_variables_login.ts` showing
placeholder-based login planning with `observe()`, explicit validation,
and execution via
  `act()`.

  # test plan

  - Ran targeted unit tests covering:
    - public `ObserveOptions` type support
    - observe variable forwarding into inference/prompting
    - placeholder preservation in returned observe actions
    - API client observe variable serialization
    - `fillForm` forwarding variables to `observe()`
  - Ran:
- `pnpm --filter @browserbasehq/stagehand exec vitest run --config
/tmp/stagehand-vitest-source.config.mjs
tests/unit/public-api/public-types.test.ts tests/unit/agent-execution-
model.test.ts tests/unit/timeout-handlers.test.ts
tests/unit/api-client-observe-variables.test.ts`
  - Ran formatting checks on changed files with Prettier.
- Added integration coverage for observe request schemas in both v3 and
v4 server tests.
- Full repo typecheck/build is still blocked by unrelated pre-existing
issues in `packages/core/lib/v3/launch/browserbase.ts` and existing
server test environment/type-resolution
  failures.
2026-03-23 20:10:02 +01:00
Sean McGuire
bfee1b8a28
[v4]: update stubs to return selector obj (#1865) 2026-03-20 17:17:20 -07:00
Sean McGuire
f517608aa2
[v4]: rm redundant routes (#1862)
# why
- to reduce bloat by removing routes that are (or will be) functionally
the same as other routes
# what changed
- removed:
  - `/mainFrame` since we already have `/mainFrameId`
  - `/asProtocolFrameTree` since we already have `/getFullFrameTree`
- `/getOrdinal` since it is unnecessary (should not really have been
exposed in the first place)
  - `/waitForMainLoadState` since we already have `/waitForLoadState`
# test plan
- removed associated tests

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Removed redundant v4 page routes and cleaned up the OpenAPI/spec and
schemas to shrink the API surface. Aligns with Linear STG-1635.

- **Refactors**
- Removed endpoints: /v4/page/mainFrame, /v4/page/asProtocolFrameTree,
/v4/page/getOrdinal, /v4/page/waitForMainLoadState
  - Updated OpenAPI, schemas, route registry, and integration tests

- **Migration**
  - Use /v4/page/mainFrameId instead of /v4/page/mainFrame
- Use /v4/page/getFullFrameTree instead of /v4/page/asProtocolFrameTree
- Use /v4/page/waitForLoadState instead of /v4/page/waitForMainLoadState
  - /v4/page/getOrdinal has no public replacement (was internal-only)

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

<!-- End of auto-generated description by cubic. -->
2026-03-20 12:38:58 -07:00
Sean McGuire
2e99c9d981
[v4]: add index to selector schemas (#1861)
# why
- selectors can resolve to multiple nodes
- we need to give the user freedom to optionally provide an `index`,
indicating the desired element if multiple are found
# what changed
- added an optional `index` field to `XPathSelectorSchema`,
`CssSelectorSchema` & `TextSelectorSchema`
- note: `CoordinateSelectorSchema` remains unchanged, since coordinates
are inherently specific

### selector schema before:
<img width="555" height="944" alt="Screenshot 2026-03-19 at 4 31 50 PM"
src="https://github.com/user-attachments/assets/cd020162-02c2-44f9-a69e-d226d8501571"
/>

### selector schema after: 
<img width="603" height="980" alt="Screenshot 2026-03-19 at 4 33 32 PM"
src="https://github.com/user-attachments/assets/0e730297-a5db-4a82-a7ee-b828a8520275"
/>

# test plan
- added new test case in `packages/server-v4/src/schemas/v4/page.ts`

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds an optional non-negative idx to XPath, CSS, and text selectors so
callers can target a specific element when a selector matches multiple
nodes. Updates the v4 schema and OpenAPI spec without breaking existing
clients.

- **New Features**
- Added optional non-negative `idx` to `XPathSelectorSchema`,
`CssSelectorSchema`, and `TextSelectorSchema`.
  - Left `CoordinateSelectorSchema` unchanged.
  - Updated `openapi.v4.yaml` with the new `idx` field and examples.
- Expanded integration tests to cover `css`, `xpath`, and `text`
selectors with `idx`.

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

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

---------

Co-authored-by: Nick Sweeting <github@sweeting.me>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-19 17:24:52 -07:00
Sean McGuire
425b18ae59
[v4]: unify selector type (#1860)
# why
- to unify `selector` into a single field across page request bodies
- this groups semantically similar fields into a shared & reusable type
# what changed
- replaced `PageSelectorSchema` (xpath-only object) with a discriminated
union of 4 selector types:
  - `PageXPathSelectorSchema`, 
  - `PageCssSelectorSchema`,
  - `PageTextSelectorSchema`, 
- `PageCoordinateSelectorSchema`
- added `PageElementSelectorSchema` (xpath/css/text, no coordinates) for
`waitForSelector`
- collapsed the dual `*SelectorParams` / `*CoordinatesParams` schema
pairs for click, hover, scroll, and dragAndDrop into single schemas with
a unified `selector` field

### example `/hover` before:
<img width="557" height="842" alt="Screenshot 2026-03-19 at 1 39 06 PM"
src="https://github.com/user-attachments/assets/efda7d84-bcd4-4a70-9bf9-7674ced59614"
/>

### example `/hover` after:
<img width="556" height="956" alt="Screenshot 2026-03-19 at 1 41 14 PM"
src="https://github.com/user-attachments/assets/f8a57ee7-c50f-4f06-81f0-965fb5a7d82b"
/>

# test plan
- added integration tests for css, text, and coordinate selector types

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Unifies the v4 page selector into a single `selector` union and adds
css, text, and coordinate options. This simplifies request bodies and
makes click, hover, scroll, and drag‑and‑drop consistent.

- **New Features**
- One `selector` union for all page actions: xpath, css, text, or
coordinates.
- Introduced `Selector` and `ElementSelector` unions; split former
`PageSelector` into `XPathSelector`, `CssSelector`, `TextSelector`, and
`CoordinateSelector`.
- Added `ElementSelector` (xpath/css/text) for element‑only cases like
`waitForSelector` and scroll‑by‑percentage; exported
`PageScrollElementParams` and `PageScrollCoordinateParams`.
- `dragAndDrop` supports mixing selector types (e.g., xpath →
coordinates).
- Added integration tests for css, text, coordinate selectors, and mixed
drag‑and‑drop.

- **Migration**
- click/hover: always send `{ selector: { xpath|css|text|x,y } }`.
Remove top‑level `x`/`y`.
- scroll: use element selector + `percentage`, or coordinate selector +
`deltaY`.
- dragAndDrop: `from`/`to` now use the unified selector (elements or
coordinates).
  - waitForSelector: use `ElementSelector` (no coordinates).

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

<!-- End of auto-generated description by cubic. -->
2026-03-19 15:21:39 -07:00
Sean McGuire
a1ccb56227
[fix]: add useSearch & toolTimeout to stainless types (#1854)
# why
- so that the stainless generated SDKs can pass in the `useSearch` &
`toolTimeout` params
# what changed
- updated the `agentExecuteSchema` to include the above params

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Added `useSearch` and `toolTimeout` to Agent Execute options in public
types (`AgentExecuteOptionsSchema`) and the OpenAPI spec, and added V3
server tests to validate both fields. This lets Stainless SDKs enable
web search and set per-tool call timeouts (STG-1621).

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

<!-- End of auto-generated description by cubic. -->
2026-03-19 12:38:20 -07:00
Sam F
a8b4fa42a8
group v4 routes with fastify plugins (#1851)
# why
This splits the v4 route groups into real Fastify plugins so each group
owns its own registration and error boundary. It removes the
path-sniffing logic from `server.ts` and makes the v4 stub server a
cleaner base for future route work.

# what changed
`page` and `browsersession` now register through Fastify plugins instead
of array loops in `server.ts`, and each plugin has its own encapsulated
error handler. `server.ts` is reduced to composing the two v4 plugins
under `/v4`.

# test plan
- `pnpm --filter @browserbasehq/stagehand-server-v4 lint`
- `pnpm --filter @browserbasehq/stagehand-server-v4 build`



<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Grouped v4 `page` and `browsersession` routes into Fastify plugins under
`/v4`, each with its own error boundary and OpenAPI tag. Added shared
helpers for tagging and typed error normalization to simplify
`server.ts` and complete STG-1610.

- **Refactors**
- Introduced `pageRoutesPlugin` and `browserSessionRoutesPlugin`;
registered at `/v4`.
- Added shared `pluginUtils` (`withTag`, `normalizePluginError`) used by
both plugins.
- Plugins tag routes (`page`, `browserSession`) and return typed
validation/serialization errors via `buildErrorResponse` and
`buildBrowserSessionErrorResponse`; applied tags across
`openapi.v4.yaml`.
- Simplified the app-level error handler to a generic fallback; removed
path sniffing and route array loops from `server.ts`.

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

<!-- End of auto-generated description by cubic. -->
2026-03-19 12:19:28 -07:00
tkattkat
93591f0a0b
remove unnecssary value param from fillform tool in dom mode (#1811)
# why

The `fillForm` tool (DOM mode) had a `value` field in its input schema
that the LLM would populate, but it was never actually used during
execution. The `execute` function only read `f.action` to build the
observe instruction — the `value` was completely ignored. This meant the
tool relied entirely on the action string (e.g. `"type foo into the
email field"`) to carry both the target and the value, while `value` was
dead weight.

This was also a problem for the `variables` feature: the schema told the
LLM to use `%variableName%` syntax in the `value` field, but since
`value` was never consumed, variable substitution through it could never
work.

# what changed

- **`fillform.ts`**: Removed the `value` field from the input schema.
The `action` field now explicitly guides the LLM to include the value to
type *within* the action description (e.g. `"type foo@bar.com into the
email field"`). When variables are available, the description shows
`%variableName%` syntax with an example. This aligns the schema with how
the tool actually works — `observe` parses the action string and returns
`Action` objects with the correct `method`, `selector`, and `arguments`,
which `act` then executes.
- **`agentSystemPrompt.ts`**: Removed the stale reference to `value` in
the variable usage instructions for DOM mode (`"value/action fields"` →
`"action fields"`).
- **`cache.ts`**: Updated `AgentReplayFillFormStep.fields` type to drop
`value`.
- **Tests**: Removed `value` from test fixtures in `timeouts.spec.ts`
and `agent-execution-model.test.ts`.

# test plan

- [ ] Run unit tests: `agent-execution-model.test.ts` passes with the
updated fillForm field shape
- [ ] Run integration tests: `timeouts.spec.ts` fillForm timeout test
passes
- [ ] Run agent eval with a form-filling task (e.g. `sign_in`) to verify
the LLM correctly embeds values in the action string and fields get
filled as expected
- [ ] Test with variables: confirm `%variableName%` in the action string
gets substituted correctly (e.g. `"type %password% into the password
field"`)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Removed the unused `value` field from the DOM‑mode `fillForm` tool;
values must now be included in the `action` string using a strict "type
<value> into the <field>" pattern. Also removed the emoji from the tool
description and aligned variable guidance, types, and tests.

- **Migration**
- Update `fillForm` inputs to only use `action` that follows: "type
<exact value> into the <field name> <fieldType>", e.g. `{ fields: [{
action: "type john@example.com into the email input" }] }`.
- Use `%variableName%` inside the `action` string, e.g. `type %password%
into the password input`.
- If you reference replay types, `AgentReplayFillFormStep.fields` now
only includes `{ action: string }`.

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

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

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

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

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

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

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

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

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

<!-- End of auto-generated description by cubic. -->
2026-03-18 16:45:39 -07:00
Miguel
84473aa1ad
Revert unintentional test commit (#1850)
# why

# what changed

# test plan

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Reverts an unintended test commit by deleting
`packages/core/tests/unit/rerender-missing-shadows.test.ts`; test suite
returns to its previous state. Also updates `turbo.json` to pass through
`BROWSERBASE_FLOW_LOGS`; no production code changes.

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

<!-- End of auto-generated description by cubic. -->
2026-03-18 15:46:47 -07:00
Sean McGuire
3dddade239
[docs]: add docs for page.setExtraHTTPHeaders() (#1842)
# why
- to add docs for the new `page.setExtraHTTPHeaders()` function
# what changed
### added docs to the page reference section:
<img width="748" height="525" alt="Screenshot 2026-03-17 at 1 49 33 PM"
src="https://github.com/user-attachments/assets/a97d8903-a17d-4af4-88e6-5d9770cb7227"
/>

### added an example in the code examples section:
<img width="724" height="766" alt="Screenshot 2026-03-17 at 1 50 26 PM"
src="https://github.com/user-attachments/assets/3e3da652-70db-4758-b388-c04316f99895"
/>





<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Added docs for `page.setExtraHTTPHeaders()` in the Page reference and
examples, covering page‑scoped behavior (applies to all requests and
child sessions) and how to replace or clear headers. Addresses Linear
STG-1413.

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

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


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

### Minor Changes

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

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

### Patch Changes

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

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

## @browserbasehq/stagehand@3.2.0

### Minor Changes

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

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

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

### Patch Changes

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

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

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

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

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

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

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

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

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

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

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

## @browserbasehq/stagehand-evals@1.1.9

### Patch Changes

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

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

### Patch Changes

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

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

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

### Patch Changes

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

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

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

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

# what changed

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

# test plan

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

Browserbase smoke:

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Shrey Pandya <shrey@browserbase.com>
2026-03-18 17:03:59 -04:00
Miguel
4ff3bb831a
Enable FlowLogger on BROWSERBASE_FLOW_LOGS=1 (#1847) 2026-03-18 13:58:33 -07:00
Sam F
5c3c38d597
Add server-v4 stubs (#1840)
# why
The intent is we just want the v4 stubs - and the openapi spec (and a
few useless tests for now). This isn't all of of the v4 stubs yet
(missing `/logs` etc), but we'll add in the rest of the stubs in
parallel.


# what changed
- Removes all "copied over" v3 *functionality* and /sessions routes etc.
- Adds v4 stubs like `/browsersession` which return simple JSON objects 
# test plan
Lint + (pretty useless) tests pass, checked /documentation accessible
locally and included screenshot.
<img width="1663" height="971" alt="Screenshot 2026-03-18 at 10 36
59 AM"
src="https://github.com/user-attachments/assets/ede65965-f0b6-452e-a841-59ad25c2d456"
/>


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds `@browserbasehq/stagehand-server-v4`, a schema‑first, stubbed v4
API for BrowserSession and Page, with a regenerated OpenAPI v4 spec.
Replaces the legacy v4 sessions runtime with simple stubs and a minimal
server boot, leaving `packages/server` unchanged.

- **New Features**
- Full v4 routes: `/v4/browsersession` (create/get/end + actions) and
`/v4/page` (navigation, frames, input, CDP, screenshots, etc.), plus
`/healthz` and `/readyz`.
- Zod v4 schemas for BrowserSession/Page expose OpenAPI components;
generator builds from route registries (`browserSessionRoutes`,
`pageRoutes`); `openapi.v4.yaml` updated.
- Integration tests for v4 BrowserSession and Page; test utils updated
for v4 shapes and a default `x-model-api-key`.

- **Refactors**
- Removed legacy v4 runtime and infra (old `sessions/*` routes, session
store, SSE, auth/env/logging/response, CORS/metrics, SEA fuse) and
legacy tests; server registers only v4 routes/components.
- Simplified health/readiness handlers and error handling with a
lightweight `AppError` in `src/types/error.ts`.
- Fixed query parameter handling in stub GET handlers and OpenAPI so GET
endpoints use the correct querystring shapes.

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

<!-- End of auto-generated description by cubic. -->
2026-03-18 13:42:05 -07:00
Sam F
5981f91713
Rename server package to server-v3 (#1839)
# why
Nick's PR had both some server-v3 changes and server-v4 changes. I split
it into two prs - just the v3 changes here, and just the v4 changes
[here](https://github.com/browserbase/stagehand/pull/1840) (WIP).

Then, once I rebased this PR, it's really just one small change to the
node SEA binary stuff.

# test plan
Verified the split with exact file manifests before creating the branch
and ran `pnpm install --lockfile-only --ignore-scripts`.




<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Renamed the Stagehand server to `packages/server-v3` and
`@browserbasehq/stagehand-server-v3`. Updated CI, release, tests, and
SEA build logic; no API or runtime changes.

- **Refactors**
- Moved `packages/server` to `packages/server-v3` and renamed the
package to `@browserbasehq/stagehand-server-v3`.
- Updated GitHub workflows (CI, SEA build, release) and artifacts to
`stagehand-server-v3-*`.
- Switched OpenAPI/Stainless references to
`packages/server-v3/openapi.v3.yaml`.
- Updated test discovery/commands and Turbo tasks to target
`@browserbasehq/stagehand-server-v3`; adjusted ESLint, workspace, and
scripts accordingly.
- Hardened SEA build: verify Node binary includes the required fuse,
fall back to the official Node distro when needed, enforce fuse
presence, use `stagehand-server-v3-sea` temp paths, centralize the fuse
value, and add a clear cache recovery hint when the cached Node binary
lacks the fuse.

- **Migration**
- Use `@browserbasehq/stagehand-server-v3` in `pnpm`/Turbo filters and
scripts.
  - Run local tasks from `packages/server-v3`.
- For SEA builds/tests, use binaries named
`stagehand-server-v3-<platform>-<arch>` and set `SEA_BINARY_NAME` if
needed.

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

<!-- End of auto-generated description by cubic. -->
2026-03-17 15:38:37 -07:00
Nick Sweeting
424efa1800
Real FlowLogger PR (several big commits were missing from #1824) (#1836)
# why

This is the real, recovered FlowLogger PR + improvements based on
yesterday's review session.

I accidentally force-pushed an earlier, incomplete branch state onto the
original flow logger PR and dropped several days of work. This PR
replaces that broken state with the actual recovered branch and the
follow-up fixes needed to make the design correct again.

<img width="1569" height="1015" alt="image"
src="https://github.com/user-attachments/assets/f99171fe-27df-488c-a87a-75605c2a3c1b"
/>


## what this PR does

This restores the intended v3 FlowLogger/EventStore design:

- every `V3` instance owns exactly one FlowLogger session
- every `V3` instance owns exactly one `EventStore`
- FlowLogger produces structured `FlowEvent`s on the instance bus
- EventStore consumes those events and fans them out to sinks
- the default query history is shallow and bounded so logging does not
grow memory without limit

The goal is a stable, queryable execution tree for
Stagehand/agent/CDP/LLM work that preserves parent/child relationships,
survives ALS re-entry, and does not let sink failures break main
execution.

## architecture

### FlowLogger

`packages/core/lib/v3/flowlogger/FlowLogger.ts`

FlowLogger owns:

- the `FlowEvent` model
- the `FlowLoggerContext` stored in AsyncLocalStorage
- method/closure wrappers: `wrapWithLogging(...)`, `runWithLogging(...)`
- re-entry helpers: `withContext(...)`, `resolveContext(...)`
- CDP event helpers
- LLM request/response helpers and middleware

FlowLogger is the event producer. It is responsible for building the
execution tree and maintaining the active parent stack. It is not
responsible for persistence or output destinations.

### EventStore

`packages/core/lib/v3/flowlogger/EventStore.ts`

EventStore owns:

- per-session sink registration
- query routing
- file-backed session directory setup
- bounded in-memory ancestry retention
- store lifecycle and teardown

Sink implementations live in
`packages/core/lib/v3/flowlogger/EventSink.ts`, and
prettifying/sanitization lives in
`packages/core/lib/v3/flowlogger/prettify.ts`.

EventStore is the consumer/router layer. It is intentionally
per-instance and single-session.

### V3 wiring

`packages/core/lib/v3/v3.ts`

In the `V3` constructor:

- `this.eventStore = new EventStore(this.sessionId, opts)`
- `this.flowLoggerContext = FlowLogger.init(this.sessionId, this.bus)`
- `this.bus.on("*", this.eventStore.emit)`

So FlowLogger always has a per-instance context, and the bus is the
handoff point between FlowLogger and EventStore.

## lifecycle

### FlowLogger lifecycle

1. `V3` creates the per-instance `FlowLoggerContext`
2. instrumented methods enter through `wrapWithLogging(...)` or
`runWithLogging(...)`
3. a started event is emitted
4. that event is pushed onto `parentEvents`
5. nested work inherits that parent stack through ALS
6. completed/error events are emitted on unwind
7. `V3.close()` clears the in-memory flow context

### EventStore lifecycle

1. `V3` creates one `EventStore(sessionId, opts)`
2. the default shallow in-memory query sink is attached immediately
3. optional sinks are attached based on runtime config
4. `V3` forwards wildcard bus events into the store
5. `destroy()` tears down the configured sinks

## config / runtime options

### always-on pieces

Every `V3` instance always gets:

- FlowLogger context
- shared event bus
- one EventStore
- one default shallow in-memory query sink

So instrumentation exists even if no human-visible sink is active.

### stderr sink

Enabled automatically when:

- `verbose: 2`
- `BROWSERBASE_FLOW_LOGS=1`

Behavior:

- writes prettified logs to stderr
- suppresses CDP events to keep interactive output high-signal
- does not retain history
- is best-effort only

### file sinks

Enabled automatically when:

- `BROWSERBASE_CONFIG_DIR` is set

Behavior:

- `JsonlFileEventSink` writes full events to `session_events.jsonl`
- `PrettyLogFileEventSink` writes prettified lines to
`session_events.log`
- `session.json` is written with sanitized options
- `sessions/latest` is maintained best-effort
- file sinks are write-only; `query()` returns `[]`

### queryable in-memory history

Default behavior:

- EventStore attaches a `ShallowInMemoryEventSink`
- retention limit is `500` events per session
- retained events keep ancestry metadata only
- retained `data` is intentionally stripped in the default sink

That shallow history is what pretty formatting uses to recover recent
ancestry without retaining screenshots/base64 payloads forever.

## memory impact

The main memory constraint is the default query sink.

What it retains:

- up to 500 recent shallow events per `V3` instance
- ids, timestamps, event types, parent ids, session id

What it does not retain by default:

- full screenshots
- large base64 blobs
- full historical payloads

Implications:

- memory scales roughly with `number_of_sessions * 500 shallow events`
- stderr sink does not retain history
- file sinks do not materially retain history in process memory beyond
normal stream buffering
- attaching `InMemoryEventSink` explicitly is an opt-in to full-payload
retention

## usage patterns

### use `wrapWithLogging(...)`

For class methods that should emit their own started/completed/error
envelope:

- `V3.act`
- `V3.extract`
- `V3.observe`
- page/understudy methods
- agent execute entrypoints

### use `runWithLogging(...)`

For closures or non-decorator code paths that still need a lifecycle
envelope.

### use `withContext(...)` / `resolveContext(...)`

For callback-driven or later async work:

- websocket callbacks
- CDP response/message dispatch
- detached async continuations

`currentContext` is strict and may throw when ALS is missing.
`resolveContext(...)` is the non-throwing lookup for “active ALS if
present, otherwise instance-owned fallback”.

### LLM logging is best-effort

If no flow context is active, LLM logging should no-op. Missing context
must not break model execution.

## reviewer expectations / edge cases

Please review this PR with these expectations in mind:

- ALS can legitimately be missing in later callbacks or detached async
work; that should not break execution unless a caller explicitly uses
strict `currentContext`
- there should be no global or multi-session fallback store; logging
belongs to a real `V3` instance/session
- parent-chain correctness matters more than sink behavior; events must
land under the right parent chain
- sink failures should not break the main library; sinks are
intentionally best-effort
- completion/error pretty lines should resolve back to the original
started-event ancestry, not synthetic completion ids
- `sessionId` often matches `browserbaseSessionId` today, but code
should not rely on that as a permanent invariant
- this PR is about FlowLogger/EventStore architecture and correctness,
not a model-default migration

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2026-03-17 15:02:12 -07:00
Sean McGuire
f56befe480
[chore]: bump "langchain/core" optional dep (#1841)
# why
- there is a vulnerability in `"langchain/core"` for versions lower than
`0.3.80` (more info
[here](https://www.cve.org/CVERecord?id=CVE-2025-68665))
- we have this package as an optional dep 
# what changed
- bumps the optional `"langchain/core"` dep to `^0.3.80`


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Bumps optional `@langchain/core` to ^0.3.80 to resolve a vulnerability
in earlier versions. Lockfile refreshed; no runtime changes.

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

<!-- End of auto-generated description by cubic. -->
2026-03-17 14:52:46 -07:00
Nick Sweeting
af9c92558f
Revert "[STG-1566] Flow logger schema and collection cleanup to prepare for Observability" (#1837)
Reverts browserbase/stagehand#1824

See https://github.com/browserbase/stagehand/pull/1836 for context

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Reverts the new flow-logging schema and event store, restoring the
previous session file–based logger. Updates agents, handlers, and evals
to use `SessionFileLogger` and removes the `sessionId` option from
`V3Options`. This undoes the STG-1566 observability changes to stabilize
logging.

- **Refactors**
  - Remove `packages/core/lib/v3/eventStore.ts` and related wiring.
- Restore `SessionFileLogger` in `flowLogger.ts` with helpers like
`formatCuaPromptPreview`, `formatLlmPromptPreview`, `logAction`, and
`logStagehandStep`.
- Replace `FlowLogger` usage with `SessionFileLogger` across
agents/handlers; update LLM clients (`OpenAICUAClient`,
`AnthropicCUAClient`, `GoogleCUAClient`, `AISdkClient`) to log
requests/responses with operation names.
- Simplify Understudy/CDP instrumentation; remove FlowLogger context in
`cdp.ts`; use `logAction` in `page.ts`.
- Remove `toTitleCase` and log explicit action names (e.g.,
`Understudy.<method>`, `Page.close`).
- Evals: switch to event-driven screenshot collection via the V3 event
bus; drop interval polling.
  - Remove `sessionId` handling and related code in `v3.ts`.

- **Migration**
  - Remove `sessionId` from `V3Options` if you were passing it.
- Any direct uses of the reverted `eventStore` or the new observability
schema are no longer available.

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

<!-- End of auto-generated description by cubic. -->
2026-03-17 02:07:28 -04:00
tkattkat
63ee247ac6
update search tool (#1834)
# Why

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

# What Changed

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


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

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

# Test Plan

- [x] Run agent with `useSearch: true` and a valid `BROWSERBASE_API_KEY`
— Browserbase search tool should return results
- [x] Run agent with `useSearch: true` and no Browserbase API key —
should throw `MissingEnvironmentVariableError`
2026-03-16 16:06:30 -07:00
Nick Sweeting
a3001a623b
[STG-1566] Flow logger schema and collection cleanup to prepare for Observability (#1824)
Refactored flow logging to an event-based system with `FlowLogger` and a
pluggable `eventStore`, improving LLM/CDP traces, action and screenshot
events, and concise prompt/response summaries. `V3` now carries a
`sessionId` and `flowLoggerContext`. Split the server into `server-v3`
and `server-v4` with separate OpenAPI, routes, and SEA builds, and
updated CI.

- **New Features**
- Added `eventStore` with `FileEventStore`, queries, aggregate metrics,
and bus attachment; exported `getEventStore`, `setEventStore`,
`destroyEventStore`, and `getFlowLogConfigDir`.
- Replaced `SessionFileLogger` with `FlowLogger` across agents and
handlers; added `wrapWithLogging` for `Page` actions; standardized event
names via `toTitleCase`.
- Switched to concise LLM summary helpers (`extractLlmPromptSummary`,
`extractLlmCuaPromptSummary`, `extractLlmCuaResponseSummary`) and
`FlowLogger.createLlmLoggingMiddleware`.
- `V3Options.sessionId` now used to associate flows; CDP calls are
linked to flow events for better correlation.
- Exported `FlowLogger`, `FlowEvent`, and `toTitleCase` from
`@core/v3/index`.

- **Migration**
- Replace `SessionFileLogger` and `@logAction` with `FlowLogger` methods
(`log*`, `wrapWithLogging`).
- Use `setEventStore/getEventStore` to plug custom storage
(`FileEventStore` by default); optionally pass `sessionId` in
`V3Options`.
- Update paths/scripts from `packages/server` to `packages/server-v3`;
use new binaries `stagehand-server-v3-*`/`stagehand-server-v4-*`.

<sup>Written for commit c35fdbd446a034056d52e3de54b2620b74f75156.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1824">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-03-16 16:04:01 -07:00
Sam F
6b19b8ceb9
[STG-1576] Sync MCP docs into Stagehand docs (#1818)
# why
Sync the Stagehand MCP docs with the Browserbase MCP docs for STG-1576.

# what changed
Copied the refreshed Browserbase MCP introduction and setup pages into
`packages/docs/v3/integrations/mcp`.

# test plan
`pnpm exec prettier --check packages/docs/docs.json
packages/docs/v3/integrations/mcp/introduction.mdx
packages/docs/v3/integrations/mcp/setup.mdx`; `pnpm --dir packages/docs
exec mint broken-links` (unrelated existing failures only); `pnpm lint`
fails in `packages/core` on an existing ESLint rule config issue.

---------

Co-authored-by: ci-test <ci-test@example.com>
2026-03-13 11:28:00 -07:00
Sean McGuire
ac4539ab6b
[chore]: refactor & fix lint for browse CLI (#1821) 2026-03-12 17:44:59 -07:00