Repository navigation
Add Stagehand.create browser attachment - #2520
Conversation
|
There was a problem hiding this comment.
All reported issues were addressed across 5 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
e112f93 to
627fe38
Compare
627fe38 to
7a640e2
Compare
There was a problem hiding this comment.
All reported issues were addressed across 5 files
Architecture diagram
sequenceDiagram
participant Consumer as Consumer Code
participant SH as Stagehand (static create)
participant Factory as localBrowser / browserbase
participant BR as Browser (StagehandBrowser)
participant Claim as claimStagehandBrowser()
participant RPC as RPCClient
participant Worker as Worker (CDP Transport)
participant Legacy as Stagehand (constructor/init)
Note over Consumer,Legacy: NEW: Stagehand.create() entry point
Consumer->>SH: Stagehand.create({ browser, model, logging })
SH->>SH: Validate input & config schema
SH->>SH: isStagehandBrowser(browser)?
alt Browser from factory
SH->>Claim: claimStagehandBrowser(browser)
Claim-->>SH: claimedBrowser (CDP webSocketDebuggerUrl)
else Not from factory
SH-->>Consumer: TypeError thrown
end
SH->>SH: Construct internal Stagehand({ browser: { type: "cdp", cdpUrl } })
Note over SH: ownsRpcTransport = false<br/>attachedBrowser = browser<br/>resolvedBrowser = { keepAlive: true }
SH->>RPC: new RPCClient(claimedBrowser.cdpClient, timeout)
SH->>SH: register notification/listener handlers
SH->>RPC: send(stagehand.init, initParams)
RPC->>Worker: stagehand.init over CDP WebSocket
Worker-->>RPC: init response (pages, etc.)
RPC-->>SH: resolved
alt Error during init
SH->>RPC: close(closeTransport: false)
SH-->>Consumer: Error thrown
else Success
SH->>SH: browserContext = new BrowserContext(rpc)
SH-->>Consumer: stagehand (initialized = true)
end
Consumer->>SH: stagehand.close()
SH->>RPC: close(closeTransport: false)
Note over SH: Does NOT close browser CDP transport
SH-->>Consumer: resolved
Consumer->>BR: browser.close()
BR->>BR: Close actual browser process/CDP
BR-->>Consumer: resolved
Note over Consumer,Legacy: COMPATIBILITY: existing init() path unchanged
Consumer->>Legacy: new Stagehand({ browserCdpUrl, ... })
Legacy-->>Consumer: stagehand (uninitialized)
Consumer->>Legacy: stagehand.init()
Legacy->>Legacy: connectRPCClient (owns transport)
Legacy->>Worker: stagehand.init over own CDP transport
Worker-->>Legacy: init response
Legacy-->>Consumer: ready
Consumer->>Legacy: stagehand.close()
Legacy->>Legacy: closeBrowserSource() (closes transport)
Legacy-->>Consumer: done
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
c33ac0e to
457bff5
Compare
457bff5 to
df060c5
Compare
df060c5 to
bbdd5f9
Compare
bbdd5f9 to
edcf2c6
Compare
edcf2c6 to
587b09e
Compare
587b09e to
2777116
Compare
2777116 to
b463984
Compare
b463984 to
03d8ef6
Compare
03d8ef6 to
e61044d
Compare
e61044d to
d174da0
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 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
## 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
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
localBrowserandbrowserbaseawait Stagehand.create({ browser, ...config })StagehandBrowserSchemaandStagehandCreateOptionsSchemainclientSchemas.ts, with public types inferred from those schemasStagehand.create()input immediately at the client boundary, including nominal browser-handle validation and unknown-key rejectionapiKeyfor local browser handles while Browserbase handles retain their owned credential metadatastagehand.close()from closing the browser-owned transportinit()/create()lifecycle during independent SDK migrationscompatibility
new Stagehand(...)andawait stagehand.init()remain supportedStagehand.create()instance cannot re-enter the legacyinit()path after closestack
Stagehand.create()— this PRinit()lifecycletest plan
Stagehand.create()tests pass, including full-boundary Zod validationpublintpassStagehand.create, schemas, and factory types are present