Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

Merge pull request #1028 from carlosplanchon/direct_html_manipulation

Nick Sweeting3bbb0bece7e5
diff --cc browser_use/agent/service.py
index 6ccb37acc,5aa8e943d..4575dc199
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@@ -86,63 -78,10 +86,65 @@@ def log_response(response: AgentOutput
logger.info(f'๐Ÿ› ๏ธ Action {i + 1}/{len(response.action)}: {action.model_dump_json(exclude_unset=True)}')
+def sigint_handler(loop: asyncio.AbstractEventLoop, agent=None):
+ """SIGINT (Ctrl+C) handler.
+
+ First Ctrl+C: Cancel current step and pause the agent.
+ Second Ctrl+C: Exit immediately.
+ """
+ global _exiting
+
+ if _exiting:
+ # Already exiting, force exit immediately
+ os._exit(0)
+
+ if getattr(loop, 'ctrl_c_pressed', False):
+ # If we're in the waiting for input state, let the pause method handle it
+ if getattr(loop, 'waiting_for_input', False):
+ return
+
+ # Second Ctrl+C - exit immediately
+ _exiting = True
+ logger.info('\n\n๐Ÿ›‘๐Ÿ›‘ Second Ctrl+C detected. Exiting immediately...\n\n')
+
+ # Force exit - more reliable than sys.exit()
+ os._exit(0)
+
+ # Mark that Ctrl+C was pressed
+ loop.ctrl_c_pressed = True
+
+ # Cancel current tasks
+ current_task = asyncio.current_task(loop)
+ for task in asyncio.all_tasks(loop):
+ if task != current_task and not task.done():
+ task_name = task.get_name() if hasattr(task, 'get_name') else str(task)
+ if 'step' in task_name or 'multi_act' in task_name or 'get_next_action' in task_name:
+ task.cancel()
+
+ # If we can get the agent reference, pause it
+ if agent and hasattr(agent, 'pause'):
+ agent.pause()
+
+ logger.info('\n\n๐Ÿ›‘ Ctrl+C detected. Current step cancelled and agent paused.')
+ logger.info('Press Enter to resume or Ctrl+C again to exit completely.\n\n')
+
+
+def sigterm_handler(loop: asyncio.AbstractEventLoop):
+ """SIGTERM handler.
+
+ Always exits the program completely.
+ """
+ global _exiting
+ if not _exiting:
+ _exiting = True
+ logger.info('\n\n๐Ÿ›‘ SIGTERM received. Exiting immediately...\n\n')
+ os._exit(0)
+
+
Context = TypeVar('Context')
+ AgentHookFunc = Callable[['Agent'], None]
+
class Agent(Generic[Context]):
@time_execution_sync('--init (agent)')
@@@ -714,22 -650,13 +716,27 @@@
# @observe(name='agent.run', ignore_output=True)
@time_execution_async('--run (agent)')
- async def run(self, max_steps: int = 100) -> AgentHistoryList:
+ async def run(
+ self,
+ max_steps: int = 100,
+ on_step_start: AgentHookFunc | None = None,
+ on_step_end: AgentHookFunc | None = None
+ ) -> AgentHistoryList:
"""Execute the task with maximum number of steps"""
+
+ loop = asyncio.get_event_loop()
+
+ # Initialize control attributes
+ setattr(loop, 'ctrl_c_pressed', False)
+ setattr(loop, 'waiting_for_input', False)
+
+ # Set up signal handlers with reference to self (the agent)
+ loop.add_signal_handler(signal.SIGINT, lambda: sigint_handler(loop, self))
+ loop.add_signal_handler(signal.SIGTERM, lambda: sigterm_handler(loop))
+
+ # Start non-blocking LLM connection verification
+ assert await self.llm._verified_api_keys, 'Failed to verify LLM API keys'
+
try:
self._log_agent_run()