@@ -122,7 +122,25 @@ def __init__(
122122 self .wait_for_captcha_solves = self .config .wait_for_captcha_solves
123123 self .system_prompt = self .config .system_prompt
124124 self .verbose = self .config .verbose
125- self .env = self .config .env .upper () if self .config .env else "BROWSERBASE"
125+
126+ # Smart environment detection
127+ if self .config .env :
128+ self .env = self .config .env .upper ()
129+ else :
130+ # Auto-detect environment based on available configuration
131+ has_browserbase_config = bool (self .browserbase_api_key and self .browserbase_project_id )
132+ has_local_config = bool (self .config .local_browser_launch_options )
133+
134+ if has_local_config and not has_browserbase_config :
135+ # Local browser options specified but no Browserbase config
136+ self .env = "LOCAL"
137+ elif not has_browserbase_config and not has_local_config :
138+ # No configuration specified, default to LOCAL for easier local development
139+ self .env = "LOCAL"
140+ else :
141+ # Default to BROWSERBASE if Browserbase config is available
142+ self .env = "BROWSERBASE"
143+
126144 self .local_browser_launch_options = (
127145 self .config .local_browser_launch_options or {}
128146 )
@@ -230,7 +248,10 @@ def cleanup_handler(sig, frame):
230248 return
231249
232250 self .__class__ ._cleanup_called = True
233- print (f"\n [{ signal .Signals (sig ).name } ] received. Ending Browserbase session..." )
251+ if self .env == "BROWSERBASE" :
252+ print (f"\n [{ signal .Signals (sig ).name } ] received. Ending Browserbase session..." )
253+ else :
254+ print (f"\n [{ signal .Signals (sig ).name } ] received. Cleaning up Stagehand resources..." )
234255
235256 try :
236257 # Try to get the current event loop
@@ -269,9 +290,15 @@ async def _async_cleanup(self):
269290 """Async cleanup method called from signal handler."""
270291 try :
271292 await self .close ()
272- print (f"Session { self .session_id } ended successfully" )
293+ if self .env == "BROWSERBASE" and self .session_id :
294+ print (f"Session { self .session_id } ended successfully" )
295+ else :
296+ print ("Stagehand resources cleaned up successfully" )
273297 except Exception as e :
274- print (f"Error ending Browserbase session: { str (e )} " )
298+ if self .env == "BROWSERBASE" :
299+ print (f"Error ending Browserbase session: { str (e )} " )
300+ else :
301+ print (f"Error cleaning up Stagehand resources: { str (e )} " )
275302 finally :
276303 # Force exit after cleanup completes (or fails)
277304 # Use os._exit to avoid any further Python cleanup that might hang
0 commit comments