Repository navigation
[feat]: add keepAlive param - #1672
Conversation
🦋 Changeset detectedLatest commit: 3887d8f The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
@seanmcguire12 I have started the AI code review. It will take a few minutes to complete. |
There was a problem hiding this comment.
No issues found across 7 files
Confidence score: 5/5
- Automated review surfaced no issues in the provided summaries.
- No files require special attention.
Architecture diagram
sequenceDiagram
participant User as User Script
participant V3 as Stagehand V3 Instance
participant Guard as Process Guards (SIGINT/Error)
participant Local as Local Chrome Process
participant BBApi as Browserbase API / Proxy
Note over User,V3: Initialization with keepAlive: true
User->>V3: NEW: init({ keepAlive: true })
alt Launch: LOCAL
V3->>Local: Spawn Chrome
V3->>Local: NEW: unref() (Allows Node to exit independently)
Note right of Local: NEW: handleSIGINT: false (Chrome ignores Ctrl+C)
else Launch: BROWSERBASE
V3->>BBApi: NEW: Create session (keepAlive: true)
end
V3-->>User: Context Ready
Note over User,Guard: Runtime / Shutdown Scenarios
alt Scenario A: Graceful Close
User->>V3: close()
else Scenario B: Process Signal/Error
Guard->>V3: _immediateShutdown(reason)
end
V3->>V3: Check keepAlive status
alt keepAlive is TRUE
Note over V3,Local: Local: Skip chrome.kill() and profile deletion
Note over V3,BBApi: Remote: Skip apiClient.end()
V3-->>User: Resolve (Browser stays open)
else keepAlive is FALSE (Default)
V3->>Local: CHANGED: Kill Chrome & delete temp profile
V3->>BBApi: CHANGED: apiClient.end() / terminate session
V3-->>User: Resolve (Browser closed)
end
opt Scenario B Error Path
Guard->>User: Re-throw original Exception/Rejection
end
Linked issue analysis
Linked issue: STG-1338: add keepAlive param
| Status | Acceptance criteria | Notes |
|---|---|---|
| ✅ | Add optional boolean keepAlive parameter in stagehand constructor params (default false) | Added V3Options keepAlive and this.keepAlive resolution |
| ✅ | Constructor keepAlive overrides browserbaseSessionCreateParams.keepAlive when both provided | Constructor resolves opts.keepAlive ?? sessionCreateParams.keepAlive |
| ✅ | Update local launch to pass chrome launcher handleSIGINT based on keepAlive | Added handleSIGINT param and pass !keepAlive from V3 |
| ✅ | Unref chrome child process after launch so Node can exit while chrome stays open when keepAlive true | Calls chrome.process?.unref() when keepAlive is true |
| ✅ | stagehand.close() skips apiClient.end() when keepAlive true | shutdownBrowserSession avoids endApiClient when keepAlive |
| ✅ | keepAlive:true keeps browser alive on uncaught error, SIGTERM/SIGINT, and explicit stagehand.close() | Shutdown guards and shutdown helpers honor keepAlive |
| ✅ | Propagate resolved keepAlive to Browserbase session creation (constructor override respected) | Builds effectiveSessionParams including resolved keepAlive |
| ✅ | Refactor shutdown into focused modules that honor keepAlive and use a 4s hard timeout | Added shutdown modules and 4000ms hard timeout in guards |
| ✅ | Add tests validating behavior across scenarios (unhandledRejection/uncaughtException, SIGTERM/SIGINT, stagehand.close()) and envs (local, bb direct WS, bb via API) | Playwright tests and helper/child scripts added for scenarios/envs |
| ✅ | Document keepAlive in public types with note it overrides session param | Types file includes doc comment noting override behavior |
Greptile OverviewGreptile SummaryThis PR adds a new Key Changes:
Architecture: Confidence Score: 4/5
Important Files Changed
Sequence DiagramsequenceDiagram
participant User
participant V3
participant Chrome/Browserbase
participant Supervisor
User->>V3: new V3({keepAlive: false})
User->>V3: init()
V3->>Chrome/Browserbase: launch/connect
Chrome/Browserbase-->>V3: ws URL
V3->>Supervisor: spawn detached process
V3->>Supervisor: send config via IPC
Supervisor->>Supervisor: start PID polling
Supervisor-->>V3: ready acknowledgement
V3-->>User: init complete
Note over User,Supervisor: Normal operation
alt keepAlive: false (parent crashes)
User->>V3: crash/signal/error
Note over V3: parent dies
Supervisor->>Supervisor: stdin/IPC closes
Supervisor->>Chrome/Browserbase: kill Chrome / REQUEST_RELEASE
Supervisor->>Supervisor: cleanup temp profile
else keepAlive: true (parent crashes)
User->>V3: crash/signal/error
Note over V3: parent dies
Note over Chrome/Browserbase: remains running
Note over Supervisor: not spawned
else keepAlive: false (normal close)
User->>V3: close()
V3->>Supervisor: send exit message
V3->>Chrome/Browserbase: kill Chrome / end session
V3->>V3: cleanup resources
else keepAlive: true (normal close)
User->>V3: close()
Note over V3: skip browser shutdown
V3->>V3: cleanup resources only
Note over Chrome/Browserbase: remains running
end
|
Additional Comments (1)
|
|
@seanmcguire12 I have started the AI code review. It will take a few minutes to complete. |
There was a problem hiding this comment.
cubic analysis
3 issues found across 10 files
Confidence score: 2/5
- Signal handling in
packages/core/lib/v3/shutdown/shutdownGuards.tscan leave the process hanging indefinitely after SIGINT/SIGTERM because default exit is overridden without a finalprocess.exit(), which is a concrete user-facing shutdown failure. - Repeated SIGINT/SIGTERM are swallowed in
packages/core/lib/v3/shutdown/shutdownGuards.ts, preventing users from force-exiting during a stuck shutdown, compounding the risk. - There’s a race in
packages/core/lib/v3/v3.tswhereshutdownBrowserSessionruns before the_isClosingguard, so concurrentclose()calls can conflict during signal-triggered shutdown. - Pay close attention to
packages/core/lib/v3/shutdown/shutdownGuards.tsandpackages/core/lib/v3/v3.ts- shutdown/close sequencing can hang or race.
Prompt for AI agents (all issues)
Check if these issues are valid — if so, understand the root cause of each and fix them.
<file name="packages/core/lib/v3/shutdown/shutdownGuards.ts">
<violation number="1" location="packages/core/lib/v3/shutdown/shutdownGuards.ts:33">
P1: After SIGINT/SIGTERM handling, the process will hang indefinitely. `process.on('SIGINT')` overrides Node's default exit behavior, but after shutdown completes (or the 4s hard timeout fires), neither `process.exit()` nor signal re-emission occurs. In a browser automation context there will almost certainly be active handles (WebSocket connections, etc.) keeping the event loop alive.
The `uncaughtException`/`unhandledRejection` handlers correctly re-throw via `setImmediate` to crash the process, but the signal handlers lack an equivalent exit mechanism.</violation>
<violation number="2" location="packages/core/lib/v3/shutdown/shutdownGuards.ts:44">
P2: Repeated SIGINT/SIGTERM signals are silently swallowed, preventing force-exit. Since `process.on` (not `process.once`) is used and the `shuttingDown` guard short-circuits on subsequent signals, the user cannot force-kill the process with a second Ctrl+C if shutdown stalls. The common convention is to force-exit on the second signal.</violation>
</file>
<file name="packages/core/lib/v3/v3.ts">
<violation number="1" location="packages/core/lib/v3/v3.ts:1348">
P2: Race condition: `shutdownBrowserSession` is called before the re-entry guard (`_isClosing` check). If `close()` is called concurrently (e.g., user calls `close()` while signal handler triggers `_immediateShutdown`), both invocations can reach `shutdownBrowserSession` before either sets `_isClosing = true`, potentially calling `apiClient.end()` twice on an already-ended client.
Move `shutdownBrowserSession` call after the re-entry guard or after setting `_isClosing = true` to prevent duplicate API client shutdown attempts.</violation>
</file>
Linked issue analysis
Linked issue: STG-1338: add keepAlive param
| Status | Acceptance criteria | Notes |
|---|---|---|
| ✅ | Add optional boolean keepAlive parameter in stagehand constructor params (default false) | Added V3Options keepAlive and this.keepAlive resolution |
| ✅ | Constructor keepAlive overrides browserbaseSessionCreateParams.keepAlive when both provided | Constructor resolves opts.keepAlive ?? sessionCreateParams.keepAlive |
| ✅ | Update local launch to pass chrome launcher handleSIGINT based on keepAlive | Added handleSIGINT param and pass !keepAlive from V3 |
| ✅ | Unref chrome child process after launch so Node can exit while chrome stays open when keepAlive true | Calls chrome.process?.unref() when keepAlive is true |
| ✅ | stagehand.close() skips apiClient.end() when keepAlive true | shutdownBrowserSession avoids endApiClient when keepAlive |
| ✅ | keepAlive:true keeps browser alive on uncaught error, SIGTERM/SIGINT, and explicit stagehand.close() | Shutdown guards and shutdown helpers honor keepAlive |
| ✅ | Propagate resolved keepAlive to Browserbase session creation (constructor override respected) | Builds effectiveSessionParams including resolved keepAlive |
| ✅ | Refactor shutdown into focused modules that honor keepAlive and use a 4s hard timeout | Added shutdown modules and 4000ms hard timeout in guards |
| ✅ | Add tests validating behavior across scenarios (unhandledRejection/uncaughtException, SIGTERM/SIGINT, stagehand.close()) and envs (local, bb direct WS, bb via API) | Playwright tests and helper/child scripts added for scenarios/envs |
| ✅ | Document keepAlive in public types with note it overrides session param | Types file includes doc comment noting override behavior |
Architecture diagram
sequenceDiagram
participant User
participant V3 as Stagehand V3
participant SG as Shutdown Guards
participant LC as Local Chrome
participant BB as Browserbase API
Note over User,BB: Initialization Phase
User->>V3: new V3({ keepAlive: true/false })
V3->>SG: NEW: installShutdownGuards()
alt Local Browser
V3->>LC: CHANGED: launchLocalChrome(handleSIGINT: !keepAlive)
opt NEW: keepAlive is true
V3->>LC: NEW: process.unref() (Allow Node to exit)
end
else Browserbase
V3->>BB: CHANGED: createSession(keepAlive)
end
Note over User,BB: Termination Flow (Signal, Error, or close())
alt Signal (SIGINT/SIGTERM)
SG->>V3: NEW: shutdownAll(reason)
else Explicit Close
User->>V3: close()
end
V3->>V3: NEW: shutdownStagehandResources() (CDP/Logs)
alt NEW: keepAlive is FALSE (Default)
alt Local
V3->>LC: CHANGED: Kill process & cleanup UserDataDir
else Browserbase
V3->>BB: CHANGED: apiClient.end()
end
else NEW: keepAlive is TRUE
Note over V3,LC: Skip process kill / profile deletion
Note over V3,BB: Skip apiClient.end()
end
V3->>V3: NEW: finalizeStagehandShutdown() (Reset internal state)
alt SIGINT/SIGTERM with keepAlive
SG->>SG: NEW: Hold event loop (4s max) for clean state reset
else Uncaught Exception
SG->>User: Re-throw error after best-effort resource cleanup
end
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
|
@seanmcguire12 I have started the AI code review. It will take a few minutes to complete. |
There was a problem hiding this comment.
cubic analysis
2 issues found across 10 files
Confidence score: 3/5
- Potential for concurrent
shutdownAllcalls becauseshuttingDownonly guards SIGINT/SIGTERM paths inpackages/core/lib/v3/shutdown/shutdownGuards.ts, which could lead to racey or duplicated shutdown behavior. - Exception/rejection handlers in
packages/core/lib/v3/shutdown/shutdownGuards.tslack the hard timeout used by signal handlers, so a hungshutdownAllmay cause the process to hang indefinitely. - These are medium-severity runtime risks in shutdown paths, so some caution is warranted before merging.
- Pay close attention to
packages/core/lib/v3/shutdown/shutdownGuards.ts- shared shutdown guard and timeout coverage.
Prompt for AI agents (all issues)
Check if these issues are valid — if so, understand the root cause of each and fix them.
<file name="packages/core/lib/v3/shutdown/shutdownGuards.ts">
<violation number="1" location="packages/core/lib/v3/shutdown/shutdownGuards.ts:51">
P1: Exception/rejection handlers lack the hard timeout that signal handlers have. If `shutdownAll` hangs (e.g., broken CDP connection), the process will hang indefinitely because the re-throw in `.finally()` only fires after the promise settles. Consider wrapping these calls in `runShutdownWithKeepAlive` (without signal re-emission) or applying a `Promise.race` with a timeout, similar to the signal path.</violation>
<violation number="2" location="packages/core/lib/v3/shutdown/shutdownGuards.ts:86">
P1: Race condition: `shuttingDown` guard is not shared between signal and exception/rejection handlers, allowing concurrent `shutdownAll` calls.
The `shuttingDown` flag only guards SIGINT/SIGTERM paths (via `startShutdown`), but `onUncaughtException` and `onUnhandledRejection` bypass it entirely, calling `opts.shutdownAll()` directly. If a signal and an exception fire in quick succession, `shutdownAll` can run concurrently — potentially double-closing browser connections or API clients.
Consider checking (and setting) `shuttingDown` at the top of all four handlers, or extracting a single entry-point that all handlers route through.</violation>
</file>
Linked issue analysis
Linked issue: STG-1338: add keepAlive param
| Status | Acceptance criteria | Notes |
|---|---|---|
| ✅ | Add optional boolean keepAlive parameter in the Stagehand V3 constructor params (defaults to false). | Added keepAlive option and constructor resolves it |
| ✅ | Constructor keepAlive overrides browserbaseSessionCreateParams.keepAlive when both are provided. | Constructor uses opts.keepAlive ?? browserbaseSessionCreateParams.keepAlive |
| ✅ | Update local launch to pass Chrome launcher's handleSIGINT based on keepAlive (v3.ts and local.ts) to prevent Chrome being killed on Ctrl+C when keepAlive:true. | Added handleSIGINT param and v3 passes !keepAlive |
| ✅ | Unref() the Chrome child process after launch so Node can exit while Chrome stays open when keepAlive:true. | Calls chrome.process?.unref() when keepAlive true |
| ✅ | stagehand.close() skips apiClient.end() when keepAlive:true. | close() delegates to shutdownBrowserSession which returns early if keepAlive |
| ✅ | Setting keepAlive:true keeps browser alive for uncaught errors (unhandledRejection/uncaughtException). | Installed guards for unhandled errors and shutdown skips browser teardown |
| ✅ | Setting keepAlive:true keeps browser alive for SIGTERM/SIGINT. | SIGINT/SIGTERM guards + local handleSIGINT logic and shutdown skip |
| ✅ | Setting keepAlive:true keeps browser alive when user explicitly calls stagehand.close(). | close() uses shutdownBrowserSession which returns early on keepAlive |
| ✅ | Propagate keepAlive into browserbase session creation so browserbase sessions honor keepAlive. | Effective session params include resolved keepAlive when set |
| ✅ | Split teardown into shutdownBrowser and shutdownStagehand modules, install process guards with a 4s hard timeout and keep-alive interval. | Added shutdown modules and guards with 4000ms hard timeout |
| ✅ | Add tests validating keepAlive behavior across scenarios: unhandledRejection/uncaughtException, SIGTERM/SIGINT, stagehand.close(), and across browser configs (local, browserbase WS, browserbase via API). | Comprehensive test files covering scenarios and envs were added |
Architecture diagram
sequenceDiagram
participant User as User / Node Process
participant Guards as ShutdownGuards
participant V3 as Stagehand V3
participant S_Browser as shutdownBrowser.ts
participant S_Internal as shutdownStagehand.ts
participant LocalBrowser as Local Chrome
participant BB_API as Browserbase API
Note over User,BB_API: Initialization Phase
User->>V3: new V3({ keepAlive: true })
V3->>V3: NEW: Resolve keepAlive (Constructor > Params)
alt Local Browser
V3->>LocalBrowser: NEW: launchLocalChrome(handleSIGINT: !keepAlive)
opt NEW: keepAlive is true
V3->>LocalBrowser: chrome.process.unref()
end
else Browserbase
V3->>BB_API: NEW: Create session with keepAlive param
end
Note over User,BB_API: Shutdown Phase (SIGINT, Error, or .close())
User->>Guards: SIGINT / Uncaught Exception
Guards->>Guards: NEW: Start 4s hard timeout & Keep-alive interval
Guards->>V3: _immediateShutdown(reason)
V3->>S_Browser: CHANGED: shutdownBrowserSession / shutdownLocalBrowser
alt NEW: keepAlive is true
S_Browser-->>V3: No-op (Browser stays running)
else keepAlive is false (Default)
S_Browser->>BB_API: CHANGED: apiClient.end()
S_Browser->>LocalBrowser: CHANGED: chrome.kill() & cleanupUserDataDir()
end
V3->>S_Internal: NEW: shutdownStagehandResources()
S_Internal-->>V3: Close loggers, unhook CDP, close context
V3->>V3: NEW: finalizeStagehandShutdown() (Reset internal state)
alt NEW: Process Signal Logic
Guards->>User: Re-emit signal (SIGINT/SIGTERM)
else NEW: Error Logic
Guards->>User: Rethrow Uncaught Exception
end
Note over Guards: If 4s passed: Force exit without full cleanup
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
There was a problem hiding this comment.
cubic analysis
1 issue found across 14 files
Confidence score: 3/5
- Missing
'error'handler onprocess.stdininpackages/core/lib/v3/shutdown/supervisor.tscould cause an uncaught exception (e.g., EPIPE) if the parent dies abruptly, terminating the supervisor unexpectedly. - Given the medium-high severity and clear runtime impact, this carries some regression risk despite being localized.
- Pay close attention to
packages/core/lib/v3/shutdown/supervisor.ts- add stdin error handling to avoid uncaught exceptions.
Prompt for AI agents (all issues)
Check if these issues are valid — if so, understand the root cause of each and fix them.
<file name="packages/core/lib/v3/shutdown/supervisor.ts">
<violation number="1" location="packages/core/lib/v3/shutdown/supervisor.ts:157">
P1: Missing `'error'` handler on `process.stdin`. If the parent dies abruptly, stdin may emit an `'error'` event (e.g., `EPIPE`) before `'end'`/`'close'`. Without a handler, this throws an uncaught exception that kills the supervisor before it can run cleanup — defeating its purpose. Add an error handler that triggers the same lifeline-closed path.</violation>
</file>
Linked issue analysis
Linked issue: STG-1338: add keepAlive param
| Status | Acceptance criteria | Notes |
|---|---|---|
| ✅ | Add keepAlive option in V3 constructor params; optional boolean default false | Added keepAlive option and constructor handling |
| ✅ | Constructor keepAlive overrides browserbaseSessionCreateParams.keepAlive when both provided | Constructor uses opts.keepAlive ?? browserbase param |
| ✅ | Replace in-process global signal handlers with a detached supervisor process using a lifeline (stdin + IPC) | Removed global guards and added supervisor process approach |
| ✅ | When keepAlive=false, supervisor is spawned during init() and performs cleanup if parent dies unexpectedly | Supervisor started on init when keepAlive is false |
| ✅ | Supervisor kills Chrome PID with SIGTERM → SIGKILL escalation for LOCAL when keepAlive=false | safeKill implements SIGTERM then SIGKILL escalation |
| ✅ | Supervisor removes temp user-data directory for LOCAL when created and keepAlive=false | cleanupLocal removes userDataDir when createdTempProfile false/false |
| ✅ | When env=BROWSERBASE & using stagehand API, supervisor sends REQUEST_RELEASE to Browserbase API when keepAlive=false | cleanupBrowserbase issues REQUEST_RELEASE via SDK |
| ✅ | Supervisor includes PID polling to guard against process reuse | startPidPolling periodically checks pid and sets pidGone |
| ✅ | When keepAlive=true, no supervisor is spawned and the browser is left running | Supervisor only started when !keepAlive; shutdown helpers skip cleanup if keepAlive |
| ✅ | When disableAPI=true (direct WS), no supervisor spawned (browser will auto release when WS dropped) | Supervisor for Browserbase only started when !disableAPI |
| ✅ | Refactor close() browser teardown into shutdown/shutdownBrowser.ts helpers (shutdownBrowserSession, shutdownLocalBrowser) | Added shutdownBrowser.ts and used in close() path |
| ✅ | Pull Stagehand internal state cleanup into shutdown/shutdownStagehand.ts (shutdownStagehandResources, finalizeStagehandShutdown) | Added shutdownStagehand helpers and used in close() finalize |
| ✅ | .close() now skips apiClient.end() when keepAlive: true | apiClient.end passed into shutdownBrowserSession only when keepAlive false |
| ✅ | Update local launch to pass chrome launcher's handleSIGINT based on keepAlive (v3.ts & local.ts) to prevent chrome kill on Ctrl+C when keepAlive=true | handleSIGINT option added and passed as !keepAlive |
| ✅ | Unref the chrome child process after launch so Node can exit while chrome stays open when keepAlive=true | chrome.process?.unref() invoked when keepAlive true |
| ✅ | Supervisor not spawned when keepAlive=true (explicit behavior) | Supervisor armed only when config.keepAlive===false |
| ✅ | Supervisor not spawned when disableAPI=true (direct WS) for Browserbase sessions | v3 only starts STAGEHAND_API supervisor when !disableAPI |
| ✅ | Supervisor uses stdin lifeline and IPC handshake with ready acknowledgement | supervisor listens on stdin/disconnect and sends 'ready' on IPC |
| ✅ | Supervisor is spawned detached with stdio pipe + ipc and unrefs child and stdin | spawn uses detached:true stdio pipe+ipc and child.unref()/stdin.unref() used |
| ✅ | Include supervisor script in build outputs/package.json changes | build-js entry and files include supervisor artifacts |
| ✅ | Add internal types and errors for shutdown supervisor messages/configs | Added types and error classes for supervisor messages and errors |
| ✅ | Tests added for keep-alive behavior covering scenarios (unhandledRejection/unhandledException, SIGTERM/SIGINT, stagehand.close()) | Test child handles scenarios; spec invokes them |
| ✅ | Tests validate each scenario across configurations: local, browserbase direct WS, browserbase via stagehand API | buildKeepAliveCases covers local and Browserbase (direct/API) permutations |
Architecture diagram
sequenceDiagram
participant User
participant App as Stagehand (Main Process)
participant Super as Supervisor Process
participant Local as Local Chrome
participant BAPI as Browserbase API
Note over App: NEW: keepAlive param (default false)<br/>Overrides Browserbase config
User->>>App: init(keepAlive)
alt Environment: LOCAL
App->>Local: CHANGED: launchLocalChrome(handleSIGINT: !keepAlive)
opt NEW: keepAlive is true
App->>App: unref() Chrome child process
end
else Environment: BROWSERBASE
App->>BAPI: Create Session (propagate keepAlive)
end
opt NEW: If keepAlive is false
App->>Super: Spawn supervisor.js
App->>Super: NEW: send config (PID or SessionID)
Super->>Super: Start PID/lifeline polling
Super-->>App: NEW: "ready" handshake
end
Note over App,Super: Runtime Execution
alt Scenario: Graceful close()
User->>App: stagehand.close()
App->>Super: NEW: Stop supervisor (no cleanup)
alt keepAlive is false
App->>App: CHANGED: Perform resource cleanup
App->>Local: Kill process / delete profile
App->>BAPI: End session (REQUEST_RELEASE)
else keepAlive is true
Note over App,Local: NEW: Skip resource cleanup
end
App-->>User: Done
else Scenario: Process Crash / SIGINT / SIGTERM
Note over App: App process terminates
App-xSuper: NEW: Stdin lifeline closed
alt NEW: keepAlive is false
Super->>Super: Detect parent exit
alt kind: LOCAL
Super->>Local: safeKill(pid) + rmSync(userDataDir)
else kind: STAGEHAND_API
Super->>BAPI: update(sessionId, status: REQUEST_RELEASE)
end
Super->>Super: exit(0)
else keepAlive is true
Note over Local,BAPI: Browser / Session remains alive
end
end
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
|
@seanmcguire12 I have started the AI code review. It will take a few minutes to complete. |
There was a problem hiding this comment.
cubic analysis
No issues found across 14 files
Confidence score: 5/5
- Automated review surfaced no issues in the provided summaries.
- No files require special attention.
Linked issue analysis
Linked issue: STG-1338: add keepAlive param
| Status | Acceptance criteria | Notes |
|---|---|---|
| ✅ | Add optional boolean keepAlive parameter in the stagehand constructor params; keepAlive defaults to false. | Added keepAlive?: in V3Options and set in V3 constructor |
| ✅ | keepAlive on the constructor overrides browserbaseSessionCreateParams.keepAlive when both are provided. | Constructor value used to build effectiveSessionParams |
| ✅ | Replace old in-process global signal handlers with a detached supervisor process that watches a lifeline (stdin pipe + IPC channel) to the parent. | Removed process guards and added supervisor process files |
| ✅ | When keepAlive is false, the supervisor is spawned during init() and performs best-effort cleanup if the parent dies unexpectedly. | Supervisor started during init when keepAlive=false |
| ✅ | If env is "LOCAL" the supervisor kills the Chrome PID (with SIGTERM → SIGKILL escalation) and removes any temp user-data directory. | safeKill escalation and rmSync userDataDir implemented |
| ✅ | If env is "BROWSERBASE" & using the stagehand API, the supervisor sends REQUEST_RELEASE to the browserbase API. | Supervisor updates session status to REQUEST_RELEASE |
| ✅ | The supervisor includes PID polling to guard against process reuse (killing a recycled PID). | startPidPolling implemented to detect pid gone |
| ✅ | When keepAlive is set to true, no supervisor is spawned, & the browser is left running. | Checks prevent starting supervisor when keepAlive=true |
| ✅ | When disableAPI is set to true (direct WS to Browserbase), no supervisor is spawned since the browser will auto release when the WS is dropped. | Supervisor start guarded by !this.disableAPI for Browserbase |
| ✅ | Refactor close() into helpers: shutdown/shutdownBrowser.ts (shutdownBrowserSession, shutdownLocalBrowser) and shutdown/shutdownStagehand.ts (shutdownStagehandResources, finalizeStagehandShutdown). | New shutdown helper modules added and used in close() |
| ✅ | .close() now skips apiClient.end() when keepAlive: true. | shutdownBrowserSession returns early when keepAlive=true |
| ✅ | Local browser launch changes: pass chrome launcher’s handleSIGINT based on keepAlive. | launchLocalChrome now accepts handleSIGINT and v3 passes it |
| ✅ | Local launch unref() the chrome child process after launch so Node can exit while chrome stays open (when keepAlive true). | chrome.process?.unref() called when keepAlive |
| ✅ | Added tests in keep-alive.spec.ts validating behavior for unhandledRejection/unhandledException, SIGTERM/SIGINT, and stagehand.close(). | Spec plus helpers and child test script added |
| ✅ | Each scenario is validated across: local browser launched by stagehand, browserbase direct WS, browserbase via stagehand API. | Helpers construct cases for local, bb direct WS, and bb via API |
| ✅ | Build packaging updated to include the supervisor script so it can be spawned in production builds. | package.json build-js updated and dist supervisor files added |
Architecture diagram
sequenceDiagram
participant User as User Script
participant SH as Stagehand (V3 Instance)
participant SV as NEW: Shutdown Supervisor (Detached)
participant Browser as Browser (Local/Remote)
participant API as Browserbase API
Note over SH,SV: Initialization (init)
User->>>SH: init()
SH->>>Browser: Launch or Connect
alt NEW: keepAlive is FALSE (Default)
SH->>>SV: spawn() detached process
SH->>>SV: Send config (PID, SessionID, API Key)
SV->>SV: Start PID polling & watch stdin lifeline
SV-->>SH: "ready" handshake
else NEW: keepAlive is TRUE
Note over SH,Browser: Skip supervisor spawning
opt LOCAL Environment
SH->>>SH: NEW: unref() Chrome process
end
end
SH-->>User: initialized
Note over SH,API: Runtime & Termination
alt Scenario: Parent Process Crash / SIGINT / Uncaught Error
Note over SV,Browser: Supervisor detects stdin/IPC closure
alt kind == LOCAL
SV->>>Browser: NEW: SIGTERM -> SIGKILL PID
SV->>SV: NEW: Clean up temp userDataDir
else kind == STAGEHAND_API
SV->>>API: NEW: update(sessionId, { status: 'REQUEST_RELEASE' })
end
else Scenario: Explicit close()
User->>>SH: close()
SH->>>SV: NEW: stop() (no cleanup)
alt CHANGED: keepAlive is TRUE
Note over SH,Browser: Skip API end() / Skip process kill
SH->>>SH: Finalize internal state only
else keepAlive is FALSE
SH->>>Browser: Kill process / end session
SH->>>SH: Finalize internal state
end
SH-->>User: closed
end
Note over User,Browser: NEW: If keepAlive=true, Browser remains running after SH exit
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/[email protected] ### Minor Changes - [#1681](#1681) [`e3db9aa`](e3db9aa) Thanks [@tkattkat](https://github.com/tkattkat)! - Add cookie management APIs: `context.addCookies()`, `context.clearCookies()`, & `context.cookies()` - [#1672](#1672) [`b65756e`](b65756e) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - add boolean keepAlive parameter to allow for configuring whether the browser should be closed when stagehand.close() is called. - [#1708](#1708) [`176d420`](176d420) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - add context.setExtraHTTPHeaders() - [#1611](#1611) [`8a3c066`](8a3c066) Thanks [@monadoid](https://github.com/monadoid)! - Using `mode` enum instead of old `cua` boolean in openapi spec ### Patch Changes - [#1683](#1683) [`7584f3e`](7584f3e) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix: include shadow DOM in .count() & .nth() & support xpath predicates - [#1644](#1644) [`1e1c9c1`](1e1c9c1) Thanks [@monadoid](https://github.com/monadoid)! - Fix unhandled CDP detaches by returning the original sendCDP promise - [#1729](#1729) [`6bef890`](6bef890) Thanks [@shrey150](https://github.com/shrey150)! - fix: support Claude 4.6 (Opus and Sonnet) in CUA mode by using the correct `computer_20251124` tool version and `computer-use-2025-11-24` beta header - [#1647](#1647) [`ffd4b33`](ffd4b33) Thanks [@tkattkat](https://github.com/tkattkat)! - Fix [Agent] - Address bug causing issues with continuing a conversation from past messages in dom mode - [#1614](#1614) [`677bff5`](677bff5) Thanks [@miguelg719](https://github.com/miguelg719)! - Enforce <number>-<number> regex validation on act/observe for elementId - [#1580](#1580) [`65ff464`](65ff464) Thanks [@tkattkat](https://github.com/tkattkat)! - Add unified variables support across act and agent with a single VariableValue type - [#1666](#1666) [`101bcf2`](101bcf2) Thanks [@Kylejeong2](https://github.com/Kylejeong2)! - add support for codex models - [#1728](#1728) [`0a94301`](0a94301) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - handle potential race condition on `.close()` when using the Stagehand API - [#1664](#1664) [`b27c04d`](b27c04d) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fixes issue with context.addInitScript() where scripts were not being applied to out of process iframes (OOPIFs), and popup pages with same process iframes (SPIFs) - [#1632](#1632) [`afbd08b`](afbd08b) Thanks [@pirate](https://github.com/pirate)! - Remove automatic `.env` loading via `dotenv`. If your app relies on `.env` files, install `dotenv` and load it explicitly in your code: ```ts import dotenv from "dotenv"; dotenv.config({ path: ".env" }); ``` - [#1624](#1624) [`0e8d569`](0e8d569) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue where screenshot masks were not being applied to dialog elements - [#1596](#1596) [`ff0f979`](ff0f979) Thanks [@tkattkat](https://github.com/tkattkat)! - Update usage/metrics handling in agent - [#1631](#1631) [`2d89d2b`](2d89d2b) Thanks [@miguelg719](https://github.com/miguelg719)! - Add right and middle click support to act and observe - [#1697](#1697) [`aac9a19`](aac9a19) Thanks [@shrey150](https://github.com/shrey150)! - fix: support `<frame>` elements in XPath frame boundary detection so `act()` works on legacy `<frameset>` pages - [#1692](#1692) [`06de50f`](06de50f) Thanks [@shrey150](https://github.com/shrey150)! - fix: skip piercer injection for chrome-extension:// and other non-HTML targets - [#1613](#1613) [`aa4d981`](aa4d981) Thanks [@miguelg719](https://github.com/miguelg719)! - SupportedUnderstudyAction Enum validation for 'method' on act/observe inference - [#1652](#1652) [`18b1e3b`](18b1e3b) Thanks [@miguelg719](https://github.com/miguelg719)! - Add support for gemini 3 flash and pro in hybrid/cua agent - [#1706](#1706) [`957d82b`](957d82b) Thanks [@chrisreadsf](https://github.com/chrisreadsf)! - Add GLM to prompt-based JSON fallback for models without native structured output support - [#1633](#1633) [`22e371a`](22e371a) Thanks [@tkattkat](https://github.com/tkattkat)! - Add warning when incorrect models are used with agents hybrid mode - [#1673](#1673) [`d29b91f`](d29b91f) Thanks [@miguelg719](https://github.com/miguelg719)! - Add multi-region support for Stagehand API with region-specific endpoints - [#1695](#1695) [`7b4f817`](7b4f817) Thanks [@tkattkat](https://github.com/tkattkat)! - Fix: zod bug when pinning zod to v3 and using structured output in agent - [#1609](#1609) [`3f9ca4d`](3f9ca4d) Thanks [@miguelg719](https://github.com/miguelg719)! - Add SupportedUnderstudyActions to observe system prompt - [#1581](#1581) [`49ead1e`](49ead1e) Thanks [@sameelarif](https://github.com/sameelarif)! - **Server-side caching is now available.** When running `env: "BROWSERBASE"`, Stagehand automatically caches `act()`, `extract()`, and `observe()` results server-side — repeated calls with the same inputs return instantly without consuming LLM tokens. Caching is enabled by default and can be disabled via `serverCache: false` on the Stagehand instance or per individual call. Check out the [browserbase blog](https://www.browserbase.com/blog/stagehand-caching) for more details. - [#1642](#1642) [`3673369`](3673369) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue where scripts added via context.addInitScripts() were not being injected into new pages that were opened via popups (eg, clicking a link that opens a new page) and/or calling context.newPage(url) - [#1735](#1735) [`c465e87`](c465e87) Thanks [@monadoid](https://github.com/monadoid)! - Supports request header authentication with connectToMCPServer - [#1705](#1705) [`ae533e4`](ae533e4) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - include error cause in UnderstudyCommandException - [#1636](#1636) [`ea33052`](ea33052) Thanks [@miguelg719](https://github.com/miguelg719)! - Include executionModel on the AgentConfigSchema - [#1679](#1679) [`5764ede`](5764ede) Thanks [@shrey150](https://github.com/shrey150)! - fix issue where locator.count() was not working with xpaths that have attribute predicates - [#1646](#1646) [`f09b184`](f09b184) Thanks [@miguelg719](https://github.com/miguelg719)! - Add user-agent to CDP connections - [#1637](#1637) [`a7d29de`](a7d29de) Thanks [@miguelg719](https://github.com/miguelg719)! - Improve error and warning message for legacy model format - [#1685](#1685) [`d334399`](d334399) Thanks [@tkattkat](https://github.com/tkattkat)! - Bump ai sdk & google provider version - [#1662](#1662) [`44416da`](44416da) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue where locator.fill() was not working on elements that require direct value setting - [#1612](#1612) [`bdd8b4e`](bdd8b4e) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue where screenshot mask was only being applied to the first element that the locator resolved to. masks now apply to all matching elements. ## @browserbasehq/[email protected] ### Minor Changes - [#1611](#1611) [`8a3c066`](8a3c066) Thanks [@monadoid](https://github.com/monadoid)! - Using `mode` enum instead of old `cua` boolean in openapi spec ### Patch Changes - [#1604](#1604) [`4753078`](4753078) Thanks [@miguelg719](https://github.com/miguelg719)! - Enable bedrock - [#1636](#1636) [`ea33052`](ea33052) Thanks [@miguelg719](https://github.com/miguelg719)! - Include executionModel on the AgentConfigSchema - [#1602](#1602) [`22a0502`](22a0502) Thanks [@miguelg719](https://github.com/miguelg719)! - Include vertex as a supported provider - Updated dependencies \[[`7584f3e`](7584f3e), [`1e1c9c1`](1e1c9c1), [`6bef890`](6bef890), [`ffd4b33`](ffd4b33), [`677bff5`](677bff5), [`65ff464`](65ff464), [`101bcf2`](101bcf2), [`0a94301`](0a94301), [`b27c04d`](b27c04d), [`afbd08b`](afbd08b), [`e3db9aa`](e3db9aa), [`0e8d569`](0e8d569), [`ff0f979`](ff0f979), [`2d89d2b`](2d89d2b), [`aac9a19`](aac9a19), [`06de50f`](06de50f), [`aa4d981`](aa4d981), [`18b1e3b`](18b1e3b), [`957d82b`](957d82b), [`b65756e`](b65756e), [`22e371a`](22e371a), [`d29b91f`](d29b91f), [`7b4f817`](7b4f817), [`176d420`](176d420), [`3f9ca4d`](3f9ca4d), [`8a3c066`](8a3c066), [`49ead1e`](49ead1e), [`3673369`](3673369), [`c465e87`](c465e87), [`ae533e4`](ae533e4), [`ea33052`](ea33052), [`5764ede`](5764ede), [`f09b184`](f09b184), [`a7d29de`](a7d29de), [`d334399`](d334399), [`44416da`](44416da), [`bdd8b4e`](bdd8b4e)]: - @browserbasehq/[email protected] ## @browserbasehq/[email protected] ### Patch Changes - Updated dependencies \[[`7584f3e`](7584f3e), [`1e1c9c1`](1e1c9c1), [`6bef890`](6bef890), [`ffd4b33`](ffd4b33), [`677bff5`](677bff5), [`65ff464`](65ff464), [`101bcf2`](101bcf2), [`0a94301`](0a94301), [`b27c04d`](b27c04d), [`afbd08b`](afbd08b), [`e3db9aa`](e3db9aa), [`0e8d569`](0e8d569), [`ff0f979`](ff0f979), [`2d89d2b`](2d89d2b), [`aac9a19`](aac9a19), [`06de50f`](06de50f), [`aa4d981`](aa4d981), [`18b1e3b`](18b1e3b), [`957d82b`](957d82b), [`b65756e`](b65756e), [`22e371a`](22e371a), [`d29b91f`](d29b91f), [`7b4f817`](7b4f817), [`176d420`](176d420), [`3f9ca4d`](3f9ca4d), [`8a3c066`](8a3c066), [`49ead1e`](49ead1e), [`3673369`](3673369), [`c465e87`](c465e87), [`ae533e4`](ae533e4), [`ea33052`](ea33052), [`5764ede`](5764ede), [`f09b184`](f09b184), [`a7d29de`](a7d29de), [`d334399`](d334399), [`44416da`](44416da), [`bdd8b4e`](bdd8b4e)]: - @browserbasehq/[email protected] Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
# why
- to give users the freedom to decide whether the browser should be kept
open or "alive" when their stagehand instance is killed
- to follow best practices by avoiding usage of global signal handlers
inside library code
# what changed
new `keepAlive` option:
- added an optional, boolean `keepAlive` parameter in the stagehand
constructor params. `keepAlive` defaults to `false`
- `keepAlive` on the constructor overrides
`browserbaseSessionCreateParams.keepAlive` when both are provided
out-of-process shutdown supervisor (`packages/core/lib/v3/shutdown/`):
- replaced the old in-process global signal handlers
(process.once("SIGINT"), etc.) with a detached supervisor process that
watches a lifeline (stdin pipe + IPC channel) to the parent
- when `keepAlive` is set to `false`, the supervisor is spawned during
`init()` and performs best-effort cleanup if the parent dies
unexpectedly:
- if `env` is `"LOCAL"` the supervisor kills the Chrome PID (with
SIGTERM → SIGKILL escalation) and removes any temp user-data directory
- if `env` is `"BROWSERBASE"` & using the stagehand API, the supervisor
sends `REQUEST_RELEASE` to the browserbase API
- the supervisor also includes PID polling to guard against process
reuse (killing a recycled PID
- when `keepAlive` is set to `true`, no supervisor is spawned, & the
browser is left running
- when `disableAPI` is set to `true` (direct WS to Browserbase), no
supervisor is spawned since the browser will auto release when the WS is
dropped
refactored `close()` into helpers:
- pulled browser teardown logic into `shutdown/shutdownBrowser.ts`
(`shutdownBrowserSession`, `shutdownLocalBrowser`)
- pulled stagehand internal state cleanup into
`shutdown/shutdownStagehand.ts` (`shutdownStagehandResources`,
`finalizeStagehandShutdown`)
-`.close()` now skips `apiClient.end()` when `keepAlive: true`
local browser launch changes:
- updated local launch to pass chrome launcher’s `handleSIGINT` based on
`keepAlive` in `packages/core/lib/v3/v3.ts` and
`packages/core/lib/v3/launch/local.ts`. this prevents chrome from
getting killed on Ctrl+C when `keepAlive: true`
- updated local launch so that we `unref()` the chrome child process
after launch so Node can exit while chrome stays open
(`packages/core/lib/v3/v3.ts`)
### behaviour notes:
- setting `keepAlive: true` will keep the browser alive in the following
scenarios:
- stagehand instance gets killed because of an uncaught error (eg,
`unhandledRejection`, `unhandledException`)
- stagehand instance gets killed because of a `SIGTERM` or `SIGINT`
- stagehand instance gets killed with an explicit call to
`stagehand.close()`
# test plan
- added tests in `keep-alive.spec.ts` that validate expected behaviour
across the following scenarios:
- `unhandledRejection`/`unhandledException`,
- `SIGTERM`/`SIGINT`,
- `stagehand.close()`
- each scenario is validated in each of the following browser
configurations:
- using a local browser launched by stagehand
- using a browserbase browser, connected directly over the WS
- using a browserbase browser + the stagehand API
<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds a keepAlive option to Stagehand V3 so you control whether the
browser/session stays up after stagehand.close(), signals, or uncaught
errors. Replaces global process handlers with a per‑instance crash‑only
supervisor with a ready handshake and PID polling to avoid race
conditions (STG‑1338).
- **New Features**
- keepAlive?: boolean (default false) on the V3 constructor; overrides
browserbaseSessionCreateParams.keepAlive when set.
- Local: set handleSIGINT based on keepAlive and unref Chrome when true;
when false, a detached supervisor watches a stdin/IPC lifeline and on
parent crash/error SIGTERM→SIGKILLs Chrome and removes the temp profile
(with PID polling). A shared cleanup helper is used by both close() and
the supervisor for consistent local teardown.
- Browserbase: propagate keepAlive to session creation; when keepAlive
is true, close() skips apiClient.end() so the session stays RUNNING;
when false (and API enabled), the supervisor requests REQUEST_RELEASE on
crash/error; when disableAPI is true (direct WS), no supervisor is
spawned and the session ends when the WS drops.
- **Migration**
- Set keepAlive: true in the V3 constructor to keep the browser/session
open on errors, signals, or stagehand.close(); this overrides any value
in browserbaseSessionCreateParams.
- When keepAlive is true, close resources yourself when done (Local:
send Browser.close; Browserbase: request release/end the session).
<sup>Written for commit 3887d8f.
Summary will update on new commits. <a
href="https://cubic.dev/pr/browserbase/stagehand/pull/1672">Review in
cubic</a></sup>
<!-- End of auto-generated description by cubic. -->
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/[email protected] ### Minor Changes - [browserbase#1681](browserbase#1681) [`e3db9aa`](browserbase@e3db9aa) Thanks [@tkattkat](https://github.com/tkattkat)! - Add cookie management APIs: `context.addCookies()`, `context.clearCookies()`, & `context.cookies()` - [browserbase#1672](browserbase#1672) [`b65756e`](browserbase@b65756e) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - add boolean keepAlive parameter to allow for configuring whether the browser should be closed when stagehand.close() is called. - [browserbase#1708](browserbase#1708) [`176d420`](browserbase@176d420) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - add context.setExtraHTTPHeaders() - [browserbase#1611](browserbase#1611) [`8a3c066`](browserbase@8a3c066) Thanks [@monadoid](https://github.com/monadoid)! - Using `mode` enum instead of old `cua` boolean in openapi spec ### Patch Changes - [browserbase#1683](browserbase#1683) [`7584f3e`](browserbase@7584f3e) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix: include shadow DOM in .count() & .nth() & support xpath predicates - [browserbase#1644](browserbase#1644) [`1e1c9c1`](browserbase@1e1c9c1) Thanks [@monadoid](https://github.com/monadoid)! - Fix unhandled CDP detaches by returning the original sendCDP promise - [browserbase#1729](browserbase#1729) [`6bef890`](browserbase@6bef890) Thanks [@shrey150](https://github.com/shrey150)! - fix: support Claude 4.6 (Opus and Sonnet) in CUA mode by using the correct `computer_20251124` tool version and `computer-use-2025-11-24` beta header - [browserbase#1647](browserbase#1647) [`ffd4b33`](browserbase@ffd4b33) Thanks [@tkattkat](https://github.com/tkattkat)! - Fix [Agent] - Address bug causing issues with continuing a conversation from past messages in dom mode - [browserbase#1614](browserbase#1614) [`677bff5`](browserbase@677bff5) Thanks [@miguelg719](https://github.com/miguelg719)! - Enforce <number>-<number> regex validation on act/observe for elementId - [browserbase#1580](browserbase#1580) [`65ff464`](browserbase@65ff464) Thanks [@tkattkat](https://github.com/tkattkat)! - Add unified variables support across act and agent with a single VariableValue type - [browserbase#1666](browserbase#1666) [`101bcf2`](browserbase@101bcf2) Thanks [@Kylejeong2](https://github.com/Kylejeong2)! - add support for codex models - [browserbase#1728](browserbase#1728) [`0a94301`](browserbase@0a94301) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - handle potential race condition on `.close()` when using the Stagehand API - [browserbase#1664](browserbase#1664) [`b27c04d`](browserbase@b27c04d) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fixes issue with context.addInitScript() where scripts were not being applied to out of process iframes (OOPIFs), and popup pages with same process iframes (SPIFs) - [browserbase#1632](browserbase#1632) [`afbd08b`](browserbase@afbd08b) Thanks [@pirate](https://github.com/pirate)! - Remove automatic `.env` loading via `dotenv`. If your app relies on `.env` files, install `dotenv` and load it explicitly in your code: ```ts import dotenv from "dotenv"; dotenv.config({ path: ".env" }); ``` - [browserbase#1624](browserbase#1624) [`0e8d569`](browserbase@0e8d569) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue where screenshot masks were not being applied to dialog elements - [browserbase#1596](browserbase#1596) [`ff0f979`](browserbase@ff0f979) Thanks [@tkattkat](https://github.com/tkattkat)! - Update usage/metrics handling in agent - [browserbase#1631](browserbase#1631) [`2d89d2b`](browserbase@2d89d2b) Thanks [@miguelg719](https://github.com/miguelg719)! - Add right and middle click support to act and observe - [browserbase#1697](browserbase#1697) [`aac9a19`](browserbase@aac9a19) Thanks [@shrey150](https://github.com/shrey150)! - fix: support `<frame>` elements in XPath frame boundary detection so `act()` works on legacy `<frameset>` pages - [browserbase#1692](browserbase#1692) [`06de50f`](browserbase@06de50f) Thanks [@shrey150](https://github.com/shrey150)! - fix: skip piercer injection for chrome-extension:// and other non-HTML targets - [browserbase#1613](browserbase#1613) [`aa4d981`](browserbase@aa4d981) Thanks [@miguelg719](https://github.com/miguelg719)! - SupportedUnderstudyAction Enum validation for 'method' on act/observe inference - [browserbase#1652](browserbase#1652) [`18b1e3b`](browserbase@18b1e3b) Thanks [@miguelg719](https://github.com/miguelg719)! - Add support for gemini 3 flash and pro in hybrid/cua agent - [browserbase#1706](browserbase#1706) [`957d82b`](browserbase@957d82b) Thanks [@chrisreadsf](https://github.com/chrisreadsf)! - Add GLM to prompt-based JSON fallback for models without native structured output support - [browserbase#1633](browserbase#1633) [`22e371a`](browserbase@22e371a) Thanks [@tkattkat](https://github.com/tkattkat)! - Add warning when incorrect models are used with agents hybrid mode - [browserbase#1673](browserbase#1673) [`d29b91f`](browserbase@d29b91f) Thanks [@miguelg719](https://github.com/miguelg719)! - Add multi-region support for Stagehand API with region-specific endpoints - [browserbase#1695](browserbase#1695) [`7b4f817`](browserbase@7b4f817) Thanks [@tkattkat](https://github.com/tkattkat)! - Fix: zod bug when pinning zod to v3 and using structured output in agent - [browserbase#1609](browserbase#1609) [`3f9ca4d`](browserbase@3f9ca4d) Thanks [@miguelg719](https://github.com/miguelg719)! - Add SupportedUnderstudyActions to observe system prompt - [browserbase#1581](browserbase#1581) [`49ead1e`](browserbase@49ead1e) Thanks [@sameelarif](https://github.com/sameelarif)! - **Server-side caching is now available.** When running `env: "BROWSERBASE"`, Stagehand automatically caches `act()`, `extract()`, and `observe()` results server-side — repeated calls with the same inputs return instantly without consuming LLM tokens. Caching is enabled by default and can be disabled via `serverCache: false` on the Stagehand instance or per individual call. Check out the [browserbase blog](https://www.browserbase.com/blog/stagehand-caching) for more details. - [browserbase#1642](browserbase#1642) [`3673369`](browserbase@3673369) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue where scripts added via context.addInitScripts() were not being injected into new pages that were opened via popups (eg, clicking a link that opens a new page) and/or calling context.newPage(url) - [browserbase#1735](browserbase#1735) [`c465e87`](browserbase@c465e87) Thanks [@monadoid](https://github.com/monadoid)! - Supports request header authentication with connectToMCPServer - [browserbase#1705](browserbase#1705) [`ae533e4`](browserbase@ae533e4) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - include error cause in UnderstudyCommandException - [browserbase#1636](browserbase#1636) [`ea33052`](browserbase@ea33052) Thanks [@miguelg719](https://github.com/miguelg719)! - Include executionModel on the AgentConfigSchema - [browserbase#1679](browserbase#1679) [`5764ede`](browserbase@5764ede) Thanks [@shrey150](https://github.com/shrey150)! - fix issue where locator.count() was not working with xpaths that have attribute predicates - [browserbase#1646](browserbase#1646) [`f09b184`](browserbase@f09b184) Thanks [@miguelg719](https://github.com/miguelg719)! - Add user-agent to CDP connections - [browserbase#1637](browserbase#1637) [`a7d29de`](browserbase@a7d29de) Thanks [@miguelg719](https://github.com/miguelg719)! - Improve error and warning message for legacy model format - [browserbase#1685](browserbase#1685) [`d334399`](browserbase@d334399) Thanks [@tkattkat](https://github.com/tkattkat)! - Bump ai sdk & google provider version - [browserbase#1662](browserbase#1662) [`44416da`](browserbase@44416da) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue where locator.fill() was not working on elements that require direct value setting - [browserbase#1612](browserbase#1612) [`bdd8b4e`](browserbase@bdd8b4e) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue where screenshot mask was only being applied to the first element that the locator resolved to. masks now apply to all matching elements. ## @browserbasehq/[email protected] ### Minor Changes - [browserbase#1611](browserbase#1611) [`8a3c066`](browserbase@8a3c066) Thanks [@monadoid](https://github.com/monadoid)! - Using `mode` enum instead of old `cua` boolean in openapi spec ### Patch Changes - [browserbase#1604](browserbase#1604) [`4753078`](browserbase@4753078) Thanks [@miguelg719](https://github.com/miguelg719)! - Enable bedrock - [browserbase#1636](browserbase#1636) [`ea33052`](browserbase@ea33052) Thanks [@miguelg719](https://github.com/miguelg719)! - Include executionModel on the AgentConfigSchema - [browserbase#1602](browserbase#1602) [`22a0502`](browserbase@22a0502) Thanks [@miguelg719](https://github.com/miguelg719)! - Include vertex as a supported provider - Updated dependencies \[[`7584f3e`](browserbase@7584f3e), [`1e1c9c1`](browserbase@1e1c9c1), [`6bef890`](browserbase@6bef890), [`ffd4b33`](browserbase@ffd4b33), [`677bff5`](browserbase@677bff5), [`65ff464`](browserbase@65ff464), [`101bcf2`](browserbase@101bcf2), [`0a94301`](browserbase@0a94301), [`b27c04d`](browserbase@b27c04d), [`afbd08b`](browserbase@afbd08b), [`e3db9aa`](browserbase@e3db9aa), [`0e8d569`](browserbase@0e8d569), [`ff0f979`](browserbase@ff0f979), [`2d89d2b`](browserbase@2d89d2b), [`aac9a19`](browserbase@aac9a19), [`06de50f`](browserbase@06de50f), [`aa4d981`](browserbase@aa4d981), [`18b1e3b`](browserbase@18b1e3b), [`957d82b`](browserbase@957d82b), [`b65756e`](browserbase@b65756e), [`22e371a`](browserbase@22e371a), [`d29b91f`](browserbase@d29b91f), [`7b4f817`](browserbase@7b4f817), [`176d420`](browserbase@176d420), [`3f9ca4d`](browserbase@3f9ca4d), [`8a3c066`](browserbase@8a3c066), [`49ead1e`](browserbase@49ead1e), [`3673369`](browserbase@3673369), [`c465e87`](browserbase@c465e87), [`ae533e4`](browserbase@ae533e4), [`ea33052`](browserbase@ea33052), [`5764ede`](browserbase@5764ede), [`f09b184`](browserbase@f09b184), [`a7d29de`](browserbase@a7d29de), [`d334399`](browserbase@d334399), [`44416da`](browserbase@44416da), [`bdd8b4e`](browserbase@bdd8b4e)]: - @browserbasehq/[email protected] ## @browserbasehq/[email protected] ### Patch Changes - Updated dependencies \[[`7584f3e`](browserbase@7584f3e), [`1e1c9c1`](browserbase@1e1c9c1), [`6bef890`](browserbase@6bef890), [`ffd4b33`](browserbase@ffd4b33), [`677bff5`](browserbase@677bff5), [`65ff464`](browserbase@65ff464), [`101bcf2`](browserbase@101bcf2), [`0a94301`](browserbase@0a94301), [`b27c04d`](browserbase@b27c04d), [`afbd08b`](browserbase@afbd08b), [`e3db9aa`](browserbase@e3db9aa), [`0e8d569`](browserbase@0e8d569), [`ff0f979`](browserbase@ff0f979), [`2d89d2b`](browserbase@2d89d2b), [`aac9a19`](browserbase@aac9a19), [`06de50f`](browserbase@06de50f), [`aa4d981`](browserbase@aa4d981), [`18b1e3b`](browserbase@18b1e3b), [`957d82b`](browserbase@957d82b), [`b65756e`](browserbase@b65756e), [`22e371a`](browserbase@22e371a), [`d29b91f`](browserbase@d29b91f), [`7b4f817`](browserbase@7b4f817), [`176d420`](browserbase@176d420), [`3f9ca4d`](browserbase@3f9ca4d), [`8a3c066`](browserbase@8a3c066), [`49ead1e`](browserbase@49ead1e), [`3673369`](browserbase@3673369), [`c465e87`](browserbase@c465e87), [`ae533e4`](browserbase@ae533e4), [`ea33052`](browserbase@ea33052), [`5764ede`](browserbase@5764ede), [`f09b184`](browserbase@f09b184), [`a7d29de`](browserbase@a7d29de), [`d334399`](browserbase@d334399), [`44416da`](browserbase@44416da), [`bdd8b4e`](browserbase@bdd8b4e)]: - @browserbasehq/[email protected]
why
what changed
new
keepAliveoption:keepAliveparameter in the stagehand constructor params.keepAlivedefaults tofalsekeepAliveon the constructor overridesbrowserbaseSessionCreateParams.keepAlivewhen both are provided out-of-process shutdown supervisor (packages/core/lib/v3/shutdown/):keepAliveis set tofalse, the supervisor is spawned duringinit()and performs best-effort cleanup if the parent dies unexpectedly:envis"LOCAL"the supervisor kills the Chrome PID (with SIGTERM → SIGKILL escalation) and removes any temp user-data directoryenvis"BROWSERBASE"& using the stagehand API, the supervisor sendsREQUEST_RELEASEto the browserbase APIkeepAliveis set totrue, no supervisor is spawned, & the browser is left runningdisableAPIis set totrue(direct WS to Browserbase), no supervisor is spawned since the browser will auto release when the WS is droppedrefactored
close()into helpers:shutdown/shutdownBrowser.ts(shutdownBrowserSession,shutdownLocalBrowser)shutdown/shutdownStagehand.ts(shutdownStagehandResources,finalizeStagehandShutdown)-
.close()now skipsapiClient.end()whenkeepAlive: truelocal browser launch changes:
handleSIGINTbased onkeepAliveinpackages/core/lib/v3/v3.tsandpackages/core/lib/v3/launch/local.ts. this prevents chrome from getting killed on Ctrl+C whenkeepAlive: trueunref()the chrome child process after launch so Node can exit while chrome stays open (packages/core/lib/v3/v3.ts)behaviour notes:
keepAlive: truewill keep the browser alive in the following scenarios:unhandledRejection,unhandledException)SIGTERMorSIGINTstagehand.close()test plan
keep-alive.spec.tsthat validate expected behaviour across the following scenarios:unhandledRejection/unhandledException,SIGTERM/SIGINT,stagehand.close()Summary by cubic
Adds a keepAlive option to Stagehand V3 so you control whether the browser/session stays up after stagehand.close(), signals, or uncaught errors. Replaces global process handlers with a per‑instance crash‑only supervisor with a ready handshake and PID polling to avoid race conditions (STG‑1338).
New Features
Migration
Written for commit 3887d8f. Summary will update on new commits. Review in cubic