Skip to content

Define TypeScript Stagehand browser contracts - #2517

Merged
miguelg719 merged 1 commit into
v4-spikefrom
feat/stagehand-browser-contract
Aug 1, 2026
Merged

miguelg719 merged 1 commit into
v4-spikefrom
feat/stagehand-browser-contract

Conversation

@miguelg719

@miguelg719 miguelg719 commented Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator

why

The Stagehand v4 browser lifecycle work in draft PR #2506 currently combines API design, transport changes, browser implementation, and the Stagehand.create() migration. This is the bottom PR in an incremental stack that isolates the browser contract for review before any runtime behavior is introduced.

Reference implementation: #2506

what changed

  • adds a dedicated packages/sdk-ts/src/browser/ module inside the TypeScript SDK
  • defines the nominal StagehandBrowser handle returned only by Stagehand browser factories
  • defines separate LocalBrowser and BrowserbaseBrowser launch/connect interfaces
  • defines browser input schemas in clientSchemas.ts, reusing protocol-generated schemas where possible
  • derives every browser option type with z.infer instead of maintaining parallel TypeScript shapes
  • adds compile-time contract tests to the TypeScript SDK suite
  • documents the intended localBrowser / browserbase / Stagehand.create() shape

intentionally not included

  • no browser launch or connection behavior
  • no CDP or RPC transport changes
  • no runtime factory exports
  • no changes to the current Stagehand constructor or init()
  • no public SDK exports

stack

  1. Define TypeScript Stagehand browser contracts #2517 TypeScript browser contract and module scaffold — this PR
  2. Add browser transport foundations #2518 Transport foundations
  3. Implement Stagehand browser factories #2519 Implement localBrowser and browserbase
  4. Add Stagehand.create browser attachment #2520 Add Stagehand.create()
  5. Migrate TypeScript consumers to Stagehand.create #2521 Migrate consumers
  6. Remove the legacy Stagehand lifecycle #2523 Remove the constructor/init() lifecycle

test plan

  • browser contract tests cover schema parsing, strict unknown-key rejection, and nominal handles
  • TypeScript SDK build passed
  • full pnpm check passed, including build, publint, lint, TypeScript, and docs validation

@changeset-bot

changeset-bot Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 9e025d2

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 7 files

Architecture diagram
sequenceDiagram
    participant Client as App Code
    participant Stagehand as Stagehand.create()
    participant LocalFactory as LocalBrowser
    participant BBF as BrowserbaseBrowser
    participant SBrowser as StagehandBrowser
    participant Proto as protocol types
    participant Test as Compile‑time Contract Tests

    Note over Client,Test: NEW: Stagehand v4 browser contract (types only, no runtime)

    Client->>LocalFactory: launch(options?: LocalBrowserLaunchOptions)
    Note right of LocalFactory: LocalBrowserLaunchOptions<br/>imported from protocol
    LocalFactory->>Proto: type check options shape
    Proto-->>LocalFactory: valid
    LocalFactory-->>Client: Promise<StagehandBrowser>
    Client->>SBrowser: (instance has provider, origin, closed, close())
    Client->>Stagehand: create({ browser: sb, model })
    Stagehand->>SBrowser: read provider ("local")
    SBrowser-->>Stagehand: ready
    Stagehand-->>Client: Stagehand instance

    opt Alternatively: Browserbase via connect
        Client->>BBF: connect(options: BrowserbaseConnectOptions)
        Note right of BBF: requires apiKey + sessionId
        BBF-->>Client: Promise<StagehandBrowser>
    end

    opt Alternatively: Browserbase via launch
        Client->>BBF: launch(options: BrowserbaseLaunchOptions)
        Note right of BBF: extends BrowserbaseSessionCreateParams
        BBF-->>Client: Promise<StagehandBrowser>
    end

    Note over SBrowser: Private brand symbol prevents<br/>ad‑hoc CDP connections

    alt Compile‑time verification
        Test->>Test: expectTypeOf checks
        Test->>SBrowser: verify StagehandBrowser shape
        Test->>LocalFactory: verify launch & connect signatures
        Test->>BBF: verify launch & connect signatures
        Test->>Proto: LocalBrowserLaunchOptions is extended
    end
