Skip to content

Add browser transport foundations - #2518

Merged
miguelg719 merged 3 commits into
feat/stagehand-browser-contractfrom
feat/stagehand-browser-transport
Aug 1, 2026
Merged

miguelg719 merged 3 commits into
feat/stagehand-browser-contractfrom
feat/stagehand-browser-transport

Conversation

@miguelg719

@miguelg719 miguelg719 commented Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator

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. Define TypeScript Stagehand browser contracts #2517 — TypeScript browser contract and module scaffold
  2. Transport foundations — this PR
  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

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

@changeset-bot

changeset-bot Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 2cb90e3

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 8 files

Architecture diagram
sequenceDiagram
    participant Client as Client Code
    participant RPC as RPCClient
    participant CDP as CDPClient
    participant Disc as Browser Discovery (fetch)
    participant WS as WebSocket (ws)
    participant Browser as Browser Endpoint

    Note over Client,Browser: Transport Foundations Flow (PR #2518)

    Client->>RPC: connectRPCClient({ cdpUrl, cdpHeaders? })
    RPC->>CDP: connect({ cdpUrl, cdpHeaders })
    Note over CDP: NEW: cdpHeaders passthrough

    alt cdpHeaders provided
        CDP->>Disc: resolveBrowserWebSocketUrl(url, { headers })
        Note over Disc: NEW: Passes Authorization and other headers
        Disc->>Browser: GET /json/version (with headers)
        Browser-->>Disc: Response (webSocketDebuggerUrl)
        Disc-->>CDP: resolved WebSocket URL
        CDP->>WS: new WebSocket(url, { headers })
        Note over WS: NEW: Uses Node `ws` for header support
    else no cdpHeaders
        CDP->>Disc: resolveBrowserWebSocketUrl(url)
        Disc->>Browser: GET /json/version (no headers)
        Browser-->>Disc: Response
        Disc-->>CDP: resolved URL
        CDP->>WS: new WebSocket(url)  (unchanged)
    end

    WS->>Browser: WebSocket handshake with headers (if any)
    Browser-->>WS: Connected
    WS-->>CDP: open event
    CDP-->>RPC: CDPClient ready
    RPC-->>Client: RPCClient instance

    Note over Client,RPC: RPC Close with Transport Ownership Option

    Client->>RPC: close(reason, { closeTransport: false })
    Note over RPC: NEW: Options parameter
    RPC->>RPC: Mark closed, clear handlers
    alt closeTransport === false
        RPC->>CDP: (skips cdp.close())
        Note over CDP: Transport remains open for handoff
        CDP-->>Browser: Connection stays active
    else closeTransport === true (default)
        RPC->>CDP: close()
        CDP->>WS: close()
        WS-->>Browser: Connection terminated
    end
    RPC-->>Client: Closed (detached)
Loading

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

Re-trigger cubic

Comment thread packages/sdk-ts/src/rpcClient.ts Resolved
Comment thread packages/sdk-ts/src/cdpClient.ts Resolved
Comment thread packages/sdk-ts/src/cdpClient.ts Resolved
@miguelg719
miguelg719 force-pushed the feat/stagehand-browser-transport branch from 39bbc88 to 58c843e Compare July 30, 2026 21:40
@miguelg719
miguelg719 marked this pull request as draft July 30, 2026 21:42
@miguelg719
miguelg719 force-pushed the feat/stagehand-browser-transport branch from 58c843e to 9d3cf34 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.

No issues found across 8 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.
Architecture diagram
sequenceDiagram
    participant Client as Client/Test
    participant RPC as RPCClient
    participant CDP as CDPClient
    participant Fetch as fetch()
    participant BrowserHTTP as Browser /json/version
    participant WS as ws WebSocket
    participant ManualCDP as ManualCDPTransport (Test)

    Note over Client,ManualCDP: NEW CDP Connection with Headers

    Client->>RPC: connectRPCClient({ cdpUrl, cdpHeaders })
    RPC->>CDP: CDPClient.connect({ cdpUrl, cdpHeaders })
    CDP->>CDP: resolveBrowserWebSocketUrl(url, { headers })

    alt headers provided
        CDP->>Fetch: fetch("/json/version", { headers })
        Fetch->>BrowserHTTP: GET /json/version with Authorization/other
        BrowserHTTP-->>Fetch: { webSocketDebuggerUrl }
        Fetch-->>CDP: version response
    else headers omitted
        CDP->>Fetch: fetch("/json/version")
        Fetch->>BrowserHTTP: GET /json/version (no custom headers)
        BrowserHTTP-->>Fetch: { webSocketDebuggerUrl }
        Fetch-->>CDP: version response
    end

    CDP->>WS: new WebSocket(webSocketDebuggerUrl, { headers })
    Note over CDP,WS: Uses Node "ws" runtime for header support
    WS->>BrowserHTTP: WebSocket handshake with custom headers
    BrowserHTTP-->>WS: Connection established
    WS-->>CDP: socket opened
    CDP-->>RPC: CDPClient instance
    RPC-->>Client: RPCClient instance

    Note over Client,ManualCDP: RPC Close Without Transport Ownership

    Client->>RPC: close(error, { closeTransport: false })
    RPC->>RPC: Mark closed, clear handlers
    RPC->>CDP: Detach listeners (onmessage, onclose, onerror)
    alt closeTransport default true (not set)
        RPC->>CDP: cdp.close()
    else closeTransport false (explicit)
        RPC->>CDP: Skip cdp.close()
        Note over RPC,ManualCDP: Transport ownership retained by caller
    end
    RPC-->>Client: (no return)

    Note over ManualCDP: Test verification
    Client->>ManualCDP: cdp.closeCalls
    ManualCDP-->>Client: 0
Loading

Re-trigger cubic

@miguelg719
miguelg719 force-pushed the feat/stagehand-browser-transport branch from 9d3cf34 to 1ea8905 Compare July 31, 2026 19:11
@miguelg719
miguelg719 force-pushed the feat/stagehand-browser-transport branch from 1ea8905 to 450254d Compare July 31, 2026 19:47
@miguelg719
miguelg719 force-pushed the feat/stagehand-browser-transport branch from 450254d to 3fbb89e Compare July 31, 2026 20:08
@miguelg719
miguelg719 force-pushed the feat/stagehand-browser-transport branch from 3fbb89e to a17c456 Compare July 31, 2026 20:27
Comment thread packages/sdk-ts/src/rpcClient.ts Resolved
Comment thread packages/sdk-ts/src/rpcClient.ts Resolved
@miguelg719
miguelg719 merged commit 3a20152 into v4-spike Aug 1, 2026
21 checks passed
miguelg719 added a commit that referenced this pull request Aug 1, 2026
# 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. **#2517 TypeScript browser contract and module scaffold** — this PR
2. #2518 Transport foundations
3. #2519 Implement `localBrowser` and `browserbase`
4. #2520 Add `Stagehand.create()`
5. #2521 Migrate consumers
6. #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
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
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.

2 participants