Repository navigation
Implement Stagehand browser factories - #2519
miguelg719 merged 1 commit into
Conversation
|
There was a problem hiding this comment.
All reported issues were addressed across 6 files
Architecture diagram
sequenceDiagram
participant Consumer as Stagehand Consumer
participant Factories as localBrowser / browserbase
participant Resolver as resolveBrowserSource
participant Connect as connectBrowser
participant CDP as CDPClient.connect
participant BBSession as Browserbase Session Client
participant BBApi as Browserbase API
participant Handle as createStagehandBrowserHandle
Note over Consumer,Handle: Browser Acquisition Flow (launch)
Consumer->>Factories: localBrowser.launch(options)
alt Headless without downloadsPath
Factories->>Factories: Validate acceptDownloads<br/>requires downloadsPath
end
Factories->>Resolver: resolveSource({browser: {type:"local",...}})
Resolver->>Resolver: Launch Chrome instance via chrome-launcher
Resolver-->>Factories: {cdpUrl, close}
Factories->>Connect: connectBrowser({provider:"local", origin:"launched", source, extensionDir, afterConnect})
Connect->>CDP: connect(cdpUrl, extensionDir, discoveryTimeoutMs)
Note over CDP: Waits for Stagehand extension<br/>service-worker.js before resolving
CDP-->>Connect: CDPClient instance
alt Download behavior configured
Connect->>CDP: sendCommand("Browser.setDownloadBehavior",...)
end
Connect->>Handle: createHandle({provider, origin, attachment:{cdpClient,...}, close})
Note over Handle: Internals stored in WeakMap,<br/>closed=false, claimed=false
Handle-->>Connect: StagehandBrowser
Connect-->>Factories: StagehandBrowser
Factories-->>Consumer: StagehandBrowser
Note over Consumer,Handle: Browser Acquisition Flow (browserbase.launch)
Consumer->>Factories: browserbase.launch({apiKey, region,...})
alt Missing apiKey
Factories->>Factories: Zod parse error
end
Factories->>Resolver: resolveSource({apiKey, browser:{type:"browserbase",...}})
Resolver->>BBApi: createSession(...)
BBApi-->>Resolver: {sessionId, connectUrl}
alt No sessionId returned
Resolver-->>Factories: no sessionId
Factories->>Resolver: closeSource (cleanup)
Factories-->>Consumer: Error thrown
end
Resolver-->>Factories: {cdpUrl, browserbaseSessionId, close}
Factories->>Connect: connectBrowser({provider:"browserbase", origin:"launched", source, preloadedExtension, workerInitMetadata:{apiKey,browser:{sessionId}}})
Connect->>CDP: connect(cdpUrl, preloadedExtension, ...)
CDP-->>Connect: CDPClient
Connect->>Handle: createHandle({provider, origin, attachment:{cdpClient, workerInitMetadata}, close})
Handle-->>Connect: StagehandBrowser
Connect-->>Factories: StagehandBrowser
Factories-->>Consumer: StagehandBrowser
Note over Consumer,Handle: Browser Acquisition Flow (browserbase.connect)
Consumer->>Factories: browserbase.connect({apiKey, sessionId})
Factories->>BBSession: createSessionClient(apiKey)
BBSession->>BBApi: retrieveSession(sessionId)
BBApi-->>BBSession: {id, connectUrl, region}
alt Missing connectUrl
BBSession-->>Factories: Error "not available for connection"
end
BBSession-->>Factories: {sessionId, cdpUrl, region}
Factories->>Connect: connectBrowser({provider:"browserbase", origin:"connected", source, preloadedExtension, workerInitMetadata:{apiKey,browser:{sessionId,region}}})
Connect->>CDP: connect(cdpUrl, preloadedExtension, ...)
CDP-->>Connect: CDPClient
Note over Connect: origin='connected' → close<br/>callback does NOT close source
Connect->>Handle: createHandle({attachment:{cdpClient, workerInitMetadata}, close})
Handle-->>Connect: StagehandBrowser
Connect-->>Factories: StagehandBrowser
Factories-->>Consumer: StagehandBrowser
Note over Consumer,Handle: Claiming & Cleanup Flow
Consumer->>Consumer: claimStagehandBrowser(browser)
Consumer->>Handle: claimHandle(browser)
alt Handle already closed
Handle-->>Consumer: Error "Cannot attach to closed browser"
else Handle already claimed
Handle-->>Consumer: Error "already attached to Stagehand"
end
Handle-->>Consumer: ClaimedStagehandBrowser (attachment)
activate Consumer
Consumer->>Consumer: browser.close()
Consumer->>Handle: close() via WeakMap internals
Handle->>CDP: close()
alt origin === 'launched'
Handle->>Resolver: closeSource() (Chrome process / Browserbase session release)
else origin === 'connected'
Note over Handle: No resource cleanup —<br/>consumer doesn't own release
end
Note over Handle: closePromise cached<br/>ensures idempotent cleanup
deactivate Consumer
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
0ee2324 to
edd6d64
Compare
edd6d64 to
bd1edd5
Compare
There was a problem hiding this comment.
All reported issues were addressed across 7 files
Architecture diagram
sequenceDiagram
participant Client
participant Factories as Browser Factories
participant ResolveSource as resolveBrowserSource
participant CDPConnector as CDPClient.connect
participant BrowserProc as Chrome/Browser Process
participant BBAPI as Browserbase API
participant Handle as StagehandBrowserHandle
Note over Client,Handle: Internal browser factories (not in public SDK)
alt localBrowser.launch
Client->>Factories: localBrowser.launch(options)
Factories->>Factories: Zod parse LocalBrowserLaunchOptions
Factories->>ResolveSource: resolveBrowserSource({browser:{type:"local",...}})
ResolveSource->>BrowserProc: chrome-launcher: launch Chrome with flags
BrowserProc-->>ResolveSource: cdpUrl, close callback
ResolveSource-->>Factories: ResolvedBrowserSource
Factories->>CDPConnector: connectCdp({cdpUrl, extensionDir, discoveryTimeoutMs, serviceWorkerUrlIncludes})
CDPConnector->>BrowserProc: connect CDP, wait for extension service worker
BrowserProc-->>CDPConnector: CDPClient instance
alt download behavior configured
CDPConnector->>BrowserProc: Browser.setDownloadBehavior
end
CDPConnector-->>Factories: cdpClient
Factories->>Handle: createStagehandBrowserHandle({provider:"local",origin:"launched",attachment,close: cleanup})
Handle-->>Factories: StagehandBrowser
Factories-->>Client: browser
alt failure path (CDP connection fails)
Factories->>BrowserProc: closeSource (chrome-launcher close)
Factories-->>Client: throw error
end
else localBrowser.connect
Client->>Factories: localBrowser.connect(options)
Factories->>Factories: Zod parse LocalBrowserConnectOptions
Factories->>ResolveSource: create ResolvedBrowserSource from cdpUrl, keepAlive=true
Factories->>CDPConnector: connectCdp({cdpUrl, headers, extensionId/extensionDir})
CDPConnector->>BrowserProc: connect to existing CDP endpoint
BrowserProc-->>CDPConnector: CDPClient
CDPConnector-->>Factories: cdpClient
Factories->>Handle: createStagehandBrowserHandle({origin:"connected",close: only cdpClient.close})
Handle-->>Factories: StagehandBrowser
Factories-->>Client: browser
else browserbase.launch
Client->>Factories: browserbase.launch(options)
Factories->>Factories: Zod parse BrowserbaseLaunchOptions
Factories->>ResolveSource: resolveBrowserSource({apiKey, browser:{type:"browserbase",...}})
ResolveSource->>BBAPI: create session with extension
BBAPI-->>ResolveSource: sessionId, cdpUrl
ResolveSource-->>Factories: ResolvedBrowserSource with browserbaseSessionId
Factories->>CDPConnector: connectCdp({cdpUrl, preloadedExtension})
CDPConnector->>BBAPI: connect via cdpUrl (extension already loaded)
BBAPI-->>CDPConnector: CDPClient
CDPConnector-->>Factories: cdpClient
Factories->>Handle: createStagehandBrowserHandle({attachment: workerInitMetadata, origin:"launched", close: cleanup source+CDP})
Handle-->>Factories: StagehandBrowser
Factories-->>Client: browser
else browserbase.connect
Client->>Factories: browserbase.connect(options)
Factories->>Factories: Zod parse BrowserbaseConnectOptions
Factories->>BBAPI: createBrowserbaseSessionClient(apiKey).connectSession(sessionId)
BBAPI->>BBAPI: retrieveSession(sessionId)
BBAPI-->>Factories: session with cdpUrl, region
Factories->>CDPConnector: connectCdp({cdpUrl, preloadedExtension})
CDPConnector->>BBAPI: connect to existing session
BBAPI-->>CDPConnector: CDPClient
CDPConnector-->>Factories: cdpClient
Factories->>Handle: createStagehandBrowserHandle({origin:"connected", attachment: workerInitMetadata, close: only cdpClient.close})
Handle-->>Factories: StagehandBrowser
Factories-->>Client: browser
end
Note over Client,Handle: Browser claiming (one-time, after factory returns)
Client->>Factories: claimStagehandBrowser(browser)
Factories->>Handle: check closure and claimed flag
alt browser closed
Handle-->>Factories: throw "Cannot attach to closed browser"
else already claimed
Handle-->>Factories: throw "already attached"
else first claim
Handle-->>Factories: return attachment
Handle->>Handle: set claimed=true
end
Factories-->>Client: attachment (e.g., CDPClient + metadata)
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
bd1edd5 to
e9cd128
Compare
33f5014 to
b60079f
Compare
cb754f3 to
9d388fb
Compare
9d388fb to
5c3a8a1
Compare
5c3a8a1 to
18c5f91
Compare
# 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
# 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]>
# 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
## 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`
## 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
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
localBrowser.launch()andlocalBrowser.connect()factoriesbrowserbase.launch()andbrowserbase.connect()factoriesBrowserbase.SessionCreateParamssurface plus the client authenticationapiKeytypediscriminator from both local and Browserbase factory inputsbrowserSettingslaunch shapesignoreDefaultArgshandling for the default window-size flagkeepAliveon normal close and failed extension preparation without leaking the CDP transportcompatibility
Stagehandconstructor andinit()remain unchanged at this stack layerstack
Stagehand.create()init()lifecycletest plan
publintpassed