Loading

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread packages/browser/package.json Resolved
Comment thread packages/sdk-ts/src/browser/index.ts Resolved
@miguelg719
miguelg719 force-pushed the feat/stagehand-browser-contract branch from ed05f04 to 7140f3b Compare July 30, 2026 21:40
@miguelg719 miguelg719 changed the title Define Stagehand browser contracts Define TypeScript Stagehand browser contracts Jul 30, 2026
@miguelg719
miguelg719 marked this pull request as draft July 30, 2026 21:42
@miguelg719
miguelg719 force-pushed the feat/stagehand-browser-contract branch from 7140f3b to 3c78efc Compare July 30, 2026 21:47
@miguelg719
miguelg719 marked this pull request as ready for review July 30, 2026 22:25

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 4 files

Architecture diagram
sequenceDiagram
    participant Consumer as Stagehand SDK Consumer
    participant BrowserMod as browser/ module
    participant Schemas as clientSchemas.ts
    participant Protocol as Protocol Schemas
    participant Tests as browser/contracts.test.ts

    Note over Consumer,Tests: Compile-time contract boundary only — no runtime behavior yet

    Consumer->>BrowserMod: imports LocalBrowser, BrowserbaseBrowser, StagehandBrowser
    BrowserMod->>BrowserMod: defines nominal brand symbol (stagehandBrowserBrand)
    BrowserMod->>Schemas: re-exports type aliases (LocalBrowserLaunchOptions etc.)
    Schemas->>Protocol: extends LocalBrowserLaunchOptionsSchema
    Schemas->>Schemas: defines new strict schemas (LocalBrowserConnect, BrowserbaseLaunch, BrowserbaseConnect)
    Schemas->>Schemas: derives TS types via z.infer
    Schemas-->>BrowserMod: exported type references
    BrowserMod-->>Consumer: returns factory interfaces with strongly-typed options

    Note over Consumer,Tests: Contract validation (compile-time checks)

    Tests->>BrowserMod: verifies StagehandBrowser is nominal (not structurally assignable)
    Tests->>BrowserMod: checks LocalBrowser.launch signature (optional options)
    Tests->>BrowserMod: checks LocalBrowser.connect signature (required cdpUrl)
    Tests->>BrowserMod: checks BrowserbaseBrowser.launch signature (required options)
    Tests->>BrowserMod: checks BrowserbaseBrowser.connect signature (required apiKey + sessionId)
    Tests->>Schemas: runs runtime schema .parse() calls
    alt Valid input
        Schemas-->>Tests: returns parsed output
    else Extra keys (strict mode)
        Schemas-->>Tests: throws ZodError
    end

    Note over Consumer,Tests: Intended future usage (documented but not wired)
    Note over Consumer: const browser = await localBrowser.launch({ headless: true })
    Note over Consumer: const stagehand = await Stagehand.create({ browser, model })
Loading

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread packages/sdk-ts/src/clientSchemas.ts Resolved
@miguelg719
miguelg719 requested a review from monadoid July 31, 2026 05:12
@miguelg719
miguelg719 force-pushed the feat/stagehand-browser-contract branch 2 times, most recently from 9e025d2 to a2adb08 Compare July 31, 2026 19:47
@miguelg719
miguelg719 requested a review from a team as a code owner July 31, 2026 19:47
@miguelg719
miguelg719 force-pushed the feat/stagehand-browser-contract branch from a2adb08 to 50b8556 Compare July 31, 2026 20:08
@miguelg719
miguelg719 force-pushed the feat/stagehand-browser-contract branch from 50b8556 to ec2e54f Compare July 31, 2026 20:27
@miguelg719
miguelg719 merged commit 32d852a into v4-spike Aug 1, 2026
21 checks passed
miguelg719 added a commit that referenced this pull request Aug 1, 2026
# why

Browser handles need to establish CDP connections and later hand those
connections to Stagehand without losing transport ownership. This is the
second PR in the browser lifecycle stack and contains only those
transport prerequisites.

