Skip to content

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

- remove append_file and instead merge it into write_file - new replace_file_str - add trailing new lines and leading_newline parameters to writing into file for robustness - adapt system prompts accordingly

mertunsalld1f532b45db9
diff --git a/browser_use/agent/system_prompt.md b/browser_use/agent/system_prompt.md
index c6346b03b..7eaab884a 100644
--- a/browser_use/agent/system_prompt.md
+++ b/browser_use/agent/system_prompt.md
@@ -98,14 +98,12 @@ Strictly follow these rules while using the browser and navigating the web:
<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 a `todo.md`: Use this to keep a checklist 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). ALWAYS use `write_file` to rewrite entire `todo.md` when you want to update your progress. NEVER use `append_file` on `todo.md` as this can explode your context.
+- Your file system is initialized with a `todo.md`: Use this to keep a checklist for known subtasks. Use `file_str_replace` tool to update markers in `todo.md` as first action whenever you complete an item. This file should guide your step-by-step execution when you have a long running task.
- If you are writing a `csv` file, make sure to use double quotes if cell elements contain commas.
-- Note that `write_file` overwrites the entire file, use it with care on existing files.
-- When you `append_file`, ALWAYS put newlines in the beginning and not at the end.
- If the file is too large, you are only given a preview of your file. Use `read_file` to see the full content if necessary.
- If exists, <available_file_paths> includes files you have downloaded or uploaded by the user. You can only read or upload these files but you don't have write access.
- If the task is really long, initialize a `results.md` file to accumulate your results.
-- DO NOT use the file system if the task is less than 5 steps!
+- DO NOT use the file system if the task is less than 10 steps!
</file_system>
<task_completion_rules>
diff --git a/browser_use/agent/system_prompt_no_thinking.md b/browser_use/agent/system_prompt_no_thinking.md
index dd9184afa..a5742b832 100644
--- a/browser_use/agent/system_prompt_no_thinking.md
+++ b/browser_use/agent/system_prompt_no_thinking.md
@@ -98,14 +98,12 @@ Strictly follow these rules while using the browser and navigating the web:
<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 a `todo.md`: Use this to keep a checklist 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). ALWAYS use `write_file` to rewrite entire `todo.md` when you want to update your progress. NEVER use `append_file` on `todo.md` as this can explode your context.
+- Your file system is initialized with a `todo.md`: Use this to keep a checklist for known subtasks. Use `file_str_replace` tool to update markers in `todo.md` as first action whenever you complete an item. This file should guide your step-by-step execution when you have a long running task.
- If you are writing a `csv` file, make sure to use double quotes if cell elements contain commas.
-- Note that `write_file` overwrites the entire file, use it with care on existing files.
-- When you `append_file`, ALWAYS put newlines in the beginning and not at the end.
- If the file is too large, you are only given a preview of your file. Use `read_file` to see the full content if necessary.
- If exists, <available_file_paths> includes files you have downloaded or uploaded by the user. You can only read or upload these files but you don't have write access.
- If the task is really long, initialize a `results.md` file to accumulate your results.
-- DO NOT use the file system if the task is less than 5 steps!
+- DO NOT use the file system if the task is less than 10 steps!
</file_system>
<task_completion_rules>
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 69be01a65..13b64d435 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -22,6 +22,7 @@ from browser_use.controller.views import (
ClickElementAction,
CloseTabAction,
DoneAction,
+ FileStrReplaceAction,
GoToUrlAction,
InputTextAction,
NoParamsAction,
@@ -31,6 +32,7 @@ from browser_use.controller.views import (
StructuredOutputAction,
SwitchTabAction,
UploadFileAction,
+ WriteFileAction,
)
from browser_use.filesystem.file_system import FileSystem
from browser_use.llm.base import BaseChatModel
@@ -744,16 +746,26 @@ Explain the content of the page and that the requested information is not availa
# File System Actions
@self.registry.action(
- 'Write content to file_name in file system. Allowed extensions are .md, .txt, .json, .csv, .pdf. For .pdf files, write the content in markdown format and it will automatically be converted to a properly formatted PDF document.'
+ 'Write or append content to file_name in file system. Allowed extensions are .md, .txt, .json, .csv, .pdf. For .pdf files, write the content in markdown format and it will automatically be converted to a properly formatted PDF document.'
)
- async def write_file(file_name: str, content: str, file_system: FileSystem):
- result = await file_system.write_file(file_name, content)
+ async def write_file(params: WriteFileAction, file_system: FileSystem):
+ content = params.content
+ if params.trailing_newline:
+ content += '\n'
+ if params.leading_newline:
+ content = '\n' + content
+ if params.append:
+ result = await file_system.append_file(params.file_name, content)
+ else:
+ result = await file_system.write_file(params.file_name, content)
logger.info(f'💾 {result}')
return ActionResult(extracted_content=result, include_in_memory=True, long_term_memory=result)
- @self.registry.action('Append content to file_name in file system')
- async def append_file(file_name: str, content: str, file_system: FileSystem):
- result = await file_system.append_file(file_name, content)
+ @self.registry.action(
+ 'Replace old_str with new_str in file_name. old_str must exactly match the string to replace in original text. Recommended tool to mark completed items in todo.md or change specific contents in a file.'
+ )
+ async def file_str_replace(params: FileStrReplaceAction, file_system: FileSystem):
+ result = await file_system.replace_file_str(params.file_name, params.old_str, params.new_str)
logger.info(f'💾 {result}')
return ActionResult(extracted_content=result, include_in_memory=True, long_term_memory=result)
diff --git a/browser_use/controller/views.py b/browser_use/controller/views.py
index cf3eadcdc..57d6b46d9 100644
--- a/browser_use/controller/views.py
+++ b/browser_use/controller/views.py
@@ -1,6 +1,6 @@
from typing import Generic, TypeVar
-from pydantic import BaseModel, ConfigDict, Field
+from pydantic import BaseModel, ConfigDict
# Action Input Models
@@ -73,28 +73,15 @@ class NoParamsAction(BaseModel):
# No fields defined - all inputs are ignored automatically
-class Position(BaseModel):
- x: int
- y: int
+class WriteFileAction(BaseModel):
+ file_name: str
+ content: str
+ append: bool = False
+ trailing_newline: bool = True
+ leading_newline: bool = False
-class DragDropAction(BaseModel):
- # Element-based approach
- element_source: str | None = Field(None, description='CSS selector or XPath of the element to drag from')
- element_target: str | None = Field(None, description='CSS selector or XPath of the element to drop onto')
- element_source_offset: Position | None = Field(
- None, description='Precise position within the source element to start drag (in pixels from top-left corner)'
- )
- element_target_offset: Position | None = Field(
- None, description='Precise position within the target element to drop (in pixels from top-left corner)'
- )
-
- # Coordinate-based approach (used if selectors not provided)
- coord_source_x: int | None = Field(None, description='Absolute X coordinate on page to start drag from (in pixels)')
- coord_source_y: int | None = Field(None, description='Absolute Y coordinate on page to start drag from (in pixels)')
- coord_target_x: int | None = Field(None, description='Absolute X coordinate on page to drop at (in pixels)')
- coord_target_y: int | None = Field(None, description='Absolute Y coordinate on page to drop at (in pixels)')
-
- # Common options
- steps: int | None = Field(10, description='Number of intermediate points for smoother movement (5-20 recommended)')
- delay_ms: int | None = Field(5, description='Delay in milliseconds between steps (0 for fastest, 10-20 for more natural)')
+class FileStrReplaceAction(BaseModel):
+ file_name: str
+ old_str: str
+ new_str: str
diff --git a/browser_use/filesystem/file_system.py b/browser_use/filesystem/file_system.py
index 9e6777cb0..6af9c7a07 100644
--- a/browser_use/filesystem/file_system.py
+++ b/browser_use/filesystem/file_system.py
@@ -321,6 +321,25 @@ class FileSystem:
except Exception as e:
return f"Error: Could not append to file '{full_filename}'. {str(e)}"
+ async def replace_file_str(self, full_filename: str, old_str: str, new_str: str) -> str:
+ """Replace old_str with new_str in file_name"""
+ if not self._is_valid_filename(full_filename):
+ return INVALID_FILENAME_ERROR_MESSAGE
+
+ file_obj = self.get_file(full_filename)
+ if not file_obj:
+ return f"File '{full_filename}' not found."
+
+ try:
+ content = file_obj.read()
+ content = content.replace(old_str, new_str)
+ await file_obj.write(content, self.data_dir)
+ return f'Successfully replaced all occurrences of "{old_str}" with "{new_str}" in file {full_filename}'
+ except FileSystemError as e:
+ return str(e)
+ except Exception as e:
+ return f"Error: Could not replace string in file '{full_filename}'. {str(e)}"
+
async def save_extracted_content(self, content: str) -> str:
"""Save extracted content to a numbered file"""
initial_filename = f'extracted_content_{self.extracted_content_count}'