Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Nuke it all
mertunsallbcdc522ade04
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex 468a7d87b..9f9dc67a3 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -17,6 +17,7 @@ from browser_use.agent.message_manager.views import MessageMetadatafrom browser_use.agent.prompts import AgentMessagePromptfrom browser_use.agent.views import ActionResult, AgentOutput, AgentStepInfo, MessageManagerStatefrom browser_use.browser.views import BrowserStateSummary+from browser_use.filesystem.file_system import FileSystemfrom browser_use.utils import time_execution_synclogger = logging.getLogger(__name__)@@ -199,6 +200,7 @@ class MessageManager:self,task: str,system_message: SystemMessage,+ file_system: FileSystem,settings: MessageManagerSettings = MessageManagerSettings(),state: MessageManagerState = MessageManagerState(),):@@ -206,7 +208,9 @@ class MessageManager:self.settings = settingsself.state = stateself.system_prompt = system_message-+ self.file_system = file_system+ self.agent_history_description = '# Agent History\n'+ self.read_state_description = ''# Only initialize messages if state is emptyif len(self.state.history.messages) == 0:self._init_messages()@@ -219,58 +223,116 @@ class MessageManager:context_message = HumanMessage(content='Context for the task' + self.settings.message_context)self._add_message_with_tokens(context_message, message_type='init')- task_message = HumanMessage(- content=f'Your ultimate task is: """{self.task}""". If you achieved your ultimate task, stop everything and use the done action in the next step to complete the task. If not, continue as usual.'- )- self._add_message_with_tokens(task_message, message_type='init')-if self.settings.sensitive_data:info = f'Here are placeholders for sensitive data: {list(self.settings.sensitive_data.keys())}'info += '\nTo use them, write <secret>the placeholder name</secret>'info_message = HumanMessage(content=info)self._add_message_with_tokens(info_message, message_type='init')- placeholder_message = HumanMessage(content='Example output:')+ placeholder_message = HumanMessage(content='Example tool call 1:')self._add_message_with_tokens(placeholder_message, message_type='init')- example_tool_call = AIMessage(+ example_tool_call_1 = AIMessage(content='',tool_calls=[{'name': 'AgentOutput','args': {'current_state': {- 'evaluation_previous_goal': """- Success - I successfully clicked on the 'Apple' link from the Google Search results page,- which directed me to the 'Apple' company homepage. This is a good start toward finding- the best place to buy a new iPhone as the Apple website often list iPhones for sale.- """.strip(),- 'memory': """- I searched for 'iPhone retailers' on Google. From the Google Search results page,- I used the 'click_element_by_index' tool to click on element at index [45] labeled 'Best Buy' but calling- the tool did not direct me to a new page. I then used the 'click_element_by_index' tool to click- on element at index [82] labeled 'Apple' which redirected me to the 'Apple' company homepage.- Currently at step 3/15.- """.strip(),- 'next_goal': """- Looking at reported structure of the current page, I can see the item '[127]<h3 iPhone/>'- in the content. I think this button will lead to more information and potentially prices- for iPhones. I'll click on the link at index [127] using the 'click_element_by_index'- tool and hope to see prices on the next page.- """.strip(),+ 'thinking': """+**Understanding the Current State:**+I have successfully navigated to https://github.com/explore and can see the page has loaded with a list of featured repositories and trending projects. The page contains interactive elements and I can identify specific repositories like bytedance/UI-TARS-desktop and ray-project/kuberay that appear to be featured or trending. The user's request seems to involve exploring GitHub repositories, likely to collect information about them such as descriptions, stars, or other metadata.++**Evaluating the Previous Action:**+My navigation to the GitHub explore page was successful. The page loaded correctly and I can see the expected content - a curated list of repositories that GitHub is featuring. This gives me a good starting point to begin the repository exploration task. The DOM shows interactive elements that I can work with, and the page structure is as expected for GitHub's explore section.++**Tracking and Planning with todo.md:**+Since this appears to be a multi-step task involving visiting multiple repositories and collecting their information, I need to create a structured plan in todo.md. This will help me track which repositories I've visited, what information I've collected, and ensure I don't miss any important repositories. The todo.md should include all visible repositories and a systematic approach to processing them.++**Writing Intermediate Results:**+I should prepare to use results.md to store the collected repository information as I gather it. Each repository's details should be appended in a consistent format for easy review.++**Preparing what goes into my memory:**+I need to capture the key repositories I've identified so far and establish that I'm at the planning stage of this multi-step task.++**Planning my next action:**+My next action should be to create a comprehensive todo.md file that outlines the entire task. This will include identifying all visible repositories, creating checkboxes for each one to visit, and establishing a clear workflow. I need to be thorough in identifying repositories since the user likely wants comprehensive coverage of what's available on the explore page.+""",+ 'evaluation_previous_goal': 'Navigated to GitHub explore page. Verdict: Success',+ 'memory': 'Found initial repositories such as bytedance/UI-TARS-desktop and ray-project/kuberay.',+ 'next_goal': 'Create todo.md checklist to track progress.',},- 'action': [{'click_element_by_index': {'index': 127}}],+ 'action': [+ {+ 'write_file': {+ 'path': 'todo.md',+ 'content': """+# Interesting Github Repositories in Explore Section++## Tasks+- [ ] Initialize a tracking file for GitHub repositories called github.md+- [ ] Visit each Github repository and find their description+- [ ] Visit bytedance/UI-TARS-desktop+- [ ] Visit ray-project/kuberay+- [ ] Check for additional Github repositories by scrolling down+- [ ] Compile all results in the requested format+- [ ] Validate that I have not missed anything in the page+- [ ] Report final results to user+""".strip('\n'),+ }+ }+ ],},'id': str(self.state.tool_id),'type': 'tool_call',},],)- self._add_message_with_tokens(example_tool_call, message_type='init')- self.add_tool_message(content='Browser started', message_type='init')+ self._add_message_with_tokens(example_tool_call_1, message_type='init')+ self.add_tool_message(content='Data written to todo.md successfully.', message_type='init')- placeholder_message = HumanMessage(content='[Your task history memory starts here]')- self._add_message_with_tokens(placeholder_message)+ placeholder_message = HumanMessage(content='Example tool call 2:')+ self._add_message_with_tokens(placeholder_message, message_type='init')++ example_tool_call_2 = AIMessage(+ content='',+ tool_calls=[+ {+ 'name': 'AgentOutput',+ 'args': {+ 'current_state': {+ 'thinking': """+**Understanding the Current State:**+I am currently on Apple's main homepage, having successfully clicked on an 'Apple' link in the previous step. The page has loaded and I can see the typical Apple website layout with navigation elements. I can see an interactive element at index [4] that is labeled 'iPhone', which indicates this is a navigation link to Apple's iPhone product section.++**Evaluating the Previous Action:**+The click on the 'Apple' link was successful and brought me to Apple's homepage as expected. The page loaded properly and I can see the navigation structure including the iPhone link. This confirms that the previous navigation action worked correctly and I'm now in the right place to continue with the iPhone-related task.++**Tracking and Planning with todo.md:**+Based on the context, this seems to be part of a larger task involving Apple products. I should be prepared to update my todo.md file if there are multiple iPhone models or other Apple products to investigate. The current goal is to access the iPhone section to see what product information is available.++**Writing Intermediate Results:**+Once I reach the iPhone page, I'll need to extract information about different iPhone models, their specifications, prices, or other details. I should accumulate all findings in results.md in a structured format as I collect the information.++**Preparing what goes into my memory:**+I need to capture that I'm in the process of navigating to the iPhone section and preparing to collect product information.++**Planning my next action:**+My next action is to click on the iPhone link at index [4] to navigate to Apple's iPhone product page. This will give me access to the iPhone lineup and allow me to gather the requested information.+""",+ 'evaluation_previous_goal': 'Clicked Apple link and reached the homepage. Verdict: Success',+ 'memory': 'On Apple homepage with iPhone link at index [4].',+ 'next_goal': 'Click iPhone link.',+ },+ 'action': [{'click_element_by_index': {'index': 4}}],+ },+ 'id': str(self.state.tool_id),+ 'type': 'tool_call',+ },+ ],+ )+ self._add_message_with_tokens(example_tool_call_2, message_type='init')+ self.add_tool_message(content='Clicked on index [4].', message_type='init')if self.settings.available_file_paths:filepaths_msg = HumanMessage(content=f'Here are file paths you can use: {self.settings.available_file_paths}')@@ -282,16 +344,55 @@ class MessageManager:self._add_message_with_tokens(msg)self.task = new_task+ def _update_agent_history_description(+ self,+ model_output: AgentOutput | None = None,+ result: list[ActionResult] | None = None,+ step_info: AgentStepInfo | None = None,+ ) -> None:+ """Update the agent history description"""++ if None in [model_output, result, step_info]:+ return++ self.read_state_description = '# Read State\n'++ step_number = step_info.step_number++ action_results = ''+ for idx, action_result in enumerate(result):+ if action_result.update_read_state:+ self.read_state_description += action_result.extracted_content + '\n'+ if action_result.memory:+ action_results += f'Action {idx + 1} Result: {action_result.memory}\n'+ elif action_result.error:+ action_results += f'Action {idx + 1} Error: {action_result.error}\n'+ else:+ raise ValueError(f'Action {idx + 1} has no memory or error')++ self.agent_history_description += f"""## Step {step_number}+Evaluation: {model_output.current_state.evaluation_previous_goal}+Memory: {model_output.current_state.memory}+Next goal: {model_output.current_state.next_goal}+{action_results}+"""+ if self.read_state_description == '# Read State\n':+ self.read_state_description = ''+@time_execution_sync('--add_state_message')def add_state_message(self,browser_state_summary: BrowserStateSummary,+ model_output: AgentOutput | None = None,result: list[ActionResult] | None = None,step_info: AgentStepInfo | None = None,use_vision=True,+ page_filtered_actions: str | None = None,) -> None:"""Add browser state as human message"""+ self._update_agent_history_description(model_output, result, step_info)+ """# if keep in memory, add to directly to history and add state without resultif result:for r in result:@@ -308,14 +409,19 @@ class MessageManager:msg = HumanMessage(content='Action error: ' + last_line)self._add_message_with_tokens(msg)result = None # if result in history, we dont want to add it again+ """# otherwise add state message and result to next message (which will not stay in memory)assert browser_state_summarystate_message = AgentMessagePrompt(browser_state_summary=browser_state_summary,- result=result,+ file_system=self.file_system,+ agent_history_description=self.agent_history_description,+ read_state_description=self.read_state_description,+ task=self.task,include_attributes=self.settings.include_attributes,step_info=step_info,+ page_filtered_actions=page_filtered_actions,).get_user_message(use_vision)self._add_message_with_tokens(state_message)diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.pyindex a30a3cee0..928ca05da 100644--- a/browser_use/agent/prompts.py+++ b/browser_use/agent/prompts.py@@ -5,8 +5,9 @@ from typing import TYPE_CHECKING, Optionalfrom langchain_core.messages import HumanMessage, SystemMessageif TYPE_CHECKING:- from browser_use.agent.views import ActionResult, AgentStepInfo+ from browser_use.agent.views import AgentStepInfofrom browser_use.browser.views import BrowserStateSummary+ from browser_use.filesystem.file_system import FileSystemclass SystemPrompt:@@ -63,74 +64,96 @@ class AgentMessagePrompt:def __init__(self,browser_state_summary: 'BrowserStateSummary',- result: list['ActionResult'] | None = None,+ file_system: 'FileSystem',+ agent_history_description: str | None = None,+ read_state_description: str | None = None,+ task: str | None = None,include_attributes: list[str] | None = None,step_info: Optional['AgentStepInfo'] = None,+ page_filtered_actions: str | None = None,):- self.state: 'BrowserStateSummary' = browser_state_summary- self.result = result+ self.browser_state: 'BrowserStateSummary' = browser_state_summary+ self.file_system: 'FileSystem' | None = file_system+ self.agent_history_description: str | None = agent_history_description+ self.read_state_description: str | None = read_state_description+ self.task: str | None = taskself.include_attributes = include_attributes or []self.step_info = step_info- assert self.state+ self.page_filtered_actions: str | None = page_filtered_actions+ assert self.browser_state- def get_user_message(self, use_vision: bool = True) -> HumanMessage:- elements_text = self.state.element_tree.clickable_elements_to_string(include_attributes=self.include_attributes)+ def _get_browser_state_description(self) -> str:+ elements_text = self.browser_state.element_tree.clickable_elements_to_string(include_attributes=self.include_attributes)- has_content_above = (self.state.pixels_above or 0) > 0- has_content_below = (self.state.pixels_below or 0) > 0+ has_content_above = (self.browser_state.pixels_above or 0) > 0+ has_content_below = (self.browser_state.pixels_below or 0) > 0if elements_text != '':if has_content_above:- elements_text = (- f'... {self.state.pixels_above} pixels above - scroll or extract content to see more ...\n{elements_text}'- )+ elements_text = f'... {self.browser_state.pixels_above} pixels above - scroll or extract content to see more ...\n{elements_text}'else:elements_text = f'[Start of page]\n{elements_text}'if has_content_below:- elements_text = (- f'{elements_text}\n... {self.state.pixels_below} pixels below - scroll or extract content to see more ...'- )+ elements_text = f'{elements_text}\n... {self.browser_state.pixels_below} pixels below - scroll or extract content to see more ...'else:elements_text = f'{elements_text}\n[End of page]'else:elements_text = 'empty page'+ tabs_text = ''+ for tab in self.browser_state.tabs:+ tabs_text += f'Tab {tab.page_id}: URL={tab.url}, Title={tab.title[:30]}\n'++ browser_state = f"""# Browser State+Current URL: {self.browser_state.url}+Available tabs:+{tabs_text}+Interactive elements from top layer of the current page inside the viewport:+{elements_text}+"""+ return browser_state++ def _get_agent_state_description(self) -> str:if self.step_info:- step_info_description = f'Current step: {self.step_info.step_number + 1}/{self.step_info.max_steps}'+ step_info_description = f'Current step: {self.step_info.step_number + 1}/{self.step_info.max_steps}\n'else:step_info_description = ''time_str = datetime.now().strftime('%Y-%m-%d %H:%M')step_info_description += f'Current date and time: {time_str}'- state_description = f"""-[Task history memory ends]-[Current state starts here]-The following is one-time information - if you need to remember it write it to memory:-Current url: {self.state.url}-Available tabs:-{self.state.tabs}-Interactive elements from top layer of the current page inside the viewport:-{elements_text}+ todo_contents = self.file_system.get_todo_contents()+ if not len(todo_contents):+ todo_contents = '[Current todo.md is empty, fill it with your plan when applicable]'++ agent_state = f"""# Agent State\n+## USER REQUEST:+{self.task}\n+## File System:+{self.file_system.describe()}\n+## Contents of todo.md:+{todo_contents}\n+## Step Info:{step_info_description}"""+ return agent_state- if self.result:- for i, result in enumerate(self.result):- if result.extracted_content:- state_description += f'\nAction result {i + 1}/{len(self.result)}: {result.extracted_content}'- if result.error:- # only use last line of error- error = result.error.split('\n')[-1]- state_description += f'\nAction error {i + 1}/{len(self.result)}: ...{error}'-- if self.state.screenshot and use_vision is True:+ def get_user_message(self, use_vision: bool = True) -> HumanMessage:+ state_description = self.agent_history_description + '\n'+ state_description += self._get_agent_state_description() + '\n'+ state_description += self._get_browser_state_description() + '\n'+ state_description += self.read_state_description + '\n'+ if self.page_filtered_actions:+ state_description += 'For this page, these additional actions are available:\n'+ state_description += self.page_filtered_actions + '\n'++ if self.browser_state.screenshot and use_vision is True:# Format message for vision modelreturn HumanMessage(content=[{'type': 'text', 'text': state_description},{'type': 'image_url',- 'image_url': {'url': f'data:image/png;base64,{self.state.screenshot}'}, # , 'detail': 'low'+ 'image_url': {'url': f'data:image/png;base64,{self.browser_state.screenshot}'}, # , 'detail': 'low'},])diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 155b4c946..e407a12de 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -7,7 +7,9 @@ import osimport reimport shutilimport sys+import tempfileimport time+import uuidfrom collections.abc import Awaitable, Callablefrom pathlib import Pathfrom threading import Thread@@ -62,6 +64,7 @@ from browser_use.dom.history_tree_processor.service import (HistoryTreeProcessor,)from browser_use.exceptions import LLMException+from browser_use.filesystem.file_system import FileSystemfrom browser_use.telemetry.service import ProductTelemetryfrom browser_use.telemetry.views import (AgentTelemetryEvent,@@ -83,6 +86,7 @@ def log_response(response: AgentOutput, registry=None) -> None:else:emoji = '❓'+ logger.info(f'💡 Thinking:\n{response.current_state.thinking}')logger.info(f'{emoji} Eval: {response.current_state.evaluation_previous_goal}')logger.info(f'🧠 Memory: {response.current_state.memory}')logger.info(f'🎯 Next goal: {response.current_state.next_goal}')@@ -163,6 +167,7 @@ class Agent(Generic[Context]):enable_memory: bool = True,memory_config: MemoryConfig | None = None,source: str | None = None,+ file_system_path: str | None = None,):if page_extraction_llm is None:page_extraction_llm = llm@@ -205,6 +210,9 @@ class Agent(Generic[Context]):# Initialize stateself.state = injected_agent_state or AgentState()+ # Initialize file system+ self._set_file_system(file_system_path)+# Action setupself._setup_action_models()self._set_browser_use_version_and_source(source)@@ -243,6 +251,7 @@ class Agent(Generic[Context]):f'{f" planner_model={self.planner_model_name}" if self.planner_model_name else ""}'f'{" +reasoning" if self.settings.is_planner_reasoning else ""}'f'{" +vision" if self.settings.use_vision_for_planner else ""} '+ f'{" +file_system" if self.file_system else ""}')# Initialize available actions for system prompt (only non-filtered actions)@@ -261,6 +270,7 @@ class Agent(Generic[Context]):override_system_message=override_system_message,extend_system_message=extend_system_message,).get_system_message(),+ file_system=self.file_system,settings=MessageManagerSettings(max_input_tokens=self.settings.max_input_tokens,include_attributes=self.settings.include_attributes,@@ -402,6 +412,44 @@ class Agent(Generic[Context]):def browser_profile(self) -> BrowserProfile:return self.browser_session.browser_profile+ def _set_file_system(self, file_system_path: str | None = None) -> None:+ # Initialize file system+ if file_system_path:+ self.file_system = FileSystem(file_system_path)+ self.file_system_path = file_system_path+ else:+ # create a temporary file system+ base_tmp = tempfile.gettempdir() # e.g., /tmp on Unix+ self.file_system_path = os.path.join(base_tmp, str(uuid.uuid4()))+ self.file_system = FileSystem(self.file_system_path)++ logger.info(f'💾 File system path: {self.file_system_path}')++ # if file system is set, add actions to the controller+ @self.controller.registry.action('Write content to file_name in file system')+ async def write_file(file_name: str, content: str):+ result = await self.file_system.write_file(file_name, content)+ logger.info(f'💾 {result}')+ return ActionResult(extracted_content=result, include_in_memory=True, memory=result)++ @self.controller.registry.action('Append content to file_name in file system')+ async def append_file(file_name: str, content: str):+ result = await self.file_system.append_file(file_name, content)+ logger.info(f'💾 {result}')+ return ActionResult(extracted_content=result, include_in_memory=True, memory=result)++ @self.controller.registry.action('Read file_name from file system')+ async def read_file(file_name: str):+ result = await self.file_system.read_file(file_name)+ max_len = 50+ if len(result) > max_len:+ display_result = result[:max_len] + '\n...'+ else:+ display_result = result+ logger.info(f'💾 {display_result}')+ memory = result.split('\n')[-1]+ return ActionResult(extracted_content=result, include_in_memory=True, memory=memory, update_read_state=True)+def _set_message_context(self) -> str | None:if self.tool_calling_method == 'raw':# For raw tool calling, only include actions with no filters initially@@ -800,11 +848,6 @@ class Agent(Generic[Context]):# Get page-specific filtered actionspage_filtered_actions = self.controller.registry.get_prompt_description(current_page)- # If there are page-specific actions, add them as a special message for this step only- if page_filtered_actions:- page_action_message = f'For this page, these additional actions are available:\n{page_filtered_actions}'- self._message_manager._add_message_with_tokens(HumanMessage(content=page_action_message))-# If using raw tool calling method, we need to update the message context with new actionsif self.tool_calling_method == 'raw':# For raw tool calling, get all non-filtered actions plus the page-filtered ones@@ -824,9 +867,11 @@ class Agent(Generic[Context]):self._message_manager.add_state_message(browser_state_summary=browser_state_summary,+ model_output=self.state.last_model_output,result=self.state.last_result,step_info=step_info,use_vision=self.settings.use_vision,+ page_filtered_actions=page_filtered_actions if page_filtered_actions else None,)# Run planner at specified intervals if planner is configured@@ -893,7 +938,7 @@ class Agent(Generic[Context]):# check again if Ctrl+C was pressed before we commit the output to historyawait self._raise_if_stopped_or_paused()- self._message_manager.add_model_output(model_output)+ # self._message_manager.add_model_output(model_output)except asyncio.CancelledError:# Task was cancelled due to Ctrl+Cself._message_manager._remove_last_state_message()@@ -910,6 +955,7 @@ class Agent(Generic[Context]):result: list[ActionResult] = await self.multi_act(model_output.action)self.state.last_result = result+ self.state.last_model_output = model_outputif len(result) > 0 and result[-1].is_done:logger.info(f'📄 Result: {result[-1].extracted_content}')@@ -1495,6 +1541,7 @@ class Agent(Generic[Context]):result = await self.controller.act(action=action,browser_session=self.browser_session,+ file_system=self.file_system,page_extraction_llm=self.settings.page_extraction_llm,sensitive_data=self.sensitive_data,available_file_paths=self.settings.available_file_paths,diff --git a/browser_use/agent/system_prompt.md b/browser_use/agent/system_prompt.mdindex 94069a4f5..3767ee0c0 100644--- a/browser_use/agent/system_prompt.md+++ b/browser_use/agent/system_prompt.md@@ -1,83 +1,163 @@-You are an AI agent designed to automate browser tasks. Your goal is to accomplish the ultimate task following the rules.--# Input Format--Task-Previous steps-Current URL-Open Tabs-Interactive Elements-[index]<type>text</type>-+You are a tool-using AI agent designed operating in an iterative loop to automate browser tasks. Your ultimate goal is accomplishing the task provided in USER REQUEST.++<intro>+You excel at following tasks:+1. Navigating complex websites and extracting precise information+2. Automating form submissions and interactive web actions+3. Gathering and saving information+4. Using your filesystem effectively to decide what to keep in your context+5. Operate effectively in an agent loop+6. Efficiently performing diverse web tasks+</intro>++<input>+At every step, you will be given a state that+1. Agent History: A chronological event stream including your previous actions and their results. This may be truncated or partially omitted.+2. Agent State: Includes the ultimate goal provided by the user, current progress, and relevant contextual memory.+3. Browser State: Contains current URL, open tabs, interactive elements indexed for actions, visible page content, and (sometimes) any visual context provided by screenshots or page snapshots.+4. Read State: If your previous action involved reading a file or extracting content (e.g., from a webpage), the full result will be included here. This data is **only shown in the current step** and will not appear in future Agent History. You are responsible for saving or interpreting the information appropriately during this step.+</input>++<agent_history>+Agent history will be given as a list of step information as follows:++Step step_number:+Evaluation of Previous Step: Agent generated assessment of last action+Memory: Agent generated memory of this step+Actions: Agent generated actions+Action Results: System generated result of those actions+</agent_history>++<agent_state>+Agent State will be given as follows:++USER REQUEST: The high-level task specified by the user. This is your ultimate objective and always remains visible.++File System: A summary of your current files in the format:+- file_name — num_lines lines++Current Step: The current step number in the agent loop.++Timestamp: The current date and time at this step.+</agent_state>++<browser_state>+1. Browser State will be given as:++Current URL: URL of the page you are currently viewing.+Open Tabs: Open tabs in the browser you can navigate to.+Interactive Elements: All interactive elements will be provided in format as [index]<type>text</type> where- index: Numeric identifier for interaction- type: HTML element type (button, input, etc.)- text: Element description- Example:- [33]<div>User form</div>- \t*[35]*<button aria-label='Submit form'>Submit</button>+Examples:+[33]<div>User form</div>+\t*[35]*<button aria-label='Submit form'>Submit</button>++Note that:- Only elements with numeric indexes in [] are interactive- (stacked) indentation (with \t) is important and means that the element is a (html) child of the element above (with a lower index)- Elements with \* are new elements that were added after the previous step (if url has not changed)--# Response Rules--1. RESPONSE FORMAT: You must ALWAYS respond with valid JSON in this exact format:- {{"current_state": {{"evaluation_previous_goal": "Success|Failed|Unknown - Analyze the current elements and the image to check if the previous goals/actions are successful like intended by the task. Mention if something unexpected happened. Shortly state why/why not",- "memory": "Description of what has been done and what you need to remember. Be very specific. Count here ALWAYS how many times you have done something and how many remain. E.g. 0 out of 10 websites analyzed. Continue with abc and xyz",- "next_goal": "What needs to be done with the next immediate action"}},- "action":[{{"one_action_name": {{// action-specific parameter}}}}, // ... more actions in sequence]}}--2. ACTIONS: You can specify multiple actions in the list to be executed in sequence. But always specify only one action name per item. Use maximum {max_actions} actions per sequence.-Common action sequences:--- Form filling: [{{"input_text": {{"index": 1, "text": "username"}}}}, {{"input_text": {{"index": 2, "text": "password"}}}}, {{"click_element": {{"index": 3}}}}]-- Navigation and extraction: [{{"go_to_url": {{"url": "https://example.com"}}}}, {{"extract_content": {{"goal": "extract the names"}}}}]-- Actions are executed in the given order-- If the page changes after an action, the sequence is interrupted and you get the new state.-- Only provide the action sequence until an action which changes the page state significantly.-- Try to be efficient, e.g. fill forms at once, or chain actions where nothing changes on the page-- only use multiple actions if it makes sense.--3. ELEMENT INTERACTION:--- Only use indexes of the interactive elements--4. NAVIGATION & ERROR HANDLING:--- If no suitable elements exist, use other functions to complete the task-- If stuck, try alternative approaches - like going back to a previous page, new search, new tab etc.-- Handle popups/cookies by accepting or closing them-- Use scroll to find elements you are looking for-- If you want to research something, open a new tab instead of using the current tab-- If captcha pops up, try to solve it - else try a different approach-- If the page is not fully loaded, use wait action--5. TASK COMPLETION:--- Use the done action as the last action as soon as the ultimate task is complete-- Dont use "done" before you are done with everything the user asked you, except you reach the last step of max_steps.-- If you reach your last step, use the done action even if the task is not fully finished. Provide all the information you have gathered so far. If the ultimate task is completely finished set success to true. If not everything the user asked for is completed set success in done to false!-- If you have to do something repeatedly for example the task says for "each", or "for all", or "x times", count always inside "memory" how many times you have done it and how many remain. Don't stop until you have completed like the task asked you. Only call done after the last step.-- Don't hallucinate actions-- Make sure you include everything you found out for the ultimate task in the done text parameter. Do not just say you are done, but include the requested information of the task.--6. VISUAL CONTEXT:--- When an image is provided, use it to understand the page layout-- Bounding boxes with labels on their top right corner correspond to element indexes--7. Form filling:-+</browser_state>++<browser_vision>+When a screenshot is provided, use it to understand the page layout. Bounding box labels correspond to element indexes.+</browser_vision>++<read_state>+1. This section will be displayed only if your previous action was one of: "read_file", "extract_content", or any similar action that returns transient data to be consumed.+2. You will see this information **only once** in your state and it will not appear again in your Agent History. You are responsible for either saving it to a relevant file or fully processing it in the current step. If you need the data later, it must be explicitly persisted now.+</read_state>++<browser_rules>+Strictly follow these rules while using the browser and navigating the web:+- Only interact with elements that have a numeric [index] assigned.+- Do not fabricate or guess indexes—use only those explicitly provided.+- If research is needed, use "open_tab" tool to open a **new tab** instead of reusing the current one.+- Switch between open tabs using `switch_tab`.+- By default, only elements in the visible viewport are listed. Use scrolling tools if you suspect relevant content is offscreen. Scroll ONLY if there are more pixels below or above the page.+- If a captcha appears, attempt solving it if possible. If not, use fallback strategies (e.g., alternative site, backtrack).+- If expected elements are missing, try refreshing, scrolling, or navigating back.+- Use multiple actions where no page transition is expected (e.g., fill multiple fields then click submit).+- If the page is not fully loaded, use the wait action.+- If your task is to find information, you can call "extract_content" on specific pages to gather information. You will see the results **only once** in your state.- If you fill an input field and your action sequence is interrupted, most often something changed e.g. suggestions popped up under the field.--8. Long tasks:--- Keep track of the status and subresults in the memory.-- You are provided with procedural memory summaries that condense previous task history (every N steps). Use these summaries to maintain context about completed actions, current progress, and next steps. The summaries appear in chronological order and contain key information about navigation history, findings, errors encountered, and current state. Refer to these summaries to avoid repeating actions and to ensure consistent progress toward the task goal.--9. Extraction:--- If your task is to find information - call extract_content on the specific pages to get and store the information.--Your responses must be always JSON with the specified format.+</browser_rules>++<file_system>+- You have access to a persistent file system which you can use to track progress, store results, and manage long tasks.+- Your file system is initialized with two files:+ 1. `todo.md`: Use this to keep a checklist or plan for known subtasks. Update it to mark completed items and track what remains. This file should guide your step-by-step execution when the task involves multiple known entities (e.g., a list of links or items to visit). The contents of this file will be also visible in your state.+ 2. `results.md`: Use this to accumulate extracted or generated results for the user. Append each new finding clearly and avoid duplication. This file serves as your output log.+- You can read, write, and append to these files using file actions.+- Always use the file system as the source of truth. Do not rely on memory alone for tracking task state.+</file_system>++<task_completion_rules>+You must call the `done` action in one of two cases:+1. When you have fully completed the USER REQUEST.+2. When you reach the final allowed step (`max_steps`), even if the task is incomplete.++In the `done` action:+- Set `success` to `true` only if the full USER REQUEST has been completed with no missing components.+- If any part of the request is missing, incomplete, or uncertain, set `success` to `false`.+- In all cases, include all relevant findings and outputs in the `text` field of the `done` action.+</task_completion_rules>++<action_rules>+- You can specify multiple actions in the list to be executed sequentially (one after another). But always specify only one action name per item. Use maximum {max_actions} actions per sequence.+- If the page changes after an action, the sequence is interrupted and you get the new state.+- ONLY use multiple actions when actions should not change the page state significantly.+- For example, when filling forms you can use multiple actions like: [{{"input_text": {{"index": 1, "text": "name"}}}}, {{"input_text": {{"index": 2, "text": "surname"}}}}, {{"click_element_by_index": {{"index": 3}}}}]+</action_rules>++<reasoning_rules>+You must reason explicitly and systematically at every step in your `thinking` block. Your reasoning should reflect deep understanding of the task, the current state, and what needs to be done next.++Follow this structured reasoning pattern:++1. **Understand the Current State**+- Carefully read all available context: agent history, browser state, read state, file contents, and the user request.+- Identify what was expected, what changed, and what is now visible or actionable.++2. **Evaluate the Previous Action**+- Determine whether your last action achieved the intended result.+- Use the DOM structure, screenshots, and newly visible elements to assess success.+- Clearly state what worked, what failed, or what is unknown—and why.+- If something failed, retry, adapt, or choose an alternative approach.++3. **Track and Plan with `todo.md`**+- For complex or multi-step tasks, create or update `todo.md` as soon as you reach the relevant URL.+- Mark completed items using the file tool.+- Refer to `todo.md` to guide and track progress throughout the task.++4. **Write Intermediate Results to Files**+- Append extracted results to `results.md` as they are found.++5. **Prepare Your Tool Call**+- Do all your reasoning in `thinking`.+- `evaluation_previous_goal`, `memory`, and `next_goal` fields are how you leave traceable reasoning for the next step.+- Each should contain 1–3 clear and informative sentences.+- Rason carefully about the most relevant next action.+- Ensure your output follows the required JSON format exactly.++6. **Before Calling `done`**+- Perform a full reasoning pass: Have you completed every part of the user request?+- Verify completeness—e.g., if the user asked to collect all products, confirm all were found by checking there are no further pages.+- In your final memory and result, summarize what was achieved. If incomplete, explain what is missing and why.+</reasoning_rules>++<output>+You must ALWAYS respond with a valid JSON in this exact format:++{{+ "current_state": {{+ "thinking": "A long and structured <think>-style reasoning block that applies the reasoning patterns provided above."+ "evaluation_previous_goal": "One-sentence analysis of your last action. Clearly state if it succeeded, failed, or is uncertain — and briefly explain why.",+ "memory": "1-3 sentences brief memory of planning, thinking, and status in this step. You should put here everything that will help you track progress in future steps.",+ "next_goal": "State the next immediate goal and the action to achieve it, in one clear sentence."+ }}+ "action":[{{"one_action_name": {{// action-specific parameter}}}}, // ... more actions in sequence]+}}+</output>diff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 434cb2ad4..a44cd3c57 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -84,6 +84,7 @@ class AgentState(BaseModel):last_result: list[ActionResult] | None = Nonehistory: AgentHistoryList = Field(default_factory=lambda: AgentHistoryList(history=[]))last_plan: str | None = None+ last_model_output: AgentOutput | None = Nonepaused: bool = Falsestopped: bool = False@@ -111,6 +112,8 @@ class ActionResult(BaseModel):extracted_content: str | None = Noneerror: str | None = Noneinclude_in_memory: bool = False # whether to include in past messages as context or not+ memory: str | None = None # Memory of this action+ update_read_state: bool = False # Whether the extracted content should be used to update the read_stateclass StepMetadata(BaseModel):@@ -130,6 +133,7 @@ class StepMetadata(BaseModel):class AgentBrain(BaseModel):"""Current internal working memory of the agent, we ask the LLM to decide new values for these on each output"""+ thinking: str | None = Noneevaluation_previous_goal: strmemory: strnext_goal: strdiff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.pyindex 86c9c509b..66c255de4 100644--- a/browser_use/controller/registry/service.py+++ b/browser_use/controller/registry/service.py@@ -18,6 +18,7 @@ from browser_use.controller.registry.views import (RegisteredAction,SpecialActionParameters,)+from browser_use.filesystem.file_system import FileSystemfrom browser_use.telemetry.service import ProductTelemetryfrom browser_use.telemetry.views import (ControllerRegisteredFunctionsTelemetryEvent,@@ -53,6 +54,7 @@ class Registry(Generic[Context]):'page_extraction_llm': BaseChatModel,'available_file_paths': list,'has_sensitive_data': bool,+ 'file_system': FileSystem,}def _normalize_action_function_signature(@@ -195,6 +197,8 @@ class Registry(Generic[Context]):raise ValueError(f'Action {func.__name__} requires browser_session but none provided.')elif param.name == 'page_extraction_llm':raise ValueError(f'Action {func.__name__} requires page_extraction_llm but none provided.')+ elif param.name == 'file_system':+ raise ValueError(f'Action {func.__name__} requires file_system but none provided.')else:raise ValueError(f"{func.__name__}() missing required special parameter '{param.name}'")call_args.append(value)@@ -206,6 +210,8 @@ class Registry(Generic[Context]):raise ValueError(f'Action {func.__name__} requires browser_session but none provided.')elif param.name == 'page_extraction_llm':raise ValueError(f'Action {func.__name__} requires page_extraction_llm but none provided.')+ elif param.name == 'file_system':+ raise ValueError(f'Action {func.__name__} requires file_system but none provided.')else:raise ValueError(f"{func.__name__}() missing required special parameter '{param.name}'")else:@@ -299,6 +305,7 @@ class Registry(Generic[Context]):params: dict,browser_session: BrowserSession | None = None,page_extraction_llm: BaseChatModel | None = None,+ file_system: FileSystem | None = None,sensitive_data: dict[str, str | dict[str, str]] | None = None,available_file_paths: list[str] | None = None,#@@ -336,6 +343,7 @@ class Registry(Generic[Context]):'page_extraction_llm': page_extraction_llm,'available_file_paths': available_file_paths,'has_sensitive_data': action_name == 'input_text' and bool(sensitive_data),+ 'file_system': file_system,}# Handle async page parameter if neededdiff --git a/browser_use/controller/registry/views.py b/browser_use/controller/registry/views.pyindex 9e7c98294..63507c705 100644--- a/browser_use/controller/registry/views.py+++ b/browser_use/controller/registry/views.py@@ -6,6 +6,7 @@ from playwright.async_api import Pagefrom pydantic import BaseModel, ConfigDictfrom browser_use.browser import BrowserSession+from browser_use.filesystem.file_system import FileSystemif TYPE_CHECKING:from browser_use.agent.service import Context@@ -170,6 +171,7 @@ class SpecialActionParameters(BaseModel):# extra injected config if the action asks for these arg namespage_extraction_llm: BaseChatModel | None = None+ file_system: FileSystem | None = Noneavailable_file_paths: list[str] | None = Nonehas_sensitive_data: bool = Falsediff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex 7cea06b22..228de7bd8 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -30,6 +30,7 @@ from browser_use.controller.views import (SendKeysAction,SwitchTabAction,)+from browser_use.filesystem.file_system import FileSystemfrom browser_use.utils import time_execution_synclogger = logging.getLogger(__name__)@@ -67,7 +68,12 @@ class Controller(Generic[Context]):if isinstance(value, enum.Enum):output_dict[key] = value.value- return ActionResult(is_done=True, success=params.success, extracted_content=json.dumps(output_dict))+ return ActionResult(+ is_done=True,+ success=params.success,+ extracted_content=json.dumps(output_dict),+ memory=f'Task completed. Success Status: {params.success}',+ )else:@self.registry.action(@@ -75,7 +81,12 @@ class Controller(Generic[Context]):param_model=DoneAction,)async def done(params: DoneAction):- return ActionResult(is_done=True, success=params.success, extracted_content=params.text)+ len_text = len(params.text)+ len_max_memory = 100+ memory = f'Task completed: {params.success} - {params.text[:len_max_memory]}'+ if len_text > len_max_memory:+ memory += f' - {len_text - len_max_memory} more characters'+ return ActionResult(is_done=True, success=params.success, extracted_content=params.text, memory=memory)# Basic Navigation Actions@self.registry.action(@@ -94,7 +105,7 @@ class Controller(Generic[Context]):msg = f'🔍 Searched for "{params.query}" in Google'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f"Searched Google for '{params.query}'")@self.registry.action('Navigate to URL in the current tab', param_model=GoToUrlAction)async def go_to_url(params: GoToUrlAction, browser_session: BrowserSession):@@ -106,14 +117,14 @@ class Controller(Generic[Context]):page = await browser_session.create_new_tab(params.url)msg = f'🔗 Navigated to {params.url}'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Navigated to {params.url}')@self.registry.action('Go back', param_model=NoParamsAction)async def go_back(params: NoParamsAction, browser_session: BrowserSession):await browser_session.go_back()msg = '🔙 Navigated back'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory='Navigated back')# wait for x seconds@self.registry.action('Wait for x seconds default 3')@@ -121,7 +132,7 @@ class Controller(Generic[Context]):msg = f'🕒 Waiting for {seconds} seconds'logger.info(msg)await asyncio.sleep(seconds)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Waited for {seconds} seconds')# Element Interaction Actions@self.registry.action('Click element by index', param_model=ClickElementAction)@@ -138,7 +149,7 @@ class Controller(Generic[Context]):if await browser_session.find_file_upload_element_by_index(params.index) is not None:msg = f'Index {params.index} - has an element which opens file upload dialog. To upload files please use a specific function to upload files 'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Clicked element {params.index}')msg = None@@ -156,7 +167,7 @@ class Controller(Generic[Context]):msg += f' - {new_tab_msg}'logger.info(new_tab_msg)await browser_session.switch_to_tab(-1)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Clicked element {params.index}')except Exception as e:logger.warning(f'Element not clickable with index {params.index} - most likely the page changed')return ActionResult(error=str(e))@@ -177,7 +188,9 @@ class Controller(Generic[Context]):msg = f'⌨️ Input sensitive data into index {params.index}'logger.info(msg)logger.debug(f'Element xpath: {element_node.xpath}')- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(+ extracted_content=msg, include_in_memory=True, memory=f"Input '{params.text}' into element {params.index}."+ )# Save PDF@self.registry.action('Save the current page as a PDF file')@@ -190,7 +203,7 @@ class Controller(Generic[Context]):await page.pdf(path=sanitized_filename, format='A4', print_background=False)msg = f'Saving page with URL {page.url} as PDF to ./{sanitized_filename}'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Saved PDF to {sanitized_filename}')# Tab Management Actions@self.registry.action('Switch tab', param_model=SwitchTabAction)@@ -201,14 +214,14 @@ class Controller(Generic[Context]):await page.wait_for_load_state()msg = f'🔄 Switched to tab {params.page_id}'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Switched to tab {params.page_id}')@self.registry.action('Open a specific url in new tab', param_model=OpenTabAction)async def open_tab(params: OpenTabAction, browser_session: BrowserSession):await browser_session.create_new_tab(params.url)msg = f'🔗 Opened new tab with {params.url}'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Opened new tab with URL {params.url}')@self.registry.action('Close an existing tab', param_model=CloseTabAction)async def close_tab(params: CloseTabAction, browser_session: BrowserSession):@@ -220,7 +233,11 @@ class Controller(Generic[Context]):new_page_idx = browser_session.tabs.index(new_page)msg = f'❌ Closed tab #{params.page_id} with {url}, now focused on tab #{new_page_idx} with url {new_page.url}'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(+ extracted_content=msg,+ include_in_memory=True,+ memory=f'Closed tab {params.page_id} with url {url}, now focused on tab {new_page_idx} with url {new_page.url}.',+ )# Content Actions@self.registry.action(@@ -252,7 +269,12 @@ class Controller(Generic[Context]):output = await page_extraction_llm.ainvoke(template.format(goal=goal, page=content))msg = f'📄 Extracted from page\n: {output.content}\n'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(+ extracted_content=msg,+ include_in_memory=True,+ memory=f'Extracted content for goal: {goal}',+ update_read_state=True,+ )except Exception as e:logger.debug(f'Error extracting content: {e}')msg = f'📄 Extracted from page\n: {content}\n'@@ -278,7 +300,9 @@ class Controller(Generic[Context]):flatten_ax_tree(node, lines)msg = '\n'.join(lines)logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=False)+ return ActionResult(+ extracted_content=msg, include_in_memory=False, memory='Retrieved accessibility tree', update_read_state=True+ )@self.registry.action('Scroll down the page by pixel amount - if none is given, scroll one page',@@ -302,7 +326,7 @@ class Controller(Generic[Context]):amount_str = f'{params.amount} pixels' if params.amount is not None else 'one page'msg = f'🔍 Scrolled down the page by {amount_str}'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Scrolled down the page by {amount_str}')@self.registry.action('Scroll up the page by pixel amount - if none is given, scroll one page',@@ -321,7 +345,7 @@ class Controller(Generic[Context]):amount_str = f'{params.amount} pixels' if params.amount is not None else 'one page'msg = f'🔍 Scrolled up the page by {amount_str}'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Scrolled up the page by{amount_str}')# send keys@self.registry.action(@@ -344,7 +368,7 @@ class Controller(Generic[Context]):raise emsg = f'⌨️ Sent keys: {params.keys}'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Sent keys: {params.keys}')@self.registry.action(description='If you dont find something which you want to interact with, scroll to it',@@ -372,7 +396,7 @@ class Controller(Generic[Context]):await asyncio.sleep(0.5) # Wait for scroll to completemsg = f'🔍 Scrolled to text: {text}'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f'Scrolled to text: {text}')except Exception as e:logger.debug(f'Locator attempt failed: {str(e)}')@@ -380,7 +404,9 @@ class Controller(Generic[Context]):msg = f"Text '{text}' not found or not visible on page"logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(+ extracted_content=msg, include_in_memory=True, memory=f"Tried scrolling to text '{text}' but it was not found"+ )except Exception as e:msg = f"Failed to scroll to text '{text}': {str(e)}"@@ -445,11 +471,16 @@ class Controller(Generic[Context]):msg = '\n'.join(all_options)msg += '\nUse the exact text string in select_dropdown_option'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(+ extracted_content=msg,+ include_in_memory=True,+ memory=f'Found dropdown options for index {index}.',+ update_read_state=True,+ )else:msg = 'No options found in any frame for dropdown'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory='No dropdown options found')except Exception as e:logger.error(f'Failed to get dropdown options: {str(e)}')@@ -474,7 +505,7 @@ class Controller(Generic[Context]):if dom_element.tag_name != 'select':logger.error(f'Element is not a select! Tag: {dom_element.tag_name}, Attributes: {dom_element.attributes}')msg = f'Cannot select option: Element with index {index} is a {dom_element.tag_name}, not a select'- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=msg)logger.debug(f"Attempting to select '{text}' using xpath: {dom_element.xpath}")logger.debug(f'Element attributes: {dom_element.attributes}')@@ -535,7 +566,7 @@ class Controller(Generic[Context]):msg = f'selected option {text} with value {selected_option_values}'logger.info(msg + f' in frame {frame_index}')- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=f"Selected option '{text}'")except Exception as frame_e:logger.error(f'Frame {frame_index} attempt failed: {str(frame_e)}')@@ -546,7 +577,7 @@ class Controller(Generic[Context]):msg = f"Could not select option '{text}' in any frame"logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=msg)except Exception as e:msg = f'Selection failed: {str(e)}'@@ -758,7 +789,7 @@ class Controller(Generic[Context]):msg = f'🖱️ Dragged from ({source_x}, {source_y}) to ({target_x}, {target_y})'logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True)+ return ActionResult(extracted_content=msg, include_in_memory=True, memory=msg)except Exception as e:error_msg = f'Failed to perform drag and drop: {str(e)}'@@ -774,7 +805,9 @@ class Controller(Generic[Context]):await page.keyboard.press('ControlOrMeta+C')extracted_tsv = await page.evaluate('() => navigator.clipboard.readText()')- return ActionResult(extracted_content=extracted_tsv, include_in_memory=True)+ return ActionResult(+ extracted_content=extracted_tsv, include_in_memory=True, memory='Retrieved sheet contents', update_read_state=True+ )@self.registry.action('Google Sheets: Get the contents of a cell or range of cells', domains=['https://docs.google.com'])async def read_cell_contents(cell_or_range: str, browser_session: BrowserSession):@@ -785,7 +818,12 @@ class Controller(Generic[Context]):await page.keyboard.press('ControlOrMeta+C')await asyncio.sleep(0.1)extracted_tsv = await page.evaluate('() => navigator.clipboard.readText()')- return ActionResult(extracted_content=extracted_tsv, include_in_memory=True)+ return ActionResult(+ extracted_content=extracted_tsv,+ include_in_memory=True,+ memory=f'Retrieved contents from {cell_or_range}',+ update_read_state=True,+ )@self.registry.action('Google Sheets: Update the content of a cell or range of cells', domains=['https://docs.google.com']@@ -802,7 +840,11 @@ class Controller(Generic[Context]):document.activeElement.dispatchEvent(new ClipboardEvent('paste', {{clipboardData}}));""")- return ActionResult(extracted_content=f'Updated cells: {cell_or_range} = {new_contents_tsv}', include_in_memory=False)+ return ActionResult(+ extracted_content=f'Updated cells: {cell_or_range} = {new_contents_tsv}',+ include_in_memory=False,+ memory=f'Updated cells {cell_or_range} with {new_contents_tsv}',+ )@self.registry.action('Google Sheets: Clear whatever cells are currently selected', domains=['https://docs.google.com'])async def clear_cell_contents(cell_or_range: str, browser_session: BrowserSession):@@ -811,7 +853,11 @@ class Controller(Generic[Context]):await select_cell_or_range(cell_or_range=cell_or_range, page=page)await page.keyboard.press('Backspace')- return ActionResult(extracted_content=f'Cleared cells: {cell_or_range}', include_in_memory=False)+ return ActionResult(+ extracted_content=f'Cleared cells: {cell_or_range}',+ include_in_memory=False,+ memory=f'Cleared cells {cell_or_range}',+ )@self.registry.action('Google Sheets: Select a specific cell or range of cells', domains=['https://docs.google.com'])async def select_cell_or_range(cell_or_range: str, page: Page):@@ -828,7 +874,11 @@ class Controller(Generic[Context]):await page.keyboard.press('Enter')await asyncio.sleep(0.2)await page.keyboard.press('Escape') # to make sure the popup still closes in the case where the jump failed- return ActionResult(extracted_content=f'Selected cells: {cell_or_range}', include_in_memory=False)+ return ActionResult(+ extracted_content=f'Selected cells: {cell_or_range}',+ include_in_memory=False,+ memory=f'Selected cells {cell_or_range}',+ )@self.registry.action('Google Sheets: Fallback method to type text into (only one) currently selected cell',@@ -838,7 +888,9 @@ class Controller(Generic[Context]):await page.keyboard.type(text, delay=0.1)await page.keyboard.press('Enter') # make sure to commit the input so it doesn't get overwritten by the next actionawait page.keyboard.press('ArrowUp')- return ActionResult(extracted_content=f'Inputted text {text}', include_in_memory=False)+ return ActionResult(+ extracted_content=f'Inputted text {text}', include_in_memory=False, memory=f"Inputted text '{text}' into cell"+ )# Register ---------------------------------------------------------------@@ -860,6 +912,7 @@ class Controller(Generic[Context]):page_extraction_llm: BaseChatModel | None = None,sensitive_data: dict[str, str] | None = None,available_file_paths: list[str] | None = None,+ file_system: FileSystem | None = None,#context: Context | None = None,) -> ActionResult:@@ -880,6 +933,7 @@ class Controller(Generic[Context]):params=params,browser_session=browser_session,page_extraction_llm=page_extraction_llm,+ file_system=file_system,sensitive_data=sensitive_data,available_file_paths=available_file_paths,context=context,diff --git a/browser_use/filesystem/__init__.py b/browser_use/filesystem/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/browser_use/filesystem/file_system.py b/browser_use/filesystem/file_system.pynew file mode 100644index 000000000..f784bf461--- /dev/null+++ b/browser_use/filesystem/file_system.py@@ -0,0 +1,93 @@+import asyncio+import re+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++INVALID_FILENAME_ERROR_MESSAGE = 'Error: Invalid filename format. Must be alphanumeric with .txt or .md extension.'+++class FileSystem:+ def __init__(self, dir_path: str):+ # Create a base directory+ self.base_dir = Path(dir_path)+ self.base_dir.mkdir(parents=True, exist_ok=True)++ # Create and use a dedicated subfolder for all operations+ self.dir = self.base_dir / 'data_storage'+ if self.dir.exists():+ raise ValueError(+ 'File system directory already exists - stopping for safety purposes. Please delete it first if you want to use this directory.'+ )+ self.dir.mkdir(exist_ok=True)++ # Initialize default files+ self.results_file = self.dir / 'results.md'+ self.todo_file = self.dir / 'todo.md'+ self.results_file.touch(exist_ok=True)+ self.todo_file.touch(exist_ok=True)++ # Create a thread pool executor for file operations+ self._executor = ThreadPoolExecutor()++ def _is_valid_filename(self, file_name: str) -> bool:+ """Check if filename matches the required pattern: name.extension"""+ pattern = r'^[a-zA-Z0-9_\-]+\.(txt|md)$'+ return bool(re.match(pattern, file_name))++ async def read_file(self, file_name: str) -> str:+ if not self._is_valid_filename(file_name):+ return INVALID_FILENAME_ERROR_MESSAGE++ path = self.dir / file_name+ if not path.exists():+ return f"File '{file_name}' not found."++ try:+ # Run file read in a thread to avoid blocking+ content = await asyncio.get_event_loop().run_in_executor(self._executor, lambda: path.read_text())+ return f'Read from file {file_name}:\n{content}'+ except Exception:+ return f"Error: Could not read file '{file_name}'."++ async def write_file(self, file_name: str, content: str) -> str:+ if not self._is_valid_filename(file_name):+ return INVALID_FILENAME_ERROR_MESSAGE++ try:+ path = self.dir / file_name+ # Run file write in a thread to avoid blocking+ await asyncio.get_event_loop().run_in_executor(self._executor, lambda: path.write_text(content))+ return f'Data written to {file_name} successfully.'+ except Exception:+ return f"Error: Could not write to file '{file_name}'."++ async def append_file(self, file_name: str, content: str) -> str:+ if not self._is_valid_filename(file_name):+ return INVALID_FILENAME_ERROR_MESSAGE++ path = self.dir / file_name+ if not path.exists():+ return f"File '{file_name}' not found."++ try:+ # Run file append in a thread to avoid blocking+ await asyncio.get_event_loop().run_in_executor(self._executor, lambda p=path, c=content: p.open('a').write(c + '\n'))+ return f'Data appended to {file_name} successfully.'+ except Exception:+ return f"Error: Could not append to file '{file_name}'."++ def describe(self) -> str:+ """List all files with their line counts."""+ description = ''+ for f in self.dir.iterdir():+ if f.is_file():+ try:+ num_lines = len(f.read_text().splitlines())+ description += f'- {f.name} — {num_lines} lines\n'+ except Exception:+ description += f'- {f.name} — [error reading file]\n'++ return description++ def get_todo_contents(self) -> str:+ return self.todo_file.read_text()