Reference implementation: #2506

# what changed

- opens CDP connections with the built-in WebSocket runtime
- keeps a persistent post-connect socket error handler and forwards
failures into RPC shutdown
- lets an RPC client close without closing its underlying CDP transport
- adds focused discovery, connection, socket-error, and ownership tests

# compatibility

- existing `connectRPCClient()` behavior remains unchanged by default
- existing RPC close behavior still closes its transport unless
explicitly disabled
- no browser factories or Stagehand public API changes are introduced

# stack

1. #2517 — TypeScript browser contract and module scaffold
2. **Transport foundations** — this PR
3. #2519 Implement `localBrowser` and `browserbase`
4. #2520 Add `Stagehand.create()`
5. #2521 Migrate consumers
6. #2523 Remove the constructor/`init()` lifecycle

# test plan

- focused CDP/RPC tests: 36 passed
- full `pnpm build` passed
- full `pnpm check` passed, including docs validation
- SDK build and `publint` passed

---------

Co-authored-by: Sean McGuire <[email protected]>
miguelg719 added a commit that referenced this pull request Aug 1, 2026
# why

With the browser contract and transport ownership established, this
stack entry implements browser acquisition and extension readiness
without exposing the factories publicly or changing Stagehand yet.

Reference implementation: #2506

# what changed

- implements nominal browser handles with one-time Stagehand claiming
and idempotent cleanup
- implements internal `localBrowser.launch()` and
`localBrowser.connect()` factories
- implements internal `browserbase.launch()` and `browserbase.connect()`
factories
- parses every launch/connect input immediately with client-side Zod
schemas
- defines Browserbase launch options as the official
`Browserbase.SessionCreateParams` surface plus the client authentication
`apiKey`
- forwards the complete Browserbase session-create payload, including
future SDK fields accepted by the client schema
- rejects the legacy `type` discriminator from both local and
Browserbase factory inputs
- keeps local launch configuration owned by the TypeScript client
instead of the cross-language protocol schema
- accepts caller-owned Browserbase extension IDs at both the top-level
and `browserSettings` launch shapes
- skips extension upload and deletion when the caller supplies an
extension; Stagehand provisions and owns cleanup only for its fallback
extension
- accepts an explicit runtime extension ID when connecting to an
existing Browserbase session
- validates Browserbase SDK create/retrieve results and normalized
connection data with Zod-derived client schemas
- acquires browsers directly rather than routing factory calls through
the legacy browser-source resolver
- waits for the Stagehand extension/CDP transport before resolving each
factory promise
- adds Browserbase existing-session retrieval without taking release
ownership
- sanitizes Browserbase create/retrieve failures behind a typed session
error
- maps the full local launch option surface into Chrome flags
- preserves selective `ignoreDefaultArgs` handling for the default
window-size flag
- preserves launched-versus-connected resource ownership during cleanup
- honors `keepAlive` on normal close and failed extension preparation
without leaking the CDP transport

# compatibility

- factories remain internal and are not re-exported from the public SDK
- current `Stagehand` constructor and `init()` remain unchanged at this
stack layer
- existing browser-source behavior remains temporarily available to the
legacy lifecycle

# stack

1. #2517 — TypeScript browser contract and module scaffold
2. #2518 — transport foundations
3. **Implement browser factories** — this PR
4. #2520 — add `Stagehand.create()`
5. #2521 — migrate consumers
6. #2523 — remove the constructor/`init()` lifecycle

# test plan

- all applicable non-runtime SDK tests at this stack layer: 149 passed
- full workspace formatting, lint, typecheck, and build passed
- SDK build and `publint` passed
miguelg719 added a commit that referenced this pull request Aug 1, 2026
# why

The browser factories now resolve only after the extension transport is
ready. This stack entry introduces the new attachment lifecycle as an
additive public API while preserving the current constructor and
`init()` path for compatibility.

Reference implementation: #2506

# what changed

