@@ -122,7 +122,25 @@ def __init__(
122
122
self .wait_for_captcha_solves = self .config .wait_for_captcha_solves
123
123
self .system_prompt = self .config .system_prompt
124
124
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
+
126
144
self .local_browser_launch_options = (
127
145
self .config .local_browser_launch_options or {}
128
146
)
@@ -230,7 +248,10 @@ def cleanup_handler(sig, frame):
230
248
return
231
249
232
250
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..." )
234
255
235
256
try :
236
257
# Try to get the current event loop
@@ -269,9 +290,15 @@ async def _async_cleanup(self):
269
290
"""Async cleanup method called from signal handler."""
270
291
try :
271
292
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" )
273
297
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 )} " )
275
302
finally :
276
303
# Force exit after cleanup completes (or fails)
277
304
# Use os._exit to avoid any further Python cleanup that might hang
0 commit comments