- publicly exports `localBrowser` and `browserbase`
- adds `await Stagehand.create({ browser, ...config })`
- defines `StagehandBrowserSchema` and `StagehandCreateOptionsSchema` in
`clientSchemas.ts`, with public types inferred from those schemas
- parses the complete `Stagehand.create()` input immediately at the
client boundary, including nominal browser-handle validation and
unknown-key rejection
- claims each browser for one Stagehand instance
- releases the claim when worker initialization fails so callers can
retry
- initializes the worker over the browser-owned CDP transport
- accepts an explicit worker-service `apiKey` for local browser handles
while Browserbase handles retain their owned credential metadata
- keeps `stagehand.close()` from closing the browser-owned transport
- exports browser option schemas, their inferred types, and
create-option types from the published SDK
- extends the packed-package contract to verify the new exports
- keeps cross-language parity strict for feature APIs while excluding
the intentionally language-specific `init()` / `create()` lifecycle
during independent SDK migrations

# compatibility

- `new Stagehand(...)` and `await stagehand.init()` remain supported
- a `Stagehand.create()` instance cannot re-enter the legacy `init()`
path after close
- no examples or existing consumers are migrated in this PR
- the breaking removal is deferred to the final stack entry

# stack

1. #2517 — TypeScript browser contract and module scaffold
2. #2518 — transport foundations
3. #2519 — browser factory implementation
4. **Additive `Stagehand.create()`** — this PR
5. #2521 Migrate consumers
6. #2523 Remove the constructor/`init()` lifecycle

# test plan

- focused `Stagehand.create()` tests pass, including full-boundary Zod
validation
- 137 non-runtime SDK tests pass on the final stack
- full workspace formatting, lint, and typecheck pass
- SDK build and `publint` pass
- generated declarations inspected; `Stagehand.create`, schemas, and
factory types are present
miguelg719 added a commit that referenced this pull request Aug 1, 2026
## Summary

Migrates the TypeScript SDK's examples, README, parity checks, and
browser-runtime smoke tests to the explicit browser lifecycle introduced
by the preceding stack:

```ts
const browser = await localBrowser.launch();
const stagehand = await Stagehand.create({ browser, model });
```

This keeps the compatibility lifecycle available for one more layer
while proving the new API against real local-browser startup and
representative consumers.

Browser cleanup is nested in `finally` blocks throughout the migrated
examples and smoke tests, so a failed `stagehand.close()` cannot leak a
local process or billable Browserbase session.

Reference spike: #2506

## Stack

- #2517 — browser contracts
- #2518 — transport foundations
- #2519 — browser factories
- #2520 — additive `Stagehand.create`
- **this PR** — consumer migration
- #2523 — remove the legacy constructor/init lifecycle

## Verification

- focused example-parity and local-browser smoke tests (15 passed)
- `pnpm --filter @browserbasehq/stagehand test:browser` (12 passed, 2
skipped)
- `pnpm build`
- `pnpm check`
miguelg719 added a commit that referenced this pull request Aug 1, 2026
## Summary

Completes the browser-lifecycle stack by making `Stagehand.create({
browser, ...config })` the sole TypeScript construction path and
removing browser launch configuration from the RPC contract.

- makes the `Stagehand` constructor private
- removes public `Stagehand.init()` and the legacy TypeScript
browser-source constructor exports/resolver
- removes the TypeScript `BrowserSource` union and legacy client-init
schema
- makes `stagehand.browser` the exact browser handle passed to
`Stagehand.create`
- keeps browser transport ownership with `localBrowser` / `browserbase`
- narrows RPC browser data to provider-neutral session metadata
(`sessionId` and optional `region`)
- removes the legacy `type` discriminator and Browserbase launch options
from worker initialization
- keeps protocol negotiation on `protocolVersion`; browser metadata is
not used for negotiation
- updates generated Python and Go worker-init models to the
provider-neutral metadata shape
- retains only the non-discriminated Browserbase session-create support
models needed by the current Python/Go generators; the deprecated source
model and its `type` field are gone
- guarantees integration cleanup still closes the browser if runtime
shutdown rejects
- strips internal test-only helpers from published declarations
- updates integration and object-wrapper fixtures to the final lifecycle

Reference spike: #2506

## Reviewer focus

The important semantic boundaries are:

1. `stagehand.close()` stops the Stagehand runtime, while
`browser.close()` owns browser/session cleanup.
2. Browser acquisition options remain client-side and never cross the
RPC boundary.
3. Worker browser metadata is session identity for cache/service
behavior, not contract negotiation.

## Stack

- #2517 — browser contracts
- #2518 — transport foundations
- #2519 — browser factories
- #2520 — additive `Stagehand.create`
- #2521 — consumer migration
- **this PR** — remove the legacy constructor/init lifecycle and narrow
RPC metadata

## Verification

- TypeScript SDK unit tests: 108 passed
- protocol tests: 317 passed
- server tests: 197 passed, 13 todo
- Python generated-model tests: 140 passed; generator drift check passed
- Go CI-equivalent test suite passed; generator drift check passed
- full workspace formatting, lint, typecheck, and build passed
- SDK build and `publint` passed
- docs checks passed
miguelg719 added a commit that referenced this pull request Aug 3, 2026
# why

Ports the merged TypeScript browser-lifecycle stack (#2517–#2523) to the
Go SDK. This bottom PR lands the internal plumbing the factory lifecycle
needs — borrow-don't-own transports and Browserbase session connect
semantics — with zero public API change.

# what changed

- adds transport ownership to `rpcClient`: shutdown still cancels,
rejects pending calls, and clears handlers, but only closes the
transport when owned
- adds `retrieveSession` (GET `/v1/sessions/{id}`) to the Browserbase
client with deliberately lenient validation (`id` required;
`connectUrl`/`region` optional)
- adds internal `connectSession` that never takes release ownership of
an existing session
- caller-supplied extension IDs suppress Stagehand extension
provisioning **and** cleanup on every path (success, create failure,
close)

# intentionally not included

- no exported identifier added or changed; legacy `New`/`Init`/`Close`
behavior is unchanged
- no factories, no `Browser` handle, no `Create`

# stack

1. **this PR — transport and Browserbase session foundations**
2. #2548 — browser factories and `stagehand.Create`
3. #2549 — remove the legacy lifecycle and migrate consumers

# test plan

- table tests for un-owned shutdown (transport left open, pending calls
still rejected), `httptest` coverage for `retrieveSession`, fake-API
cases proving caller extension IDs are never uploaded/deleted
- full package gates green: gofmt, `go vet`, `go build`, `go test`,
generator `--check`, examples compile, root `pnpm run test:unit`,
changeset check
miguelg719 added a commit that referenced this pull request Aug 3, 2026
## Summary

Completes the Go port of the browser-lifecycle stack (#2517–#2523) by
making `stagehand.Create(ctx, CreateOptions)` the sole construction
path, mirroring the TypeScript end state.

- removes `New`, `Init`, `StagehandClientInitParams`, the
`BrowserSource` union, and the public `ResolvedBrowserSource`; the
raw-CDP-with-headers path has no replacement (`ConnectLocalBrowser`
takes a bare CDP URL)
- `Browser()` returns the exact handle passed to `CreateOptions`
- `Stagehand.Close` never closes the CDP transport, Chrome process, or
Browserbase session; browser lifetime is exclusively
`Browser.Close(ctx)`; `Close` results are memoized for TS `closePromise`
parity
- updates `ErrNotInitialized` message to point at the new lifecycle
(exported var name unchanged)
- migrates all 7 examples and the live tests to launch → `Create` →
`client.Close(ctx)` → `browser.Close(ctx)` (deferred in that order so a
failed client close can't leak the process)
- updates the Go ast-grep example-parity patterns to the multi-value
`stagehand.Create` shape in the same commit (they gate TS CI)

## Reviewer focus

1. `Stagehand.Close` stops the runtime; `Browser.Close` owns
browser/session cleanup — under no configuration does Stagehand touch
the browser-owned transport.
2. Browser acquisition options stay client-side; `stagehand.init` wire
payload is unchanged (`models.gen.go` untouched, no regeneration).
3. Parity accessors remain exactly `{Browser, Context, Initialized}`;
the central `StagehandInitParams` literal stays in `stagehand.go`.

## Follow-up (not in this PR)

- `packages/docs/v4/**` Go snippets still show the deleted `New`/`Init`
lifecycle (~10 files); docs migration should follow once this stack
settles.

## Stack

- #2547 — transport and Browserbase session foundations
- #2548 — browser factories and `stagehand.Create`
- **this PR** — remove the legacy lifecycle and migrate consumers

## Verification

- full package gates green: gofmt, `go vet`, `go build`, `go test`,
generator `--check` + generator tests, all 7 examples compile
- root `pnpm run test:unit` green (ast-grep example-parity + sdk-parity
against the migrated Go examples/source)
- changeset check passed; live tests (`CHROME_PATH`) migrated and
exercised by CI

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Make `stagehand.Create(ctx, CreateOptions)` the only way to build the Go
client and finalize split lifecycles: the client stops the worker; the
`Browser` owns its cleanup. `Stagehand.Close` memoizes the first result
(including failures) for repeated or concurrent calls.

- **Refactors**
- Removed `New`, `Init`, `StagehandClientInitParams`, the
`BrowserSource` union, and public `ResolvedBrowserSource`; deleted the
legacy resolver and tests.
- `Stagehand.Browser()` returns the exact `*Browser` passed to `Create`;
the client never closes Chrome or a Browserbase session.
- Standardized factories: `LaunchLocalBrowser`, `ConnectLocalBrowser`,
`LaunchBrowserbase` (uses `BrowserbaseLaunchOptions`); factories
materialize the bundled extension and set `extensionDir` on `Browser`.
- Enforced local `KeepAlive` at the factory: `Browser.Close` terminates
a launched Chrome only when `KeepAlive` is false (covered by tests).
- Updated examples, live tests, and ast-grep rules to launch/connect →
`Create` → `client.Close(ctx)` → `browser.Close(ctx)`; Go parity now
uses `create()` (Python still `init()`).

- **Migration**
  - Replace:
    - `client := stagehand.New(...); client.Init(ctx)` with:
- `browser := stagehand.LaunchLocalBrowser(...) |
ConnectLocalBrowser(...) | LaunchBrowserbase(...)`
- `client, _ := stagehand.Create(ctx, stagehand.CreateOptions{Browser:
browser, ...})`
- Manage lifetimes separately: `defer client.Close(ctx)` and `defer
browser.Close(ctx)`.
- For existing CDP, use `ConnectLocalBrowser(ctx,
LocalBrowserConnectOptions{CDPURL: ...})`.
- For Browserbase, create via `LaunchBrowserbase(ctx,
stagehand.BrowserbaseLaunchOptions{APIKey: ...})`.

<sup>Written for commit ad12189.
Summary will update on new commits.</sup>

<a
href="https://cubic.dev/pr/browserbase/stagehand/pull/2549?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->
miguelg719 added a commit that referenced this pull request Aug 3, 2026
# why

Ports the merged TypeScript browser-lifecycle stack (#2517–#2523) to the
Python SDK. This bottom PR lands the entire new-lifecycle machinery as
internal, unexported code so it can be reviewed in isolation while the
legacy constructor/`init()` lifecycle stays fully green.

# what changed

- adds `stagehand/browser.py`: nominal `StagehandBrowser` handle
(token-guarded construction, one-time Stagehand claim, idempotent
memoized `close()`)
- implements internal `local_browser.launch()` /
`local_browser.connect()` factories that resolve only after the
Stagehand extension service worker is ready
- enforces launched-versus-connected ownership (`owns_source = launched
and not keep_alive`) with `ExceptionGroup` cleanup semantics mirroring
the TS `connectBrowser`
- implements local downloads via root-session
`Browser.setDownloadBehavior` (previously `NotImplementedError`)
- reserves `browserbase.launch()` / `browserbase.connect()` API shape as
`NotImplementedError` stubs — the Python SDK has never had Browserbase
support; worker metadata is shaped `{api_key, browser:
BrowserSessionMetadata}` so a future implementation needs no
`Stagehand.create` changes
- adds `RPCClient.close(close_transport=False)` so Stagehand can later
detach from a browser-owned transport
- slims `browser_source.py` to a legacy adapter re-binding the moved
Chrome launcher; all existing monkeypatch seams keep working

# intentionally not included

- no public API change; `__init__.py` exports untouched
- no changes to the `Stagehand` constructor, `init()`, or async-with
- no changes under `_generated/` (already synced by the merged TS stack)

# stack

1. **this PR — browser handle, factories, and transport detach
(internal)**
2. #2545 — replace the constructor/`init()` lifecycle with
`Stagehand.create` + browser factories
3. #2552 — implement Browserbase sessions

# test plan

- new `tests/test_browser.py` (374 lines): claim/release, ownership
matrix, launch flags, downloads, connect extension routing
- `RPCClient` `close_transport=False` coverage; existing legacy suites
pass unchanged
- full package gates green: `uv sync --locked`, `generate.py --check`,
`ruff format --check`, `ruff check`, `ty check`, `pytest`
miguelg719 added a commit that referenced this pull request Aug 3, 2026
## Summary

Completes the Python port of the browser-lifecycle stack (#2517–#2523)
by making `await Stagehand.create(browser=..., ...)` the sole
construction path, mirroring the TypeScript end state.

- makes `Stagehand()` unconstructible directly (module-private token;
`TypeError` points at `Stagehand.create`)
- removes `init()`, async-with, the flattened browser constructor
kwargs, the `BrowserSource` union models, and `browser_source.py`
- exports `local_browser`, `browserbase`, and `StagehandBrowser` from
the package root
- `stagehand.browser` returns the exact handle passed to `create`; a
failed `create` releases the claim so the same handle can be retried
- `stagehand.close()` never touches the browser or CDP socket —
browser/session lifetime is exclusively `browser.close()`
- worker init keeps the exact `StagehandInitParams` wire shape; handle
metadata overrides caller `api_key`, and local handles omit `browser`
entirely
- migrates all 7 examples, README, and the CI wheel-smoke script to
launch → create → `stagehand.close()` → `browser.close()` (browser close
in the outermost `finally`)
- updates the Python ast-grep example-parity patterns to the
`Stagehand.create` shape

## Reviewer focus

1. `stagehand.close()` stops the runtime; `browser.close()` owns browser
cleanup — under no configuration does Stagehand close the transport or
process.
2. Browser acquisition options stay client-side and never cross the RPC
boundary.
3. One-shot asyncio semantics: memoized `close()`, claim release under
failed `create`, concurrent-close safety.

## Stack

- #2544 — browser handle, factories, and transport detach (internal)
- **this PR** — replace the constructor/`init()` lifecycle with
`Stagehand.create`
- #2552 — implement Browserbase sessions

## Verification

- full Python package gates green: `generate.py --check`, `ruff format
--check`, `ruff check`, `ty check`, `pytest` (rewritten lifecycle suite
incl. wire-shape, claim-retry, and concurrent-close tests)
- repo `pnpm run test:unit` green (ast-grep example-parity + sdk-parity
against the migrated sources)
- changeset check passed; wheel smoke exercised by CI
`python-wheel-smoke`

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Make `await Stagehand.create(browser=...)` the only way to start the
Python client. Adds `local_browser` and `browserbase` factories, moves
browser lifetime to the browser handle, and hardens close/cancel and
launch validation (incl. Python 3.12’s eager task factory).

- **Refactors**
  - `Stagehand()` is no longer constructible; use `Stagehand.create`.
- Removed `init()`, async-with usage, and `BrowserSource` models;
deleted `browser_source.py`. `ResolvedBrowserSource` now lives in
`browser.py` with dead fields removed.
- Exported `local_browser`, `browserbase`, and `StagehandBrowser` from
`stagehand`.
- `stagehand.browser` returns the exact handle passed to `create`.
Failed or canceled `create` releases the claim and detaches the RPC
client with `close_transport=False`.
- `stagehand.close()` stops the runtime only, is safe under Python
3.12’s eager task factory, and never closes the browser or CDP socket.
- Removed `connect_rpc_client`; updated README, examples (incl.
`model_gateway.py`), tests, smoke script, and ast-grep rules (Python now
requires `Stagehand.create`).
- Hardened browser handle: stricter launch validation (viewport pairing,
list arg types), preserves explicit viewport when default flags are
ignored, and treats a vanished Chrome as exited on close.

- **Migration**
- Launch a browser: `browser = await local_browser.launch(...)` or
`browser = await browserbase.launch(api_key=...)`.
- Create the client: `stagehand = await
Stagehand.create(browser=browser, ...)`.
- Close in order: `await stagehand.close()` then `await browser.close()`
(put browser close in the outermost finally).
  - Remove any `async with Stagehand(...)` and calls to `init()`.

<sup>Written for commit 9fdb16d.
Summary will update on new commits.</sup>

<a
href="https://cubic.dev/pr/browserbase/stagehand/pull/2545?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->
miguelg719 added a commit that referenced this pull request Aug 6, 2026
…ext (#2617)

## Summary

Review follow-up for #2570, implemented. Three fixes and one test
cleanup; only functional change is the session-URL restoration.

- **Session/debug URLs on the v4 path** (the one functional gap):
`initStagehand` now creates the Browserbase session first via the shared
`launchRunnerProvidedBrowserbaseChrome()` creator and attaches with
`browserbase.connect({ apiKey, sessionId })`, instead of
`browserbase.launch` (which hides the session id behind the opaque
`StagehandBrowser` handle, #2517). `sessionUrl`/`debugUrl` flow into
every TaskResult and the Braintrust replay click-through again, and the
session is explicitly released (`REQUEST_RELEASE`) on cleanup and on
every init failure path — `browser.close()` on a connected handle only
disconnects.
- **`BenchHarnessContext` → discriminated union** (`sdk: "v4" | "v3"`):
the runner narrows on the discriminant instead of probing five optional
fields; the `v4Page ?? page` fallback is gone, and a legacy task
reaching a v4 context is an explicit `EvalsError` instead of `v3:
undefined`.
- **Dead `systemPrompt` parameter dropped** from `initStagehand` —
nothing passes it, and the v3 equivalent is agent-only.
- **Test fixtures off the deleted `combination` category** → `agent`,
the only non-deterministic category left after #2587.

Not touched, for reviewer attention on #2570 itself: the
`EVAL_VERIFIER_MODEL` / keyless-provider and Claude Code result-parsing
commits are orthogonal to running a/e/o on v4 (they only affect the
agent/external-harness grading paths and change nothing unless the env
var is set) — candidates for splitting into their own PR.

## Verification

- typecheck, fmt, and 410/410 unit tests green
- LOCAL end-to-end through the built CLI: `run dropdown -e local -t 1 -m
google/gemini-2.5-flash` → **1/1 passed** (first full v4 pass through
the harness; requires `packages/extension` built for the local launch's
extension preload)
- BROWSERBASE connect path not exercised here (no key in this
environment) — needs one `run dropdown -e browserbase -t 1` to confirm
sessionUrl lands in results

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Restores session and debug URLs for v4 eval runs by creating Browserbase
sessions first and connecting, and simplifies the harness context with
an explicit v3/v4 split for clearer task handling.

- **Bug Fixes**
- Restored `sessionUrl` and `debugUrl` for v4 tasks. `initStagehand` now
creates the session via `launchRunnerProvidedBrowserbaseChrome` and
attaches with `browserbase.connect({ apiKey, sessionId })`.
  - Releases the session on cleanup and on init failure paths.

- **Refactors**
- `BenchHarnessContext` is now a discriminated union (`sdk: "v4" |
"v3"`). Removes `v4Page ?? page` fallback and throws on legacy tasks
reaching the v4 context.
- Dropped the unused `systemPrompt` from `initStagehand` in
`@browserbasehq/stagehand` v4 flow.
  - Moved legacy test fixtures from `combination` to `agent`.

<sup>Written for commit e31cb72.
Summary will update on new commits.</sup>

<a
href="https://cubic.dev/pr/browserbase/stagehand/pull/2617?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants