SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]
SWE-agent Multimodal (#1223)
Kilian Lieret4fce28706f96
diff --git a/config/default_mm_no_images.yaml b/config/default_mm_no_images.yamlnew file mode 100644index 00000000..b4cc9fca--- /dev/null+++ b/config/default_mm_no_images.yaml@@ -0,0 +1,82 @@+# Configuration for SWE-agent with image viewing capabilities+# This extends the default config with image parsing history processor+# and the image_tools bundle for viewing images as base64-encoded markdown.+agent:+ templates:+ # disable_image_processing: false+ disable_image_processing: true+ system_template: |-+ You are a helpful assistant that can interact with a computer to solve tasks.+ instance_template: |-+ <uploaded_files>+ {{working_dir}}+ </uploaded_files>+ I've uploaded a python code repository in the directory {{working_dir}}. Consider the following PR description:++ <pr_description>+ {{problem_statement}}+ </pr_description>++ Can you help me implement the necessary changes to the repository so that the requirements specified in the <pr_description> are met?+ I've already taken care of all changes to any of the test files described in the <pr_description>. This means you DON'T have to modify the testing logic or any of the tests in any way!+ Your task is to make the minimal changes to non-tests files in the {{working_dir}} directory to ensure the <pr_description> is satisfied.+ Follow these steps to resolve the issue:+ 1. As a first step, it might be a good idea to find and read code relevant to the <pr_description>+ 2. Create a script to reproduce the error and execute it with `python <filename.py>` using the bash tool, to confirm the error+ 3. Edit the sourcecode of the repo to resolve the issue+ 4. Rerun your reproduce script and confirm that the error is fixed!+ 5. Think about edgecases and make sure your fix handles them as well+ Your thinking should be thorough and so it's fine if it's very long.++ Note: You can use the view_image command to display images as embedded base64 data when relevant.++ If you need to start a command that has long-running output (e.g. a web server), you should _always_ use the following pattern:+ server_command &> my_server_log.txt &++ This way you can see the server's output in the my_server_log.txt file and it will not block the rest of your work.+ next_step_template: |-+ OBSERVATION:+ {{observation}}+ next_step_no_output_template: |-+ Your command ran successfully and did not produce any output.+ max_observation_length: 10_000_000 # need longer for images+ tools:+ execution_timeout: 300 # need longer for builds+ bundles:+ - path: tools/registry+ - path: tools/edit_anthropic+ # - path: tools/image_tools # lets models view image files+ # - path: tools/web_browser # browser tool for interacting with web servers+ - path: tools/review_on_submit_m+ registry_variables:+ USE_FILEMAP: 'true'+ SUBMIT_REVIEW_MESSAGES:+ - |+ Thank you for your work on this issue. Please carefully follow the steps below to help review your changes.++ 1. If you made any changes to your code after running the reproduction script, please run the reproduction script again.+ If the reproduction script is failing, please revisit your changes and make sure they are correct.+ If you have already removed your reproduction script, please ignore this step.+ 2. Remove your reproduction script (if you haven't done so already).+ 3. If you have modified any TEST files, please revert them to the state they had before you started fixing the issue.+ You can do this with `git checkout -- /path/to/test/file.py`. Use below <diff> to find the files you need to revert.+ 4. Run the submit command again to confirm.++ Here is a list of all of your changes:++ <diff>+ {{diff}}+ </diff>+ enable_bash_tool: true+ parse_function:+ type: function_calling+ # history_processors:+ # - type: image_parsing # parses base64 encoded images in the observation+ # - type: cache_control # enable for claude+ # last_n_messages: 2 # enable for claude+instances:+ type: swe_bench+ subset: multimodal+ split: dev+ shuffle: true+ # filter: processing__p5.js-6069diff --git a/config/default_mm_with_images.yaml b/config/default_mm_with_images.yamlnew file mode 100644index 00000000..ca11206e--- /dev/null+++ b/config/default_mm_with_images.yaml@@ -0,0 +1,83 @@+# Configuration for SWE-agent with image viewing capabilities+# This extends the default config with image parsing history processor+# and the image_tools bundle for viewing images as base64-encoded markdown.+agent:+ templates:+ disable_image_processing: false+ system_template: |-+ You are a helpful assistant that can interact with a computer to solve tasks.+ instance_template: |-+ <uploaded_files>+ {{working_dir}}+ </uploaded_files>+ I've uploaded a python code repository in the directory {{working_dir}}. Consider the following PR description:++ <pr_description>+ {{problem_statement}}+ </pr_description>++ Can you help me implement the necessary changes to the repository so that the requirements specified in the <pr_description> are met?+ I've already taken care of all changes to any of the test files described in the <pr_description>. This means you DON'T have to modify the testing logic or any of the tests in any way!+ Your task is to make the minimal changes to non-tests files in the {{working_dir}} directory to ensure the <pr_description> is satisfied.+ Follow these steps to resolve the issue:+ 1. As a first step, it might be a good idea to find and read code relevant to the <pr_description>+ 2. Create a script to reproduce the error and execute it with `python <filename.py>` using the bash tool, to confirm the error+ 3. Edit the sourcecode of the repo to resolve the issue+ 4. Rerun your reproduce script and confirm that the error is fixed!+ 5. Think about edgecases and make sure your fix handles them as well+ Your thinking should be thorough and so it's fine if it's very long.++ Note: You can use the view_image command to display images as embedded base64 data when relevant.+ You'll also be given access browser tools to interact with the web or a local server.+ In the browser, your mouse is shown as a red crosshair.++ If you need to start a command that has long-running output (e.g. a web server), you should _always_ use the following pattern:+ server_command &> my_server_log.txt &++ This way you can see the server's output in the my_server_log.txt file and it will not block the rest of your work.+ next_step_template: |-+ OBSERVATION:+ {{observation}}+ next_step_no_output_template: |-+ Your command ran successfully and did not produce any output.+ max_observation_length: 10_000_000 # need longer for images+ tools:+ execution_timeout: 300 # need longer for builds+ bundles:+ - path: tools/registry+ - path: tools/edit_anthropic+ - path: tools/image_tools # lets models view image files+ - path: tools/web_browser # browser tool for interacting with web servers+ - path: tools/review_on_submit_m+ registry_variables:+ USE_FILEMAP: 'true'+ SUBMIT_REVIEW_MESSAGES:+ - |+ Thank you for your work on this issue. Please carefully follow the steps below to help review your changes.++ 1. If you made any changes to your code after running the reproduction script, please run the reproduction script again.+ If the reproduction script is failing, please revisit your changes and make sure they are correct.+ If you have already removed your reproduction script, please ignore this step.+ 2. Remove your reproduction script (if you haven't done so already).+ 3. If you have modified any TEST files, please revert them to the state they had before you started fixing the issue.+ You can do this with `git checkout -- /path/to/test/file.py`. Use below <diff> to find the files you need to revert.+ 4. Run the submit command again to confirm.++ Here is a list of all of your changes:++ <diff>+ {{diff}}+ </diff>+ enable_bash_tool: true+ parse_function:+ type: function_calling+ history_processors:+ - type: image_parsing # parses base64 encoded images in the observation+ # - type: cache_control # enable for claude+ # last_n_messages: 2 # enable for claude+instances:+ type: swe_bench+ subset: multimodal+ split: dev+ shuffle: true+ # filter: processing__p5.js-6069diff --git a/docs/config/config.md b/docs/config/config.mdindex 0f673f7a..4f571608 100644--- a/docs/config/config.md+++ b/docs/config/config.md@@ -13,6 +13,8 @@ A configuration is represented in one or more `.yaml` files, specified by the `-!!! tip "Default config files"Our default config files are in the [`config/`](https://github.com/SWE-agent/SWE-agent/tree/main/config) directory.+ For multimodal support, use `config/default_mm_with_images.yaml` which includes image processing capabilities.+To use a config file, you can use the `--config` flag in the command line interface.```bash@@ -38,3 +40,33 @@ This is the current default configuration file which is loaded when no `--configRelative paths in config files are resolved to the `SWE_AGENT_CONFIG_ROOT` environment variable (if set)or the SWE-agent repository root.+## Multimodal Configuration++For working with images and vision-capable models, SWE-agent provides specialized multimodal configuration options.++These options are best demonstrated in `default_mm_with_images.yaml`.++This configuration enables full image processing capabilities:++- **SWE-bench Multimodal Image processing**: Downloads and converts GitHub issue images to base64 format for SWE-bench Multimodal instances.+- **Extended observation length**: Increases observation token limits to accommodate images+- **Image tools**: Includes `image_tools` bundle for viewing images+- **Web browsing tools**: Includes `web_browser` bundle for using web browsers+- **History processing**: Enables `image_parsing` history processor for parsing++### Key Multimodal Settings++```yaml+agent:+ templates:+ disable_image_processing: false # enable/disable image processing+ max_observation_length: 10_000_000 # increased for images+ tools:+ bundles:+ - path: tools/image_tools # image viewing capabilities+ - path: tools/web_browser # browser automation tools+ history_processors:+ - type: image_parsing # process image tools outputs (required for tools to work)+```++See the [multimodal guide](../usage/multimodal.md) for detailed configuration options.diff --git a/docs/faq.md b/docs/faq.mdindex 5cc8d118..8459d773 100644--- a/docs/faq.md+++ b/docs/faq.md@@ -13,9 +13,9 @@ This is probably because of union types.See [this section](usage/cl_tutorial.md#union-types) for more information, but the short version is that some options (e.g., the repository or problem statement) can be specified in multiple ways, so we try every option until we find the one that works based on your inputs.If none of them work, we throw an error which then tells you why we cannot initialize any of the types, so this will get somewhat long and confusing.-> I have a question/bug report/feature request...+> Why are my images not being processed?-Please open a [github issue!](https://github.com/SWE-agent/SWE-agent/issues)!+Check that you're using a multimodal configuration (see `default_mm_with_images.yaml` as an example), have internet connectivity, and images are under 10MB. See [Multimodal usage notes](usage/multimodal.md) for more details.## Models@@ -23,6 +23,10 @@ Please open a [github issue!](https://github.com/SWE-agent/SWE-agent/issues)!Probably all of them, including local models! There's even a few for testing. See [models](installation/keys.md) and [more on models](config/models.md).+> Does SWE-agent support multimodal models and images?++Yes! SWE-agent supports vision-capable models that can process images from GitHub issues. Use `--config config/default_mm_with_images.yaml` and specify a multimodal model like Claude Sonnet 4 or GPT-4o. See the [multimodal guide](usage/multimodal.md) for details.+> What can I do if my model doesn't support function calling?You can configure how to parse the model's response by choosing your `agent.tools.parse_function`.@@ -48,4 +52,11 @@ Yes! Take a look at [this tutorial](usage/adding_custom_tools.md).You're probably most interested in the `*.traj` files, which contain complete records of SWE-agent's thought process and actions. See [output files](usage/trajectories.md) for more information.+## Anything else?++> I have a question/bug report/feature request...++Please open a [github issue!](https://github.com/SWE-agent/SWE-agent/issues)!++{% include-markdown "_footer.md" %}\ No newline at end of filediff --git a/docs/index.md b/docs/index.mdindex 9a4bcb4b..3a3f666c 100644--- a/docs/index.md+++ b/docs/index.md@@ -68,6 +68,7 @@ SWE-agent is built and maintained by researchers from Princeton University and S## 📣 News+* **NEW**: [Multimodal support for SWE-bench](usage/multimodal.md) - Process images from GitHub issues with vision-capable AI models* May 2: [SWE-agent-LM-32b](https://swesmith.com) achieves open-weights SOTA on SWE-bench* Feb 28: [SWE-agent 1.0 + Claude 3.7 is SoTA on SWE-Bench full](https://x.com/KLieret/status/1895487966409298067)* Feb 25: [SWE-agent 1.0 + Claude 3.7 is SoTA on SWE-bench verified](https://x.com/KLieret/status/1894408819670733158)diff --git a/docs/usage/batch_mode.md b/docs/usage/batch_mode.mdindex ea948f2f..e85e5fb0 100644--- a/docs/usage/batch_mode.md+++ b/docs/usage/batch_mode.md@@ -52,6 +52,37 @@ Kind of slow, isn't it?If you are using [`sb-cli`](https://www.swebench.com/sb-cli/), you can automatically evaluate on SWE-bench by adding the `--evaluate=True` flag.This will already submit submissions to `sb-cli` while you are running, so that you should receive results within a minute of finishing your run.+## Multimodal SWE-bench++SWE-agent supports the **SWE-bench Multimodal** dataset, which includes GitHub issues with associated images (screenshots, diagrams, UI mockups). To run on multimodal instances:++```bash+sweagent run-batch \+ --config config/default_mm_with_images.yaml \+ --agent.model.name claude-sonnet-4-20250514 \+ --agent.model.per_instance_cost_limit 2.00 \+ --instances.type swe_bench \+ --instances.subset multimodal \+ --instances.split dev \+ --instances.slice :3 \+ --instances.shuffle=True+```++Key differences for multimodal runs:++- **Configuration**: Use `config/default_mm_with_images.yaml` which includes image processing capabilities+- **Subset**: Use `--instances.subset multimodal` to access the multimodal dataset+- **Token limits**: Consider higher cost limits as images consume more tokens+- **Multimodal Tools**: `tools/image_tools` and `tools/web_browser` include useful tools for viewing images and web browsers++The system automatically:+- Downloads images from GitHub issue URLs+- Converts them to base64 markdown format+- Provides visual context to the AI model++!!! tip "Multimodal Configuration"+ See the [multimodal guide](multimodal.md) for detailed configuration options and troubleshooting.+## Running in parallelLet's speed things up and run on 5 instances at once. Only a single line to change:diff --git a/docs/usage/index.md b/docs/usage/index.mdindex 00d6e2a5..5931b024 100644--- a/docs/usage/index.md+++ b/docs/usage/index.md@@ -29,4 +29,12 @@ Just want to run it? See [getting started](../index.md) instead+- :material-image:{ .lg .middle } __Multimodal Support__++ ---++ Use SWE-agent with vision-capable AI models for image processing.++ [:octicons-arrow-right-24: Multimodal Guide](multimodal.md)+</div>diff --git a/docs/usage/multimodal.md b/docs/usage/multimodal.mdnew file mode 100644index 00000000..38e7d67f--- /dev/null+++ b/docs/usage/multimodal.md@@ -0,0 +1,157 @@+# Multimodal Support++SWE-agent supports multimodal AI models that can process both text and images. This enables the agent to work with visual context from GitHub issues, such as screenshots, diagrams, and UI mockups.++## Overview++The multimodal implementation automatically:++- **Detects multimodal instances** from SWE-bench Multimodal datasets+- **Downloads images** from GitHub issue URLs+- **Converts to base64 markdown** format for AI model consumption+- **Handles errors gracefully** with fallback to text-only processing++## Supported Image Categories++Currently, SWE-agent processes images from the `problem_statement` category, which includes:++- Screenshots showing bugs or issues+- UI mockups and design specifications+- Diagrams explaining the problem+- Error screenshots and visual evidence++!!! note "Design Choice"+ Only `problem_statement` images are processed to provide essential visual context for understanding the task, while preserving agent autonomy in determining solution approaches. Images from `patch` and `test_patch` categories may contain solution hints and are not processed.++## Configuration++### Basic Multimodal Setup++Use the pre-configured multimodal setup:++```bash+sweagent run-batch \+ --config config/default_mm_with_images.yaml \+ --instances.type swe_bench \+ --instances.subset multimodal \+ --instances.split dev+```++### Disabling Image Processing++You can disable image processing globally:++```yaml+# config/your_config.yaml+agent:+ templates:+ disable_image_processing: true+```++Or for specific instances:++```python+from sweagent.agent.problem_statement import SWEBenchMultimodalProblemStatement++problem_statement = SWEBenchMultimodalProblemStatement(+ text="Fix the rendering issue",+ issue_images=["https://example.com/screenshot.png"],+ disable_image_processing=True # Skip image processing+)+```++## Supported Models++Multimodal support works with any vision-capable models, including:++- **Claude Sonnet 4**+- **o3** and **o4-mini**+- **Gemini 2.5** models++Example model configuration:++```yaml+# model_configs/claude-sonnet-4-20250514_mm.yaml+model:+ name: claude-sonnet-4-20250514+ # Vision capabilities automatically detected+```++## Image Processing Details++### Supported Formats+- PNG, JPEG, WebP images+- Maximum size: 10MB per image+++## Example Usage++### Automatic Detection++When loading SWE-bench instances, multimodal support is automatic:++```json+{+ "instance_id": "example__repo-123",+ "problem_statement": "Fix the chart rendering bug...",+ "image_assets": {+ "problem_statement": ["http://example.com/chart.png"]+ }+}+```++### Direct Usage++```python+from sweagent.agent.problem_statement import SWEBenchMultimodalProblemStatement++problem_statement = SWEBenchMultimodalProblemStatement(+ text="Fix the rendering issue shown in the screenshots",+ issue_images=[+ "https://example.com/before.png",+ "https://example.com/after.png"+ ]+)++# This downloads images and converts them to base64 markdown+processed_text = problem_statement.get_problem_statement()+```++## Configuration Options++In order to enable multimodal processing, you need to update the following configuration options:++### History Processing++Enable image parsing in your configuration:++```yaml+agent:+ history_processors:+ - type: image_parsing # Parse base64 encoded images in observations+```++### Tool Bundles++Include image and browser tools for visual tasks:++```yaml+agent:+ tools:+ bundles:+ - path: tools/image_tools # includes open_image tool to let models open image files+ - path: tools/web_browser # includes 17 browser automation tools (click_mouse, open_site, etc.)+```++The `web_browser` bundle provides tools for:+- Opening websites (`open_site`)+- Taking screenshots (`screenshot_site`)+- Interacting with web pages (`click_mouse`, `type_text`, `scroll_on_page`)+- Executing JavaScript (`execute_script_on_page`)+- And more - see the [configuration guide](../config/config.md#web-browser-tools) for the full list++### Templates Configuration++We've enabled multimodal processing when `--instances.type=swe-bench --instances.subset=multimodal` are set.++To disable this behavior, you must set `--templates.disable_image_processing=true`.\ No newline at end of filediff --git a/pyproject.toml b/pyproject.tomlindex 96f59b74..7f2de6c7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -60,6 +60,7 @@ dependencies = ["swe-rex>=1.2.0","tabulate","textual>=1.0.0",+ "requests",][project.scripts]diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex fa10bb93..45220045 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -95,6 +95,10 @@ class TemplateConfig(BaseModel):put_demos_in_history: bool = False"""If True, add demonstration to history instead of as a single message"""+ disable_image_processing: bool = False+ """If True, disable image processing for multimodal problem statements (i.e. SWEBenchMultimodalProblemStatement).+ """+shell_check_error_template: str = ("Your bash command contained syntax errors and was NOT executed. ""Please fix the syntax errors and try again. This can be the result "@@ -566,6 +570,16 @@ class DefaultAgent(AbstractAgent):This method is called by `self.run`."""output_dir.mkdir(parents=True, exist_ok=True)++ # apply template configuration to multimodal problem statements+ if hasattr(problem_statement, "type") and problem_statement.type == "swe_bench_multimodal":+ from sweagent.agent.problem_statement import SWEBenchMultimodalProblemStatement++ if isinstance(problem_statement, SWEBenchMultimodalProblemStatement):+ # apply the global disable_image_processing setting if it's not explicitly set+ if not problem_statement.disable_image_processing and self.templates.disable_image_processing:+ problem_statement.disable_image_processing = True+self._problem_statement = problem_statementself._env = enviid = self._problem_statement.id@@ -585,7 +599,7 @@ class DefaultAgent(AbstractAgent):self.info["swe_rex_hash"] = get_rex_commit_hash()assert self._env is not Noneassert self._problem_statement is not None- self._env.set_env_variables({"PROBLEM_STATEMENT": self._problem_statement.get_problem_statement()})+ self._env.set_env_variables({"PROBLEM_STATEMENT": self._problem_statement.get_problem_statement_for_env()})self.add_system_message_to_history()self.add_demonstrations_to_history()self.add_instance_template_to_history(state=self.tools.get_state(self._env))diff --git a/sweagent/agent/history_processors.py b/sweagent/agent/history_processors.pyindex 9f030a86..2ca8c03d 100644--- a/sweagent/agent/history_processors.py+++ b/sweagent/agent/history_processors.py@@ -20,6 +20,14 @@ class AbstractHistoryProcessor(Protocol):# -----------------+def _get_content_stats(entry: HistoryItem) -> tuple[int, int]:+ if isinstance(entry["content"], str):+ return len(entry["content"].splitlines()), 0+ n_text_lines = sum(len(item["text"].splitlines()) for item in entry["content"] if item.get("type") == "text")+ n_images = sum(1 for item in entry["content"] if item.get("type") == "image_url")+ return n_text_lines, n_images++def _get_content_text(entry: HistoryItem) -> str:if isinstance(entry["content"], str):return entry["content"]@@ -37,8 +45,8 @@ def _set_content_text(entry: HistoryItem, text: str) -> None:def _clear_cache_control(entry: HistoryItem) -> None:if isinstance(entry["content"], list):- assert len(entry["content"]) == 1, "Expected single message in content"- entry["content"][0].pop("cache_control", None)+ for item in entry["content"]:+ item.pop("cache_control", None)entry.pop("cache_control", None)@@ -160,8 +168,10 @@ class LastNObservations(BaseModel):assert data.get("message_type") == "observation", (f"Expected observation for dropped entry, got: {data.get('message_type')}")- text = _get_content_text(data)- _set_content_text(data, f"Old environment output: ({len(text.splitlines())} lines omitted)")+ num_text_lines, num_images = _get_content_stats(data)+ data["content"] = f"Old environment output: ({num_text_lines} lines omitted)"+ if num_images > 0:+ data["content"] += f" ({num_images} images omitted)"new_history.append(data)return new_history@@ -314,20 +324,76 @@ class RemoveRegex(BaseModel):if i_entry < self.keep_last:new_history.append(entry)else:- text = _get_content_text(entry)- for pattern in self.remove:- text = re.sub(pattern, "", text, flags=re.DOTALL)- _set_content_text(entry, text)+ if isinstance(entry["content"], list):+ for item in entry["content"]:+ if item["type"] == "text":+ for pattern in self.remove:+ item["text"] = re.sub(pattern, "", item["text"], flags=re.DOTALL)+ else:+ assert isinstance(entry["content"], str), "Expected string content"+ for pattern in self.remove:+ entry["content"] = re.sub(pattern, "", entry["content"], flags=re.DOTALL)new_history.append(entry)return list(reversed(new_history))+class ImageParsingHistoryProcessor(BaseModel):+ """Parse embedded base64 images from markdown and convert to multi-modal format."""++ type: Literal["image_parsing"] = "image_parsing"+ allowed_mime_types: set[str] = {"image/png", "image/jpeg", "image/webp"}++ _pattern = re.compile(r"(!\[([^\]]*)\]\(data:)([^;]+);base64,([^)]+)(\))")+ model_config = ConfigDict(extra="forbid")++ def __call__(self, history: History) -> History:+ return [self._process_entry(entry) for entry in history]++ def _process_entry(self, entry: HistoryItem) -> HistoryItem:+ if entry.get("role") not in ["user", "tool"]:+ return entry+ entry = copy.deepcopy(entry)+ content = _get_content_text(entry)+ segments = self._parse_images(content)+ if any(seg["type"] == "image_url" for seg in segments):+ entry["content"] = segments+ return entry++ def _parse_images(self, content: str) -> list[dict]:+ segments = []+ last_end = 0+ has_images = False++ def add_text(text: str) -> None:+ """Add text to the last segment if it's text, otherwise create new text segment."""+ if text and segments and segments[-1]["type"] == "text":+ segments[-1]["text"] += text+ elif text:+ segments.append({"type": "text", "text": text})++ for match in self._pattern.finditer(content):+ markdown_prefix, alt_text, mime_type, base64_data, markdown_suffix = match.groups()+ add_text(content[last_end : match.start()])+ mime_type = "image/jpeg" if mime_type == "image/jpg" else mime_type+ if mime_type in self.allowed_mime_types:+ add_text(markdown_prefix)+ segments.append({"type": "image_url", "image_url": {"url": f"data:{mime_type};base64,{base64_data}"}})+ add_text(markdown_suffix)+ has_images = True+ else:+ add_text(match.group(0))+ last_end = match.end()+ add_text(content[last_end:])+ return segments if has_images else [{"type": "text", "text": content}]++HistoryProcessor = Annotated[DefaultHistoryProcessor| LastNObservations| ClosedWindowHistoryProcessor| TagToolCallObservations| CacheControlHistoryProcessor- | RemoveRegex,+ | RemoveRegex+ | ImageParsingHistoryProcessor,Field(discriminator="type"),]diff --git a/sweagent/agent/problem_statement.py b/sweagent/agent/problem_statement.pyindex 897d7724..582f4520 100644--- a/sweagent/agent/problem_statement.py+++ b/sweagent/agent/problem_statement.py@@ -1,28 +1,60 @@+import base64import hashlibimport osimport uuidfrom pathlib import Pathfrom typing import Any, Literal, Protocol+from urllib.parse import urlparse-from pydantic import BaseModel, ConfigDict, Field+import requests+from pydantic import BaseModel, ConfigDict, Field, PrivateAttrfrom sweagent.utils.github import _get_problem_statement_from_github_issue, _parse_gh_issue_urlfrom sweagent.utils.log import get_loggerlogger = get_logger("swea-config", emoji="🔧")+# Constants for image processing+VALID_IMAGE_MIME_TYPES = {+ "image/png",+ "image/jpeg",+ "image/jpg", # Some servers return jpg instead of jpeg+ "image/webp",+}+class ProblemStatement(Protocol):- """A problem statement for a task."""+ """A problem statement for a task. Any class that implements this protocol+ can be used as a problem statement.+ """id: strdef get_problem_statement(self) -> str: ...+ def get_problem_statement_for_env(self) -> str:+ """Used for setting environment variables in the container.++ By default, this is the same as get_problem_statement().+ """+ return self.get_problem_statement()+def get_extra_fields(self) -> dict[str, Any]: ...-class EmptyProblemStatement(BaseModel):+class _BuiltinProblemStatementBase(BaseModel):+ """A base class for the builtin problem statements to avoid typing much"""++ def get_problem_statement(self) -> str: ...++ def get_problem_statement_for_env(self) -> str:+ return self.get_problem_statement()++ def get_extra_fields(self) -> dict[str, Any]:+ return {}+++class EmptyProblemStatement(_BuiltinProblemStatementBase):id: str = Field(default_factory=lambda: str(uuid.uuid4()))type: Literal["empty"] = "empty""""Discriminator for (de)serialization/CLI. Do not change."""@@ -32,11 +64,8 @@ class EmptyProblemStatement(BaseModel):def get_problem_statement(self) -> str:return ""- def get_extra_fields(self) -> dict[str, Any]:- return {}--class TextProblemStatement(BaseModel):+class TextProblemStatement(_BuiltinProblemStatementBase):text: strextra_fields: dict[str, Any] = Field(default_factory=dict)@@ -69,7 +98,7 @@ class TextProblemStatement(BaseModel):return f"id={self.id}, text={self.text[:30]}..."-class FileProblemStatement(BaseModel):+class FileProblemStatement(_BuiltinProblemStatementBase):path: Pathextra_fields: dict[str, Any] = Field(default_factory=dict)@@ -96,7 +125,7 @@ class FileProblemStatement(BaseModel):return self.extra_fields-class GithubIssue(BaseModel):+class GithubIssue(_BuiltinProblemStatementBase):github_url: strextra_fields: dict[str, Any] = Field(default_factory=dict)@@ -125,11 +154,144 @@ class GithubIssue(BaseModel):return self.extra_fields-ProblemStatementConfig = TextProblemStatement | GithubIssue | EmptyProblemStatement | FileProblemStatement+class SWEBenchMultimodalProblemStatement(_BuiltinProblemStatementBase):+ text: str++ issue_images: list[str] = Field(default_factory=list)+ """List of image asset URLs.+ """++ disable_image_processing: bool = False+ """If True, skip image downloading and processing, treating this as a text-only problem statement.+ """++ extra_fields: dict[str, Any] = Field(default_factory=dict)+ """Any additional data to be added to the instance.+ This data will be available when formatting prompt templates.+ """++ type: Literal["swe_bench_multimodal"] = "swe_bench_multimodal"+ """Discriminator for (de)serialization/CLI. Do not change."""++ id: str = None # type: ignore++ _cached_problem_statement: str | None = PrivateAttr(default=None)++ model_config = ConfigDict(extra="forbid")++ def model_post_init(self, __context: Any) -> None:+ if self.id is None:+ logger.info("Setting problem statement id to hash of text")+ self.id = hashlib.sha256(self.text.encode()).hexdigest()[:6]++ def get_problem_statement_for_env(self) -> str:+ """Return the problem statement without images.++ Images are not supported in the environment.+ """+ return self.text++ def get_problem_statement(self) -> str:+ if self.disable_image_processing:+ logger.info("Image processing disabled, returning text-only problem statement")+ return self.text++ if self._cached_problem_statement is not None:+ return self._cached_problem_statement++ processed_text = self.text+ for link in self.issue_images:+ try:+ image_markdown = self._download_and_convert_image(link)+ if image_markdown:+ processed_text += f"\n\n{image_markdown}"+ except Exception as e:+ logger.warning(f"Failed to process image from {link}: {e}")++ # cache to avoid re-processing images+ self._cached_problem_statement = processed_text+ return processed_text++ def get_extra_fields(self) -> dict[str, Any]:+ return self.extra_fields++ def _download_and_convert_image(self, url: str) -> str | None:+ """Download an image from URL and convert it to base64 markdown format.++ Args:+ url: The URL of the image to download++ Returns:+ Base64 markdown string if successful, None if failed++ Raises:+ Various exceptions for network/processing errors+ """+ try:+ parsed_url = urlparse(url)+ if not parsed_url.scheme or not parsed_url.netloc:+ logger.warning(f"Invalid URL format: {url}")+ return None+ headers = {+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.133 Safari/537.36"+ }+ response = requests.get(url, headers=headers, timeout=30, stream=True)+ response.raise_for_status()+ content_type = response.headers.get("content-type", "").lower()+ if content_type == "image/jpg":+ content_type = "image/jpeg"+ if content_type not in VALID_IMAGE_MIME_TYPES:+ logger.warning(f"Unsupported image MIME type '{content_type}' for URL: {url}. Not encoding image.")+ return None+ max_size = 10 * 1024 * 1024 # 10MB+ content_length = response.headers.get("content-length")+ if content_length and int(content_length) > max_size:+ logger.warning(f"Image too large ({content_length} bytes) for URL: {url}")+ return None+ image_data = b""+ for chunk in response.iter_content(chunk_size=8192):+ image_data += chunk+ if len(image_data) > max_size:+ logger.warning(f"Image too large (>{max_size} bytes) for URL: {url}")+ return None+ if not image_data:+ logger.warning(f"Empty image data for URL: {url}")+ return None+ b64_data = base64.b64encode(image_data).decode("ascii")+ markdown = f""+ logger.info(f"Successfully processed image from {url} ({len(image_data)} bytes, {content_type})")+ return markdown++ except requests.exceptions.Timeout:+ logger.warning(f"Timeout downloading image from {url}")+ return None+ except requests.exceptions.RequestException as e:+ logger.warning(f"Network error downloading image from {url}: {e}")+ return None+ except Exception as e:+ logger.warning(f"Unexpected error processing image from {url}: {e}")+ return None++ def __repr__(self) -> str:+ n_images = len(self.issue_images)+ return f"SWEBenchMultimodalProblemStatement(id={self.id}, text={self.text[:30]}..., images={n_images})"++ def __str__(self) -> str:+ n_images = len(self.issue_images)+ return f"id={self.id}, text={self.text[:30]}..., images={n_images}"+++ProblemStatementConfig = (+ TextProblemStatement+ | SWEBenchMultimodalProblemStatement+ | GithubIssue+ | EmptyProblemStatement+ | FileProblemStatement+)def problem_statement_from_simplified_input(- *, input: str, type: Literal["text", "text_file", "github_issue"]+ *, input: str, type: Literal["text", "text_file", "github_issue", "swe_bench_multimodal"]) -> ProblemStatementConfig:"""Get a problem statement from an `input` string and a `type`.@@ -143,6 +305,8 @@ def problem_statement_from_simplified_input(return FileProblemStatement(path=Path(input))elif type == "github_issue":return GithubIssue(github_url=input)+ elif type == "swe_bench_multimodal":+ return SWEBenchMultimodalProblemStatement(text=input)else:msg = f"Unknown problem statement type: {type}"raise ValueError(msg)diff --git a/sweagent/inspector/fileViewer.js b/sweagent/inspector/fileViewer.jsindex ebca3cbe..155aeddf 100644--- a/sweagent/inspector/fileViewer.js+++ b/sweagent/inspector/fileViewer.js@@ -58,6 +58,40 @@ function createTrajectoryItem(item, index) {.replace(/'/g, "'");};+ const processImagesInObservation = (observation) => {+ if (!observation) {+ return { processedText: "", images: [] };+ }++ // regex to match markdown-style base64 images: + const imageRegex = /!\[([^\]]*)\]\(data:image\/([^;]+);base64,([^)]+)\)/g;+ const images = [];+ let processedText = observation;+ let match;++ while ((match = imageRegex.exec(observation)) !== null) {+ const [fullMatch, altText, format, base64Data] = match;++ // create image object+ const imageObj = {+ altText: altText || "Image",+ format: format,+ dataUrl: `data:image/${format};base64,${base64Data}`,+ id: `img_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,+ };++ images.push(imageObj);++ // replace the full base64 string with a placeholder+ processedText = processedText.replace(+ fullMatch,+ `[IMAGE: ${imageObj.altText}]`,+ );+ }++ return { processedText, images };+ };+const getMessageContent = (msg) => {if (!msg.content) {return "";@@ -116,6 +150,30 @@ function createTrajectoryItem(item, index) {.join("\n"): "";+ // Process images in observation+ const { processedText: processedObservation, images: observationImages } =+ processImagesInObservation(item.observation);++ // Create separate image pane HTML if there are images+ const observationImagesPane =+ observationImages.length > 0+ ? `<div class="observation-images-section" data-title="Observation Images">+ <div class="content-wrapper">+ <div class="observation-images">+ ${observationImages+ .map(+ (img) =>+ `<div class="observation-image-container">+ <img src="${img.dataUrl}" alt="${escapeHtml(img.altText)}" class="observation-image" id="${img.id}">+ <div class="image-caption">${escapeHtml(img.altText)}</div>+ </div>`,+ )+ .join("")}+ </div>+ </div>+ </div>`+ : "";+return `<div class="trajectory-item fade-in" id="${elementId}"><div class="trajectory-main">@@ -130,9 +188,10 @@ ${escapeHtml(item.action)}</code></pre></div><div class="observation-section" data-title="Environment Observation"><div class="content-wrapper">- <pre><code class="language-python">${escapeHtml(item.observation)}</code></pre>+ <pre><code class="language-python">${escapeHtml(processedObservation)}</code></pre></div></div>+ ${observationImagesPane}${item.execution_time? `<div class="execution-time">Execution time: ${item.execution_time}s</div>`@@ -183,6 +242,9 @@ function viewFile(fileName) {hljs.highlightElement(block);});});++ // Initialize image click handlers after all items are added+ initializeImageHandlers();} else {container.textContent = "No trajectory content found.";}@@ -202,6 +264,64 @@ function viewFile(fileName) {});}+function initializeImageHandlers() {+ // Remove existing overlay if present+ const existingOverlay = document.querySelector(".image-overlay");+ if (existingOverlay) {+ existingOverlay.remove();+ }++ // Create overlay element+ const overlay = document.createElement("div");+ overlay.className = "image-overlay";+ document.body.appendChild(overlay);++ // Add click handlers to all observation images+ document.querySelectorAll(".observation-image").forEach((img) => {+ img.addEventListener("click", function (e) {+ e.preventDefault();+ e.stopPropagation();++ // Toggle expanded state+ if (this.classList.contains("expanded")) {+ this.classList.remove("expanded");+ overlay.classList.remove("active");+ } else {+ // Remove expanded class from all other images+ document+ .querySelectorAll(".observation-image.expanded")+ .forEach((otherImg) => {+ otherImg.classList.remove("expanded");+ });++ // Add expanded class to clicked image+ this.classList.add("expanded");+ overlay.classList.add("active");+ }+ });+ });++ // Close expanded image when clicking overlay+ overlay.addEventListener("click", function () {+ document.querySelectorAll(".observation-image.expanded").forEach((img) => {+ img.classList.remove("expanded");+ });+ overlay.classList.remove("active");+ });++ // Close expanded image when pressing Escape key+ document.addEventListener("keydown", function (e) {+ if (e.key === "Escape") {+ document+ .querySelectorAll(".observation-image.expanded")+ .forEach((img) => {+ img.classList.remove("expanded");+ });+ overlay.classList.remove("active");+ }+ });+}+function refreshCurrentFile() {if (currentFileName) {const currentScrollPosition =diff --git a/sweagent/inspector/server.py b/sweagent/inspector/server.pyindex 551359cb..76b7cca8 100644--- a/sweagent/inspector/server.py+++ b/sweagent/inspector/server.py@@ -12,6 +12,30 @@ from typing import Anyimport yaml+def add_problem_statement(content):+ """The problem statement is the first 'user' message in the history.++ We'll prepend the trajectory with the problem statement.+ """+ problem_statement = ""+ for item in content["history"]:+ if item["role"] == "user":+ problem_statement = item["content"]+ break+ if problem_statement:+ content["trajectory"].insert(+ 0,+ {+ "thought": "",+ "action": "",+ "response": "",+ "observation": problem_statement,+ "messages": [{"role": "system", "content": "Problem Statement placeholder"}],+ },+ )+ return content++def append_exit(content):exit_status = content.get("info", {}).get("exit_status", None)if exit_status is None:@@ -147,6 +171,7 @@ def load_content(file_name, gold_patches, test_patches) -> dict[str, Any]:results_file = Path(file_name).parent / "results.json"results = load_results(results_file)+ content = add_problem_statement(content)content = append_exit(content)content = append_patch(Path(file_name).stem, content, gold_patches, "Gold")content = append_patch(Path(file_name).stem, content, test_patches, "Test")diff --git a/sweagent/inspector/style.css b/sweagent/inspector/style.cssindex a5072351..7fb4b8e5 100644--- a/sweagent/inspector/style.css+++ b/sweagent/inspector/style.css@@ -226,9 +226,26 @@ h2 {color: #d4d4d4;}+.observation-images-section {+ padding: 4px;+ position: relative;+ min-height: 30px;+ height: 200px;+ max-height: 200px;+ background: #2d2d30;+ border-top: 1px solid #454545;+ display: flex;+ flex-direction: column;+ resize: vertical;+ overflow: hidden;+ width: calc(100% - 16px);+ color: #d4d4d4;+}+/* Add section headers */.response-section::before,.observation-section::before,+.observation-images-section::before,.messages-section::before {content: attr(data-title);font-weight: bold;@@ -312,6 +329,7 @@ h2 {/* Add a visual indicator for resizable areas */.response-section:hover,.observation-section:hover,+.observation-images-section:hover,.messages-section.expanded:hover {outline: 1px dashed #999;}@@ -373,3 +391,64 @@ input[type="checkbox"] {margin: 0;cursor: pointer;}++/* observation images styles */+.observation-images {+ margin-top: 10px;+ padding: 10px 0;+}++.observation-image-container {+ margin-bottom: 15px;+ text-align: center;+}++.observation-image {+ max-width: 100%;+ max-height: 400px;+ border: 1px solid #454545;+ border-radius: 5px;+ background-color: #1e1e1e;+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);+ cursor: pointer;+ transition: transform 0.2s ease;+}++.observation-image:hover {+ transform: scale(1.02);+ border-color: #1697e2;+}++.image-caption {+ margin-top: 5px;+ font-size: 0.9em;+ color: #b3b3b3;+ font-style: italic;+}++.observation-image.expanded {+ position: fixed;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%) scale(1);+ max-width: 90vw;+ max-height: 90vh;+ z-index: 1000;+ border: 2px solid #1697e2;+ box-shadow: 0 0 20px rgba(0, 0, 0, 0.8);+}++.image-overlay {+ position: fixed;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ background-color: rgba(0, 0, 0, 0.8);+ z-index: 999;+ display: none;+}++.image-overlay.active {+ display: block;+}diff --git a/sweagent/run/batch_instances.py b/sweagent/run/batch_instances.pyindex 1aa4a5c1..a46d4b04 100644--- a/sweagent/run/batch_instances.py+++ b/sweagent/run/batch_instances.py@@ -1,3 +1,4 @@+import jsonimport randomimport refrom abc import ABC, abstractmethod@@ -13,7 +14,11 @@ from swerex.deployment.config import ()from typing_extensions import Self-from sweagent.agent.problem_statement import ProblemStatementConfig, TextProblemStatement+from sweagent.agent.problem_statement import (+ ProblemStatementConfig,+ SWEBenchMultimodalProblemStatement,+ TextProblemStatement,+)from sweagent.environment.repo import GithubRepoConfig, LocalRepoConfig, PreExistingRepoConfigfrom sweagent.environment.swe_env import EnvironmentConfigfrom sweagent.utils.files import load_file@@ -108,9 +113,19 @@ class SimpleBatchInstance(BaseModel):"""Merge the deployment options into the `SimpleBatchInstance` object to get a full `BatchInstance`."""# Very important: Make a copy of the deployment config because it will be shared among instances!!!deployment = deployment.model_copy(deep=True)- problem_statement = TextProblemStatement(- text=self.problem_statement, id=self.instance_id, extra_fields=self.extra_fields- )++ if "issue_images" in self.extra_fields:+ problem_statement = SWEBenchMultimodalProblemStatement(+ text=self.problem_statement,+ issue_images=self.extra_fields.pop("issue_images"),+ id=self.instance_id,+ extra_fields=self.extra_fields,+ )+ else:+ problem_statement = TextProblemStatement(+ text=self.problem_statement, id=self.instance_id, extra_fields=self.extra_fields+ )+if not self.repo_name:repo = Noneelif "github" in self.repo_name:@@ -161,12 +176,17 @@ class SimpleBatchInstance(BaseModel):# Docker doesn't allow double underscore, so we replace them with a magic tokenid_docker_compatible = iid.replace("__", "_1776_")image_name = f"swebench/sweb.eval.x86_64.{id_docker_compatible}:latest".lower()+ extra_fields = {}+ if "image_assets" in instance:+ issue_images = json.loads(instance["image_assets"])["problem_statement"]+ extra_fields["issue_images"] = issue_imagesreturn cls(image_name=image_name,problem_statement=instance["problem_statement"],instance_id=iid,repo_name="testbed",base_commit=instance["base_commit"],+ extra_fields=extra_fields,)diff --git a/tests/test_problem_statement_multimodal.py b/tests/test_problem_statement_multimodal.pynew file mode 100644index 00000000..76043042--- /dev/null+++ b/tests/test_problem_statement_multimodal.py@@ -0,0 +1,111 @@+from unittest.mock import Mock, patch++import requests++from sweagent.agent.problem_statement import SWEBenchMultimodalProblemStatement+++class TestSWEBenchMultimodalProblemStatement:+ example_image_url = (+ "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Candide1759.jpg/330px-Candide1759.jpg"+ )++ def test_initialization(self):+ """Test basic initialization of multimodal problem statement."""+ problem_statement = SWEBenchMultimodalProblemStatement(+ text="Test problem statement", issue_images=[self.example_image_url], id="test_id"+ )+ assert problem_statement.text == "Test problem statement"+ assert problem_statement.issue_images == [self.example_image_url]+ assert problem_statement.id == "test_id"+ assert problem_statement.type == "swe_bench_multimodal"++ def test_get_problem_statement_no_images(self):+ """Test get_problem_statement when no images are present."""+ problem_statement = SWEBenchMultimodalProblemStatement(text="Test problem statement", issue_images=[])+ result = problem_statement.get_problem_statement()+ assert result == "Test problem statement"++ @patch("requests.get")+ def test_get_problem_statement_with_valid_image(self, mock_get):+ """Test get_problem_statement with a valid image that gets processed."""+ # mock successful HTTP response+ mock_response = Mock()+ mock_response.raise_for_status.return_value = None+ mock_response.headers = {"content-type": "image/png"}+ mock_response.iter_content.return_value = [b"fake_image_data"]+ mock_get.return_value = mock_response+ problem_statement = SWEBenchMultimodalProblemStatement(+ text="Test problem statement", issue_images=[self.example_image_url]+ )+ result = problem_statement.get_problem_statement()+ # should contain original text plus the base64 image+ assert "Test problem statement" in result+ assert f"+ def test_get_problem_statement_with_network_error(self, mock_get):+ """Test that network errors are handled gracefully with warnings."""+ # mock network error+ mock_get.side_effect = requests.exceptions.RequestException("Network error")+ problem_statement = SWEBenchMultimodalProblemStatement(+ text="Test problem statement", issue_images=[self.example_image_url]+ )+ result = problem_statement.get_problem_statement()+ assert result == "Test problem statement"++ @patch("requests.get")+ def test_get_problem_statement_with_invalid_mime_type(self, mock_get):+ """Test that invalid MIME types are handled gracefully."""+ # mock response with invalid MIME type+ mock_response = Mock()+ mock_response.raise_for_status.return_value = None+ mock_response.headers = {"content-type": "text/html"}+ mock_get.return_value = mock_response+ problem_statement = SWEBenchMultimodalProblemStatement(+ text="Test problem statement", issue_images=["http://example.com/document.html"]+ )+ result = problem_statement.get_problem_statement()+ assert result == "Test problem statement"++ @patch("requests.get")+ def test_caching_behavior(self, mock_get):+ """Test that get_problem_statement caches results and doesn't re-download images."""+ mock_response = Mock()+ mock_response.raise_for_status.return_value = None+ mock_response.headers = {"content-type": "image/png"}+ mock_response.iter_content.return_value = [b"fake_image_data"]+ mock_get.return_value = mock_response+ problem_statement = SWEBenchMultimodalProblemStatement(+ text="Test problem statement", issue_images=[self.example_image_url]+ )+ result1 = problem_statement.get_problem_statement()+ assert mock_get.call_count == 1+ result2 = problem_statement.get_problem_statement()+ assert mock_get.call_count == 1 # should still be 1, not 2, because of caching+ assert result1 == result2+ assert "Test problem statement" in result1+ assert f":+ """Test that invalid URLs are handled gracefully."""+ problem_statement = SWEBenchMultimodalProblemStatement(+ text="Test problem statement", issue_images=["not_a_url", "ftp://invalid_scheme.com/image.png"]+ )+ result = problem_statement.get_problem_statement()+ assert result == "Test problem statement"++ @patch("requests.get")+ def test_large_image_handling(self, mock_get):+ """Test that large images are rejected."""+ mock_response = Mock()+ mock_response.raise_for_status.return_value = None+ mock_response.headers = {"content-type": "image/png", "content-length": "20971520"} # 20MB+ mock_get.return_value = mock_response++ problem_statement = SWEBenchMultimodalProblemStatement(+ text="Test problem statement", issue_images=["http://example.com/huge_image.png"]+ )++ result = problem_statement.get_problem_statement()+ assert result == "Test problem statement"diff --git a/tools/image_tools/bin/view_image b/tools/image_tools/bin/view_imagenew file mode 100755index 00000000..b9abfa2b--- /dev/null+++ b/tools/image_tools/bin/view_image@@ -0,0 +1,36 @@+#!/usr/bin/env python3+# view_image – view an image file as a base64-encoded markdown image+import base64+import mimetypes+import pathlib+import sys++VALID_MIME_TYPES = {+ "image/png",+ "image/jpeg",+ "image/webp",+}++if len(sys.argv) != 2:+ sys.exit(f"usage: {pathlib.Path(sys.argv[0]).name} <image-file>")++img_path = pathlib.Path(sys.argv[1])++if not img_path.exists():+ sys.exit(f"Error: File '{img_path}' does not exist")++if not img_path.is_file():+ sys.exit(f"Error: '{img_path}' is not a file")++try:+ mime = mimetypes.guess_type(img_path.name)[0]+ if mime not in VALID_MIME_TYPES:+ sys.exit(f"Error: Unsupported image type: {mime}. Valid types are: {', '.join(VALID_MIME_TYPES)}")++ # read the file, base64-encode, and convert bytes → str+ b64 = base64.b64encode(img_path.read_bytes()).decode("ascii")++ # write the exact markdown snippet to stdout+ print(f"")+except Exception as e:+ sys.exit(f"Error processing image: {e}")diff --git a/tools/image_tools/config.yaml b/tools/image_tools/config.yamlnew file mode 100644index 00000000..b262f0bf--- /dev/null+++ b/tools/image_tools/config.yaml@@ -0,0 +1,9 @@+tools:+ view_image:+ signature: "view_image <image_file>"+ docstring: "view an image file"+ arguments:+ - name: image_file+ type: string+ description: "the path to the image file to view"+ required: true\ No newline at end of filediff --git a/tools/web_browser/bin/click_mouse b/tools/web_browser/bin/click_mousenew file mode 100755index 00000000..6733c54d--- /dev/null+++ b/tools/web_browser/bin/click_mouse@@ -0,0 +1,41 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _autosave_screenshot_from_response,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def click(x, y, button):+ """Click at the specified coordinates (x, y)."""+ response = send_request(+ config.port,+ "click",+ "POST",+ {"x": x, "y": y, "button": button, "return_screenshot": config.autoscreenshot},+ )+ if response is None:+ return+ _print_response_with_metadata(response)+ _autosave_screenshot_from_response(response, config.screenshot_mode)+++if __name__ == "__main__":+ parser = ArgumentParser()+ parser.add_argument("x", type=int)+ parser.add_argument("y", type=int)+ parser.add_argument("button", nargs="?", default="left", choices=["left", "right"])+ args = parser.parse_args()+ click(args.x, args.y, args.button)diff --git a/tools/web_browser/bin/close_site b/tools/web_browser/bin/close_sitenew file mode 100755index 00000000..e9deebf6--- /dev/null+++ b/tools/web_browser/bin/close_site@@ -0,0 +1,28 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import _print_response_with_metadata, send_request++config = ClientConfig()+++def close():+ """Close the currently open window."""+ response = send_request(config.port, "close", "POST")+ if response is None:+ return+ _print_response_with_metadata(response)+++if __name__ == "__main__":+ parser = ArgumentParser()+ args = parser.parse_args()+ close()diff --git a/tools/web_browser/bin/double_click_mouse b/tools/web_browser/bin/double_click_mousenew file mode 100755index 00000000..0be03374--- /dev/null+++ b/tools/web_browser/bin/double_click_mouse@@ -0,0 +1,37 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _autosave_screenshot_from_response,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def double_click(x, y):+ """Double-click at the specified coordinates (x, y)."""+ response = send_request(+ config.port, "double_click", "POST", {"x": x, "y": y, "return_screenshot": config.autoscreenshot}+ )+ if response is None:+ return+ _print_response_with_metadata(response)+ _autosave_screenshot_from_response(response, config.screenshot_mode)+++if __name__ == "__main__":+ parser = ArgumentParser()+ parser.add_argument("x", type=int)+ parser.add_argument("y", type=int)+ args = parser.parse_args()+ double_click(args.x, args.y)diff --git a/tools/web_browser/bin/drag_mouse b/tools/web_browser/bin/drag_mousenew file mode 100755index 00000000..08f8e283--- /dev/null+++ b/tools/web_browser/bin/drag_mouse@@ -0,0 +1,46 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _autosave_screenshot_from_response,+ _print_error,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def drag(path):+ """Drag mouse along a path. Path should be a JSON list of x, y lists: '[[0, 0], [100, 100]]'."""+ import json++ try:+ path_data = json.loads(path)+ except json.JSONDecodeError:+ _print_error("Path must be valid JSON")+ return+ response = send_request(+ config.port, "drag", "POST", {"path": path_data, "return_screenshot": config.autoscreenshot}+ )+ if response is None:+ return+ _print_response_with_metadata(response)+ _autosave_screenshot_from_response(response, config.screenshot_mode)+++if __name__ == "__main__":+ parser = ArgumentParser()+ parser.add_argument(+ "path", type=str, help="The path to drag the mouse along (JSON list of x, y lists) e.g. '[[0, 0], [100, 100]]'"+ )+ args = parser.parse_args()+ drag(args.path)diff --git a/tools/web_browser/bin/execute_script_on_page b/tools/web_browser/bin/execute_script_on_pagenew file mode 100755index 00000000..aa24cff4--- /dev/null+++ b/tools/web_browser/bin/execute_script_on_page@@ -0,0 +1,39 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _autosave_screenshot_from_response,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def execute_script(script):+ """Execute a custom JavaScript code snippet on the current page."""+ response = send_request(+ config.port,+ "execute_script",+ "POST",+ {"script": script, "return_screenshot": config.autoscreenshot},+ )+ if response is None:+ return+ _print_response_with_metadata(response)+ _autosave_screenshot_from_response(response, config.screenshot_mode)+++if __name__ == "__main__":+ parser = ArgumentParser()+ parser.add_argument("script", type=str, help="The JavaScript code snippet to execute")+ args = parser.parse_args()+ execute_script(args.script)diff --git a/tools/web_browser/bin/get_console_output b/tools/web_browser/bin/get_console_outputnew file mode 100755index 00000000..e754a139--- /dev/null+++ b/tools/web_browser/bin/get_console_output@@ -0,0 +1,48 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def get_console_output():+ """Get console output from the browser."""+ response = send_request(config.port, "console", "GET", {})+ if response is None:+ return+ _print_response_with_metadata(response)+ if "console_messages" in response:+ console_messages = response["console_messages"]+ if console_messages:+ print("\n--- Console Messages ---")+ for ix, msg in enumerate(console_messages):+ # timestamp = msg.get("timestamp", 0)+ msg_type = msg.get("type", "log")+ text = msg.get("text", "")+ location = msg.get("location", {})+ print(f"[{ix + 1}] {msg_type.upper()}: {text}")+ if location:+ url = location.get("url", "")+ line_number = location.get("lineNumber", "")+ column_number = location.get("columnNumber", "")+ if url:+ print(f" Location: {url}:{line_number}:{column_number}")+ print("Console buffer cleared.")+++if __name__ == "__main__":+ parser = ArgumentParser()+ args = parser.parse_args()+ get_console_output()diff --git a/tools/web_browser/bin/move_mouse b/tools/web_browser/bin/move_mousenew file mode 100755index 00000000..47f88ea4--- /dev/null+++ b/tools/web_browser/bin/move_mouse@@ -0,0 +1,35 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _autosave_screenshot_from_response,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def move(x, y):+ """Move mouse to the specified coordinates (x, y)."""+ response = send_request(config.port, "move", "POST", {"x": x, "y": y, "return_screenshot": config.autoscreenshot})+ if response is None:+ return+ _print_response_with_metadata(response)+ _autosave_screenshot_from_response(response, config.screenshot_mode)+++if __name__ == "__main__":+ parser = ArgumentParser()+ parser.add_argument("x", type=int)+ parser.add_argument("y", type=int)+ args = parser.parse_args()+ move(args.x, args.y)diff --git a/tools/web_browser/bin/navigate_back b/tools/web_browser/bin/navigate_backnew file mode 100755index 00000000..a9ddb2b2--- /dev/null+++ b/tools/web_browser/bin/navigate_back@@ -0,0 +1,33 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _autosave_screenshot_from_response,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def back():+ """Navigate back in the browser history."""+ response = send_request(config.port, "back", "POST", {"return_screenshot": config.autoscreenshot})+ if response is None:+ return+ _print_response_with_metadata(response)+ _autosave_screenshot_from_response(response, config.screenshot_mode)+++if __name__ == "__main__":+ parser = ArgumentParser()+ args = parser.parse_args()+ back()diff --git a/tools/web_browser/bin/navigate_forward b/tools/web_browser/bin/navigate_forwardnew file mode 100755index 00000000..4483782d--- /dev/null+++ b/tools/web_browser/bin/navigate_forward@@ -0,0 +1,33 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _autosave_screenshot_from_response,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def forward():+ """Navigate forward in the browser history."""+ response = send_request(config.port, "forward", "POST", {"return_screenshot": config.autoscreenshot})+ if response is None:+ return+ _print_response_with_metadata(response)+ _autosave_screenshot_from_response(response, config.screenshot_mode)+++if __name__ == "__main__":+ parser = ArgumentParser()+ args = parser.parse_args()+ forward()diff --git a/tools/web_browser/bin/open_site b/tools/web_browser/bin/open_sitenew file mode 100755index 00000000..c59d58bf--- /dev/null+++ b/tools/web_browser/bin/open_site@@ -0,0 +1,36 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _autosave_screenshot_from_response,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def open(url):+ """Open the specified website URL."""+ if Path(url).is_file():+ url = f"file://{Path(url).resolve()}"+ response = send_request(config.port, "goto", "POST", {"url": url, "return_screenshot": config.autoscreenshot})+ if response is None:+ return+ _print_response_with_metadata(response)+ _autosave_screenshot_from_response(response, config.screenshot_mode)+++if __name__ == "__main__":+ parser = ArgumentParser()+ parser.add_argument("url", type=str, help="The URL of the website to open")+ args = parser.parse_args()+ open(args.url)diff --git a/tools/web_browser/bin/press_keys_on_page b/tools/web_browser/bin/press_keys_on_pagenew file mode 100755index 00000000..0de03749--- /dev/null+++ b/tools/web_browser/bin/press_keys_on_page@@ -0,0 +1,51 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _autosave_screenshot_from_response,+ _print_error,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def keypress(keys):+ """Press the specified keys. Keys should be a JSON string like '["ctrl", "c"]'."""+ import json++ try:+ keys_data = json.loads(keys)+ except json.JSONDecodeError:+ _print_error("Keys must be valid JSON")+ return+ response = send_request(+ config.port,+ "keypress",+ "POST",+ {"keys": keys_data, "return_screenshot": config.autoscreenshot},+ )+ if response is None:+ return+ _print_response_with_metadata(response)+ _autosave_screenshot_from_response(response, config.screenshot_mode)+++if __name__ == "__main__":+ parser = ArgumentParser()+ parser.add_argument(+ "keys",+ type=str,+ help='The keys to press (JSON string like \'["ctrl", "c"]\')',+ )+ args = parser.parse_args()+ keypress(args.keys)diff --git a/tools/web_browser/bin/reload_page b/tools/web_browser/bin/reload_pagenew file mode 100755index 00000000..8d695604--- /dev/null+++ b/tools/web_browser/bin/reload_page@@ -0,0 +1,33 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _autosave_screenshot_from_response,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def reload():+ """Reload the current webpage."""+ response = send_request(config.port, "reload", "POST", {"return_screenshot": config.autoscreenshot})+ if response is None:+ return+ _print_response_with_metadata(response)+ _autosave_screenshot_from_response(response, config.screenshot_mode)+++if __name__ == "__main__":+ parser = ArgumentParser()+ args = parser.parse_args()+ reload()diff --git a/tools/web_browser/bin/run_web_browser_server b/tools/web_browser/bin/run_web_browser_servernew file mode 100755index 00000000..e3fa9506--- /dev/null+++ b/tools/web_browser/bin/run_web_browser_server@@ -0,0 +1,394 @@+#!/root/python3.11/bin/python3+"""Web Browser server ‒ Flask + Playwright backend."""++from __future__ import annotations++import atexit+import functools+import signal+import sys+import time+from pathlib import Path+from typing import Any++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from browser_manager import BrowserManager+from flask import Flask, Response, jsonify, request+from web_browser_config import ServerConfig+from web_browser_utils import catch_error, normalize_url, validate_request++config = ServerConfig()+++browser_manager = BrowserManager()+++def cleanup_on_exit():+ """Cleanup function for atexit and signal handlers."""+ browser_manager.cleanup()+++def signal_handler(signum, frame):+ """Handle shutdown signals."""+ print(f"\nReceived signal {signum}, shutting down...")+ cleanup_on_exit()+ sys.exit(0)+++# register cleanup handlers+atexit.register(cleanup_on_exit)+signal.signal(signal.SIGINT, signal_handler)+signal.signal(signal.SIGTERM, signal_handler)+++app = Flask(__name__)+++def require_website_open(func):+ """Decorator to ensure a website is open before executing the route."""++ @functools.wraps(func)+ def wrapper(*args, **kwargs):+ if not browser_manager.is_website_open():+ return create_response({"status": "error", "message": "Please open a website first."}, False)+ return func(*args, **kwargs)++ return wrapper+++def _get_response_metadata() -> dict[str, Any]:+ """Gather comprehensive metadata for API responses."""+ metadata = {}+ if browser_manager.is_website_open():+ metadata["Browser Type"] = browser_manager.browser_name+ metadata["Mouse Position"] = f"({browser_manager.mouse_x},{browser_manager.mouse_y})"+ metadata["Viewport Size"] = f"{browser_manager.window_width}×{browser_manager.window_height}"+ with browser_manager._browser_lock() as page:+ metadata["Current URL"] = page.url+ metadata["Page Title"] = page.title()++ scroll_info = page.evaluate("""() => ({+ scroll_position: { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop },+ page_dimensions: { width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight },+ visible_dimensions: { width: window.innerWidth, height: window.innerHeight }+ })""")+ scroll_pos = scroll_info["scroll_position"]+ page_dims = scroll_info["page_dimensions"]+ visible_dims = scroll_info["visible_dimensions"]+ metadata["Scroll Position"] = f"({scroll_pos['x']},{scroll_pos['y']})"+ metadata["Page Dimensions"] = f"{page_dims['width']}×{page_dims['height']}"+ metadata["Visible Dimensions"] = f"{visible_dims['width']}×{visible_dims['height']}"+ return metadata+++def create_response(data: dict[str, Any], return_screenshot: bool) -> Response:+ """Create a JSON response with comprehensive metadata and optional screenshot."""+ response_data = {**data}+ if return_screenshot:+ response_data.update(browser_manager.take_screenshot())+ if "metadata" not in response_data:+ response_data["metadata"] = {}+ response_data["metadata"].update(_get_response_metadata())+ return jsonify(response_data)++[email protected]("/info", methods=["GET"])+@catch_error+def info():+ if not browser_manager.is_website_open():+ return create_response({"status": "success", "message": "No page open"}, False)+ data = {+ "status": "success",+ "message": "Loaded info for current page",+ }+ return create_response(data, False)++[email protected]("/close", methods=["POST"])+@catch_error+def close_browser():+ browser_manager.cleanup()+ browser_manager._init_browser()+ return create_response({"status": "success", "message": "Closed browser"}, False)++[email protected]("/set_window_size", methods=["POST"])+@validate_request("width", "height", "return_screenshot")+@require_website_open+@catch_error+def set_window_size():+ width, height = request.json["width"], request.json["height"]+ return_screenshot = request.json["return_screenshot"]+ if width <= 0 or height <= 0:+ return create_response(+ {"status": "error", "message": f"Invalid dimensions ({width},{height}). Must be positive"}, False+ )+ with browser_manager._browser_lock() as page:+ page.set_viewport_size({"width": width, "height": height})+ browser_manager.window_width = width+ browser_manager.window_height = height+ browser_manager.constrain_mouse_position(page)+ data = {"status": "success", "message": f"Set viewport to {width}×{height}"}+ return create_response(data, return_screenshot)++[email protected]("/screenshot", methods=["GET"])+@require_website_open+def screenshot():+ data = {"status": "success", "message": "Screenshot"}+ return create_response(data, True)++[email protected]("/click", methods=["POST"])+@validate_request("x", "y", "button", "return_screenshot")+@catch_error+@require_website_open+def click():+ x, y = round(request.json["x"]), round(request.json["y"])+ button = request.json["button"]+ return_screenshot = request.json["return_screenshot"]+ x_valid, y_valid = browser_manager.validate_coordinates(x, y)+ if not x_valid or not y_valid:+ return create_response(+ {+ "status": "error",+ "message": f"Invalid coordinates ({x},{y}). Must be within {browser_manager.window_width}x{browser_manager.window_height}",+ },+ False,+ )+ with browser_manager._browser_lock() as page:+ page.mouse.click(x, y, button=button)+ browser_manager.mouse_x, browser_manager.mouse_y = x, y+ data = {"status": "success", "message": f"Clicked '{button}' at ({x},{y})"}+ return create_response(data, return_screenshot)++[email protected]("/double_click", methods=["POST"])+@validate_request("x", "y", "return_screenshot")+@catch_error+@require_website_open+def double_click():+ x, y = round(request.json["x"]), round(request.json["y"])+ return_screenshot = request.json["return_screenshot"]+ x_valid, y_valid = browser_manager.validate_coordinates(x, y)+ if not x_valid or not y_valid:+ return create_response(+ {+ "status": "error",+ "message": f"Invalid coordinates ({x},{y}). Must be within {browser_manager.window_width}x{browser_manager.window_height}",+ },+ False,+ )+ with browser_manager._browser_lock() as page:+ page.mouse.dblclick(x, y)+ browser_manager.mouse_x, browser_manager.mouse_y = x, y+ data = {"status": "success", "message": f"Double‑clicked at ({x},{y})"}+ return create_response(data, return_screenshot)++[email protected]("/move", methods=["POST"])+@validate_request("x", "y", "return_screenshot")+@catch_error+@require_website_open+def move():+ x, y = request.json["x"], request.json["y"]+ return_screenshot = request.json["return_screenshot"]+ x_valid, y_valid = browser_manager.validate_coordinates(x, y)+ if not x_valid or not y_valid:+ return create_response(+ {+ "status": "error",+ "message": f"Invalid coordinates ({x},{y}). Must be within {browser_manager.window_width}x{browser_manager.window_height}",+ },+ False,+ )+ with browser_manager._browser_lock() as page:+ page.mouse.move(x, y)+ browser_manager.mouse_x, browser_manager.mouse_y = x, y+ data = {"status": "success", "message": f"Moved mouse to ({x},{y})"}+ return create_response(data, return_screenshot)++[email protected]("/drag", methods=["POST"])+@validate_request("path", "return_screenshot")+@catch_error+@require_website_open+def drag():+ path: list[list[int]] = request.json["path"]+ return_screenshot = request.json["return_screenshot"]+ if not path or len(path) < 2:+ return create_response({"status": "error", "message": "Path needs at least two points"}, False)+ for ix, point in enumerate(path):+ if len(point) != 2:+ return create_response(+ {"status": "error", "message": f"Path point {ix} must have exactly 2 coordinates"}, False+ )+ x, y = point+ x_valid, y_valid = browser_manager.validate_coordinates(x, y)+ if not x_valid or not y_valid:+ return create_response(+ {+ "status": "error",+ "message": f"Invalid coordinates ({x},{y}) at path point {ix}. Must be within {browser_manager.window_width}x{browser_manager.window_height}",+ },+ False,+ )++ with browser_manager._browser_lock() as page:+ page.mouse.move(*path[0])+ page.mouse.down()+ for x, y in path[1:]:+ page.mouse.move(x, y)+ page.mouse.up()+ browser_manager.mouse_x, browser_manager.mouse_y = path[-1]+ data = {"status": "success", "message": "Dragged the mouse along the path"}+ return create_response(data, return_screenshot)++[email protected]("/type", methods=["POST"])+@validate_request("text", "return_screenshot")+@catch_error+@require_website_open+def type_():+ text = request.json["text"]+ return_screenshot = request.json["return_screenshot"]+ with browser_manager._browser_lock() as page:+ page.keyboard.type(text)+ data = {"status": "success", "message": f"Typed '{text}'"}+ return create_response(data, return_screenshot)++[email protected]("/scroll", methods=["POST"])+@validate_request("scroll_x", "scroll_y", "return_screenshot")+@catch_error+@require_website_open+def scroll():+ delta_x, delta_y = request.json["scroll_x"], request.json["scroll_y"]+ return_screenshot = request.json["return_screenshot"]+ with browser_manager._browser_lock() as page:+ page.mouse.wheel(delta_x, delta_y)+ data = {"status": "success", "message": f"Scrolled by ({delta_x},{delta_y})"}+ return create_response(data, return_screenshot)++[email protected]("/execute_script", methods=["POST"])+@validate_request("script", "return_screenshot")+@catch_error+@require_website_open+def exec_script():+ script = request.json["script"]+ return_screenshot = request.json["return_screenshot"]+ with browser_manager._browser_lock() as page:+ result = page.evaluate(script)+ data = {"status": "success", "message": (f"Script executed.\n<script_result>\n{result}\n</script_result>")}+ return create_response(data, return_screenshot)++[email protected]("/back", methods=["POST"])+@validate_request("return_screenshot")+@catch_error+@require_website_open+def back():+ return_screenshot = request.json["return_screenshot"]+ with browser_manager._browser_lock() as page:+ page.go_back()+ data = {"status": "success", "message": "Navigated back"}+ return create_response(data, return_screenshot)++[email protected]("/forward", methods=["POST"])+@validate_request("return_screenshot")+@catch_error+@require_website_open+def forward():+ return_screenshot = request.json["return_screenshot"]+ with browser_manager._browser_lock() as page:+ page.go_forward()+ data = {"status": "success", "message": "Navigated forward"}+ return create_response(data, return_screenshot)++[email protected]("/reload", methods=["POST"])+@validate_request("return_screenshot")+@catch_error+@require_website_open+def reload():+ return_screenshot = request.json["return_screenshot"]+ with browser_manager._browser_lock() as page:+ page.reload()+ data = {"status": "success", "message": "Reloaded the page"}+ return create_response(data, return_screenshot)++[email protected]("/wait", methods=["POST"])+@validate_request("ms", "return_screenshot")+@catch_error+@require_website_open+def wait():+ milliseconds = request.json["ms"]+ return_screenshot = request.json["return_screenshot"]+ time.sleep(milliseconds / 1000.0)+ data = {"status": "success", "message": f"Waited {milliseconds} ms"}+ return create_response(data, return_screenshot)++[email protected]("/keypress", methods=["POST"])+@validate_request("keys", "return_screenshot")+@catch_error+@require_website_open+def keypress():+ keys: list[str] = request.json["keys"]+ return_screenshot = request.json["return_screenshot"]+ if not isinstance(keys, list):+ return create_response({"status": "error", "message": "Keys must be a list"}, False)+ if not keys:+ return create_response({"status": "error", "message": "Keys list empty"}, False)+ with browser_manager._browser_lock() as _:+ for key in keys[:-1]:+ browser_manager.key_down(key)+ browser_manager.key_press(keys[-1])+ for key in reversed(keys[:-1]):+ browser_manager.key_up(key)+ data = {"status": "success", "message": f"Pressed keys {keys}"}+ return create_response(data, return_screenshot)++[email protected]("/goto", methods=["POST"])+@validate_request("url", "return_screenshot")+@catch_error+def goto():+ url = normalize_url(request.json["url"])+ return_screenshot = request.json["return_screenshot"]+ with browser_manager._browser_lock() as page:+ page.goto(url, wait_until="load")+ data = {"status": "success", "message": f"Navigated to {url}"}+ return create_response(data, return_screenshot)++[email protected]("/console", methods=["GET"])+@catch_error+@require_website_open+def get_console():+ console_messages = browser_manager.get_console_output()+ data = {+ "status": "success",+ "message": f"Retrieved {len(console_messages)} console messages",+ "console_messages": console_messages,+ }+ return create_response(data, False)+++def main():+ """Run the Flask server with proper cleanup handling."""+ try:+ app.run(host="0.0.0.0", port=config.port, threaded=False, use_reloader=False)+ except KeyboardInterrupt:+ print("\nShutting down gracefully...")+ finally:+ cleanup_on_exit()+++if __name__ == "__main__":+ main()diff --git a/tools/web_browser/bin/screenshot_site b/tools/web_browser/bin/screenshot_sitenew file mode 100755index 00000000..df5ea3b6--- /dev/null+++ b/tools/web_browser/bin/screenshot_site@@ -0,0 +1,38 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ ScreenshotMode,+ _handle_screenshot,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def screenshot():+ """Capture a screenshot and handle it according to the default config.screenshot_mode."""+ response = send_request(config.port, "screenshot", "GET")+ if response is None:+ return+ screenshot_data = response["screenshot"]+ _print_response_with_metadata(response)+ if config.screenshot_mode == ScreenshotMode.SAVE:+ _handle_screenshot(screenshot_data, ScreenshotMode.SAVE)+ else:+ _handle_screenshot(screenshot_data, ScreenshotMode.PRINT)+++if __name__ == "__main__":+ parser = ArgumentParser()+ args = parser.parse_args()+ screenshot()diff --git a/tools/web_browser/bin/scroll_on_page b/tools/web_browser/bin/scroll_on_pagenew file mode 100755index 00000000..407e2ec1--- /dev/null+++ b/tools/web_browser/bin/scroll_on_page@@ -0,0 +1,40 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _autosave_screenshot_from_response,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def scroll(scroll_x, scroll_y):+ """Scroll by (scroll_x, scroll_y) pixels at current mouse position."""+ response = send_request(+ config.port,+ "scroll",+ "POST",+ {"scroll_x": scroll_x, "scroll_y": scroll_y, "return_screenshot": config.autoscreenshot},+ )+ if response is None:+ return+ _print_response_with_metadata(response)+ _autosave_screenshot_from_response(response, config.screenshot_mode)+++if __name__ == "__main__":+ parser = ArgumentParser()+ parser.add_argument("scroll_x", type=int, help="The number of pixels to scroll horizontally")+ parser.add_argument("scroll_y", type=int, help="The number of pixels to scroll vertically")+ args = parser.parse_args()+ scroll(args.scroll_x, args.scroll_y)diff --git a/tools/web_browser/bin/set_browser_window_size b/tools/web_browser/bin/set_browser_window_sizenew file mode 100755index 00000000..88fc6468--- /dev/null+++ b/tools/web_browser/bin/set_browser_window_size@@ -0,0 +1,40 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _autosave_screenshot_from_response,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def set_window_size(width, height):+ """Set the browser window size to the specified width and height."""+ response = send_request(+ config.port,+ "set_window_size",+ "POST",+ {"width": width, "height": height, "return_screenshot": config.autoscreenshot},+ )+ if response is None:+ return+ _print_response_with_metadata(response)+ _autosave_screenshot_from_response(response, config.screenshot_mode)+++if __name__ == "__main__":+ parser = ArgumentParser()+ parser.add_argument("width", type=int, help="The new width of the browser window")+ parser.add_argument("height", type=int, help="The new height of the browser window")+ args = parser.parse_args()+ set_window_size(args.width, args.height)diff --git a/tools/web_browser/bin/type_text b/tools/web_browser/bin/type_textnew file mode 100755index 00000000..67ada96d--- /dev/null+++ b/tools/web_browser/bin/type_text@@ -0,0 +1,34 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _autosave_screenshot_from_response,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def type(text):+ """Type the given text at the current cursor position."""+ response = send_request(config.port, "type", "POST", {"text": text, "return_screenshot": config.autoscreenshot})+ if response is None:+ return+ _print_response_with_metadata(response)+ _autosave_screenshot_from_response(response, config.screenshot_mode)+++if __name__ == "__main__":+ parser = ArgumentParser()+ parser.add_argument("text", type=str, help="The text to type at the currently focused element")+ args = parser.parse_args()+ type(args.text)diff --git a/tools/web_browser/bin/wait_time b/tools/web_browser/bin/wait_timenew file mode 100755index 00000000..87e8fce1--- /dev/null+++ b/tools/web_browser/bin/wait_time@@ -0,0 +1,39 @@+#!/root/python3.11/bin/python3+from __future__ import annotations++import sys+from argparse import ArgumentParser+from pathlib import Path++lib_path = str(Path(__file__).resolve().parent.parent / "lib")+sys.path.insert(0, lib_path)++from web_browser_config import ClientConfig+from web_browser_utils import (+ _autosave_screenshot_from_response,+ _print_response_with_metadata,+ send_request,+)++config = ClientConfig()+++def wait(ms):+ """Wait for the specified number of milliseconds."""+ response = send_request(+ config.port,+ "wait",+ "POST",+ {"ms": ms, "return_screenshot": config.autoscreenshot},+ )+ if response is None:+ return+ _print_response_with_metadata(response)+ _autosave_screenshot_from_response(response, config.screenshot_mode)+++if __name__ == "__main__":+ parser = ArgumentParser()+ parser.add_argument("ms", type=int, help="The number of milliseconds to wait")+ args = parser.parse_args()+ wait(args.ms)diff --git a/tools/web_browser/config.yaml b/tools/web_browser/config.yamlnew file mode 100644index 00000000..e250404d--- /dev/null+++ b/tools/web_browser/config.yaml@@ -0,0 +1,155 @@+tools:+ open_site:+ signature: "open_site <url>"+ docstring: "Open the specified website URL or local file path"+ arguments:+ - name: url+ type: string+ description: "The URL to open (can be a web URL or file path)"+ required: true++ close_site:+ signature: "close_site"+ docstring: "Close the currently open browser window"+ arguments: []++ screenshot_site:+ signature: "screenshot_site"+ docstring: "Take a screenshot of the current page"+ arguments: []++ click_mouse:+ signature: "click_mouse <x> <y> [<button>]"+ docstring: "Click at the specified coordinates (shown as a red crosshair) on the current page"+ arguments:+ - name: x+ type: integer+ description: "X coordinate"+ required: true+ - name: y+ type: integer+ description: "Y coordinate"+ required: true+ - name: button+ type: string+ description: "Mouse button to click (left or right, default: left)"+ required: false+ enum: ["left", "right"]++ double_click_mouse:+ signature: "double_click_mouse <x> <y>"+ docstring: "Double-click at the specified coordinates (shown as a red crosshair) on the current page"+ arguments:+ - name: x+ type: integer+ description: "X coordinate"+ required: true+ - name: y+ type: integer+ description: "Y coordinate"+ required: true++ move_mouse:+ signature: "move_mouse <x> <y>"+ docstring: "Move mouse to the specified coordinates (shown as a red crosshair) on the current page"+ arguments:+ - name: x+ type: integer+ description: "X coordinate"+ required: true+ - name: y+ type: integer+ description: "Y coordinate"+ required: true++ drag_mouse:+ signature: "drag_mouse <path>"+ docstring: "Drag mouse along a path (JSON format: [[x1,y1],[x2,y2],...]) on the current page"+ arguments:+ - name: path+ type: string+ description: "JSON array of coordinate pairs for the drag path (e.g., '[[0,0],[100,100]]')"+ required: true++ type_text:+ signature: "type_text <text>"+ docstring: "Type the given text at the current focused element on the current page"+ arguments:+ - name: text+ type: string+ description: "Text to type"+ required: true++ scroll_on_page:+ signature: "scroll_on_page <scroll_x> <scroll_y>"+ docstring: "Scroll by the specified number of pixels on the current page"+ arguments:+ - name: scroll_x+ type: integer+ description: "Horizontal scroll amount in pixels"+ required: true+ - name: scroll_y+ type: integer+ description: "Vertical scroll amount in pixels"+ required: true++ execute_script_on_page:+ signature: "execute_script_on_page <script>"+ docstring: "Execute a custom JavaScript code snippet on the current page"+ arguments:+ - name: script+ type: string+ description: "JavaScript code to execute"+ required: true++ navigate_back:+ signature: "navigate_back"+ docstring: "Navigate back in the browser history"+ arguments: []++ navigate_forward:+ signature: "navigate_forward"+ docstring: "Navigate forward in the browser history"+ arguments: []++ reload_page:+ signature: "reload_page"+ docstring: "Reload the current webpage"+ arguments: []++ wait_time:+ signature: "wait_time <ms>"+ docstring: "Wait for the specified number of milliseconds"+ arguments:+ - name: ms+ type: integer+ description: "Time to wait in milliseconds"+ required: true++ press_keys_on_page:+ signature: "press_keys_on_page <keys>"+ docstring: "Press the specified keys (JSON format: [\"key1\", \"key2\"]) on the current page"+ arguments:+ - name: keys+ type: string+ description: "JSON array of keys to press (e.g., '[\"ctrl\", \"c\"]')"+ required: true++ set_browser_window_size:+ signature: "set_browser_window_size <width> <height>"+ docstring: "Set the browser window size to the specified dimensions"+ arguments:+ - name: width+ type: integer+ description: "Window width in pixels"+ required: true+ - name: height+ type: integer+ description: "Window height in pixels"+ required: true+++ get_console_output:+ signature: "get_console_output"+ docstring: "Get console output messages from the browser (logs, errors, warnings, etc.)"+ arguments: []diff --git a/tools/web_browser/install.sh b/tools/web_browser/install.shnew file mode 100644index 00000000..bc746d6f--- /dev/null+++ b/tools/web_browser/install.sh@@ -0,0 +1,22 @@+#!/usr/bin/env bash++/root/python3.11/bin/python3 -m pip install flask requests playwright+/root/python3.11/bin/python3 -m playwright install-deps chromium++if [ -f /usr/bin/google-chrome ]; then+ export WEB_BROWSER_CHROMIUM_EXECUTABLE_PATH=/usr/bin/google-chrome+elif [ -f /usr/bin/chromium ]; then+ export WEB_BROWSER_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium+elif [ -f /usr/bin/google-chrome-stable ]; then+ export WEB_BROWSER_CHROMIUM_EXECUTABLE_PATH=/usr/bin/google-chrome-stable+else+ /root/python3.11/bin/python3 -m playwright install chromium+fi++export WEB_BROWSER_SCREENSHOT_MODE=print++export WEB_BROWSER_PORT=19321++mkdir -p /root/.web_browser_logs++run_web_browser_server &> /root/.web_browser_logs/web-browser-server.log &diff --git a/tools/web_browser/lib/browser_manager.py b/tools/web_browser/lib/browser_manager.pynew file mode 100644index 00000000..965d401d--- /dev/null+++ b/tools/web_browser/lib/browser_manager.py@@ -0,0 +1,326 @@+from __future__ import annotations++import base64+import contextlib+from pathlib import Path+import threading+import time+from typing import Any++from playwright.sync_api import Browser, Page, Playwright, sync_playwright++from web_browser_config import ServerConfig++config = ServerConfig()++SUPPORTED_BROWSERS = {"chromium", "firefox"}++CROSSHAIR_JS = """+([x, y, id]) => {+ const size = 20;+ const thickness = 3;+ const hId = id + '_h';+ const vId = id + '_v';++ const createLine = (elementId, styles) => {+ let line = document.getElementById(elementId);+ if (!line) {+ line = document.createElement('div');+ line.id = elementId;+ Object.assign(line.style, {+ position: 'fixed',+ pointerEvents: 'none',+ zIndex: '2147483647',+ backgroundColor: 'red',+ boxSizing: 'border-box',+ margin: '0',+ padding: '0',+ border: 'none',+ outline: 'none',+ transform: 'translateZ(0)',+ ...styles+ });+ document.body.appendChild(line);+ }+ return line;+ };++ const hLine = createLine(hId, {+ width: `${size}px`,+ height: `${thickness}px`,+ left: `${Math.round(x - size / 2)}px`,+ top: `${Math.round(y - thickness / 2)}px`+ });++ const vLine = createLine(vId, {+ width: `${thickness}px`,+ height: `${size}px`,+ left: `${Math.round(x - thickness / 2)}px`,+ top: `${Math.round(y - size / 2)}px`+ });+}+"""+++REMOVE_CROSSHAIR_JS = """+(id) => {+ const hEl = document.getElementById(id + '_h');+ const vEl = document.getElementById(id + '_v');+ if (hEl) hEl.remove();+ if (vEl) vEl.remove();+}+"""+++KEY_MAP = {+ # Function keys+ "f1": "F1", "f2": "F2", "f3": "F3", "f4": "F4", "f5": "F5", "f6": "F6",+ "f7": "F7", "f8": "F8", "f9": "F9", "f10": "F10", "f11": "F11", "f12": "F12",++ # Number keys (top row)+ "0": "Digit0", "1": "Digit1", "2": "Digit2", "3": "Digit3", "4": "Digit4",+ "5": "Digit5", "6": "Digit6", "7": "Digit7", "8": "Digit8", "9": "Digit9",++ # Letter keys+ "a": "KeyA", "b": "KeyB", "c": "KeyC", "d": "KeyD", "e": "KeyE", "f": "KeyF",+ "g": "KeyG", "h": "KeyH", "i": "KeyI", "j": "KeyJ", "k": "KeyK", "l": "KeyL",+ "m": "KeyM", "n": "KeyN", "o": "KeyO", "p": "KeyP", "q": "KeyQ", "r": "KeyR",+ "s": "KeyS", "t": "KeyT", "u": "KeyU", "v": "KeyV", "w": "KeyW", "x": "KeyX",+ "y": "KeyY", "z": "KeyZ",++ # Arrow keys+ "up": "ArrowUp", "down": "ArrowDown", "left": "ArrowLeft", "right": "ArrowRight",+ "arrow_up": "ArrowUp", "arrow_down": "ArrowDown", "arrow_left": "ArrowLeft", "arrow_right": "ArrowRight",++ # Navigation keys+ "home": "Home", "end": "End", "page_up": "PageUp", "page_down": "PageDown",+ "pageup": "PageUp", "pagedown": "PageDown",++ # Editing keys+ "backspace": "Backspace", "delete": "Delete", "insert": "Insert",+ "enter": "Enter", "return": "Enter", "tab": "Tab", "escape": "Escape", "esc": "Escape",++ # Modifier keys+ "shift": "Shift", "ctrl": "Control", "control": "Control", "alt": "Alt", "meta": "Meta",+ "shift_left": "ShiftLeft", "ctrl_or_meta": "ControlOrMeta", "control_or_meta": "ControlOrMeta",++ # Punctuation and symbols+ "space": " ", "spacebar": " ",+ "backquote": "Backquote", "`": "Backquote", "backtick": "Backquote",+ "minus": "Minus", "-": "Minus", "dash": "Minus",+ "equal": "Equal", "=": "Equal", "equals": "Equal",+ "backslash": "Backslash", "\\": "Backslash",+ "bracket_left": "BracketLeft", "[": "BracketLeft",+ "bracket_right": "BracketRight", "]": "BracketRight",+ "semicolon": "Semicolon", ";": "Semicolon",+ "quote": "Quote", "'": "Quote", "apostrophe": "Quote",+ "comma": "Comma", ",": "Comma",+ "period": "Period", ".": "Period", "dot": "Period",+ "slash": "Slash", "/": "Slash",++ # Numpad keys+ "numpad_0": "Numpad0", "numpad_1": "Numpad1", "numpad_2": "Numpad2", "numpad_3": "Numpad3",+ "numpad_4": "Numpad4", "numpad_5": "Numpad5", "numpad_6": "Numpad6", "numpad_7": "Numpad7",+ "numpad_8": "Numpad8", "numpad_9": "Numpad9",+ "numpad_add": "NumpadAdd", "numpad_subtract": "NumpadSubtract",+ "numpad_multiply": "NumpadMultiply", "numpad_divide": "NumpadDivide",+ "numpad_decimal": "NumpadDecimal", "numpad_enter": "NumpadEnter",++ # Lock keys+ "caps_lock": "CapsLock", "capslock": "CapsLock",+ "num_lock": "NumLock", "numlock": "NumLock",+ "scroll_lock": "ScrollLock", "scrolllock": "ScrollLock",++ # Common combinations (case-insensitive aliases)+ "ENTER": "Enter", "ESCAPE": "Escape", "BACKSPACE": "Backspace", "DELETE": "Delete",+ "TAB": "Tab", "SPACE": " ", "UP": "ArrowUp", "DOWN": "ArrowDown",+ "LEFT": "ArrowLeft", "RIGHT": "ArrowRight", "HOME": "Home", "END": "End",+}+++class BrowserManager:+ """Manages Playwright browser instance with proper resource cleanup."""++ def __init__(self):+ self.headless = config.headless+ self.browser_type = self._validate_browser_type(config.browser_type)+ self.page: Page | None = None+ self.screenshot_index = 0+ self.mouse_x = 0+ self.mouse_y = 0+ self._lock = threading.RLock()+ self.window_width = config.window_width+ self.window_height = config.window_height+ self.screenshot_delay = config.screenshot_delay+ self.reconnect_timeout = config.reconnect_timeout+ self.crosshair_id = config.crosshair_id+ self.console_messages: list[dict[str, Any]] = []+ self._init_browser()++ def _validate_browser_type(self, browser_type: str) -> str:+ """Validate and return the browser type."""+ browser_type = browser_type.lower()+ if browser_type not in SUPPORTED_BROWSERS:+ msg = (+ f"Unsupported browser type: {browser_type}. "+ f"Supported browsers: {', '.join(sorted(SUPPORTED_BROWSERS))}"+ )+ raise ValueError(msg)+ return browser_type++ def _init_browser(self):+ self.playwright: Playwright = sync_playwright().start()+ browser_launcher = getattr(self.playwright, self.browser_type)+ executable_path = None+ if self.browser_type == "chromium" and config.chromium_executable_path:+ executable_path = config.chromium_executable_path+ elif self.browser_type == "firefox" and config.firefox_executable_path:+ executable_path = config.firefox_executable_path+ launch_options = {"headless": self.headless}+ if executable_path and Path(executable_path).exists():+ launch_options["executable_path"] = executable_path+ elif executable_path:+ print(+ f"Warning: Executable path '{executable_path}' does not exist, using default browser"+ )+ self.browser: Browser = browser_launcher.launch(**launch_options)++ @property+ def browser_name(self) -> str:+ """Get the name of the browser."""+ return self.browser.browser_type.name++ @contextlib.contextmanager+ def _browser_lock(self):+ """Context manager for thread-safe browser operations."""+ with self._lock:+ yield self._ensure_browser()++ def _ensure_browser(self) -> Page:+ """Launch Chromium lazily and move cursor to (0,0) once."""+ if self.page is not None:+ return self.page+ ctx = self.browser.new_context(+ viewport={"width": self.window_width, "height": self.window_height}+ )+ self.page = ctx.new_page()+ self._setup_console_listener(self.page)+ self.page.mouse.move(0, 0)+ self.mouse_x = self.mouse_y = 0+ return self.page++ def is_website_open(self) -> bool:+ """Check if a website is currently open."""+ return self.page is not None and self.page.url not in (None, "about:blank", "")++ def cleanup(self):+ """Clean up browser resources safely."""+ with self._lock:+ for resource, name in [+ (self.page, "page"),+ (self.browser, "browser"),+ (self.playwright, "playwright")+ ]:+ if resource is not None:+ try:+ if name == "playwright":+ resource.stop()+ else:+ resource.close()+ except Exception:+ pass # Ignore cleanup errors++ self.browser = self.page = self.playwright = None++ def _inject_crosshair(self, page: Page, x: int, y: int) -> bool:+ """Inject crosshair at given coordinates. Returns True if successful."""+ try:+ page.evaluate(CROSSHAIR_JS, [x, y, self.crosshair_id])+ return True+ except Exception:+ return False++ def _remove_crosshair(self, page: Page) -> None:+ """Remove crosshair elements from the page."""+ try:+ page.evaluate(REMOVE_CROSSHAIR_JS, self.crosshair_id)+ except Exception:+ pass++ def take_screenshot(self) -> dict[str, Any]:+ """Capture screenshot with crosshair."""+ with self._browser_lock() as page:+ # this retry logic is a hack to ensure the page is loaded+ # (at least enough to inject the crosshair)+ timeout = time.time() + self.reconnect_timeout+ while time.time() < timeout:+ if self._inject_crosshair(page, self.mouse_x, self.mouse_y):+ break+ time.sleep(max(0.3, self.screenshot_delay))+ time.sleep(self.screenshot_delay)+ screenshot_data = page.screenshot(type="png")+ self._remove_crosshair(page)+ self.screenshot_index += 1+ return {+ "screenshot": base64.b64encode(screenshot_data).decode(),+ "screenshot_index": self.screenshot_index,+ }++ def validate_coordinates(self, x: int, y: int) -> tuple[bool, bool]:+ x_is_valid = 0 <= x <= self.window_width+ y_is_valid = 0 <= y <= self.window_height+ return (x_is_valid, y_is_valid)++ def constrain_mouse_position(self, page: Page) -> bool:+ """Constrain mouse position to window bounds and move if needed.+ """+ if self.window_width <= 0 or self.window_height <= 0:+ return False+ if self.mouse_x >= self.window_width or self.mouse_y >= self.window_height:+ self.mouse_x = min(self.mouse_x, self.window_width - 1)+ self.mouse_y = min(self.mouse_y, self.window_height - 1)+ self.mouse_x = max(0, self.mouse_x)+ self.mouse_y = max(0, self.mouse_y)+ page.mouse.move(self.mouse_x, self.mouse_y)+ return True+ return False++ def get_key(self, key: str) -> str:+ """Get the key from the key map."""+ if key.lower() in KEY_MAP:+ return KEY_MAP[key.lower()]+ msg = f"Key {key} not found. Supported keys: {', '.join(KEY_MAP.keys())}"+ raise ValueError(msg)++ def key_down(self, key: str):+ """Press and hold a key."""+ playwright_key = self.get_key(key)+ self.page.keyboard.down(playwright_key)++ def key_press(self, key: str):+ """Press a key."""+ playwright_key = self.get_key(key)+ self.page.keyboard.press(playwright_key)++ def key_up(self, key: str):+ """Release a key."""+ playwright_key = self.get_key(key)+ self.page.keyboard.up(playwright_key)++ def _setup_console_listener(self, page: Page):+ """Set up console message listener for the page."""+ def on_console(msg):+ self.console_messages.append({+ "type": msg.type,+ "text": msg.text,+ "timestamp": time.time(),+ "location": msg.location+ })+ page.on("console", on_console)++ def get_console_output(self) -> list[dict[str, Any]]:+ """Get all console messages and clear the buffer."""+ with self._lock:+ messages = self.console_messages.copy()+ self.console_messages.clear()+ return messagesdiff --git a/tools/web_browser/lib/web_browser_config.py b/tools/web_browser/lib/web_browser_config.pynew file mode 100644index 00000000..53dd204c--- /dev/null+++ b/tools/web_browser/lib/web_browser_config.py@@ -0,0 +1,31 @@+from __future__ import annotations++import os+from dataclasses import dataclass, field++from web_browser_utils import ScreenshotMode+++@dataclass+class ClientConfig:+ """Configuration for the web_browser client"""+ port: int = int(os.getenv("WEB_BROWSER_PORT", "8009"))+ autoscreenshot: bool = os.getenv("WEB_BROWSER_AUTOSCREENSHOT", "1") == "1"+ screenshot_mode: ScreenshotMode = ScreenshotMode(+ os.getenv("WEB_BROWSER_SCREENSHOT_MODE", ScreenshotMode.SAVE.value)+ )+++@dataclass+class ServerConfig:+ """Configuration for the web_browser server"""+ port: int = int(os.getenv("WEB_BROWSER_PORT", "8009"))+ window_width: int = int(os.getenv("WEB_BROWSER_WINDOW_WIDTH", 1024))+ window_height: int = int(os.getenv("WEB_BROWSER_WINDOW_HEIGHT", 768))+ headless: bool = os.getenv("WEB_BROWSER_HEADLESS", "1") != "0"+ screenshot_delay: float = float(os.getenv("WEB_BROWSER_SCREENSHOT_DELAY", 0.2))+ browser_type: str = os.getenv("WEB_BROWSER_BROWSER_TYPE", "chromium")+ reconnect_timeout: float = float(os.getenv("WEB_BROWSER_RECONNECT_TIMEOUT", 15))+ chromium_executable_path: str | None = os.getenv("WEB_BROWSER_CHROMIUM_EXECUTABLE_PATH")+ firefox_executable_path: str | None = os.getenv("WEB_BROWSER_FIREFOX_EXECUTABLE_PATH")+ crosshair_id: str = "__web_browser_crosshair__"diff --git a/tools/web_browser/lib/web_browser_utils.py b/tools/web_browser/lib/web_browser_utils.pynew file mode 100644index 00000000..88d6d6ce--- /dev/null+++ b/tools/web_browser/lib/web_browser_utils.py@@ -0,0 +1,123 @@+from __future__ import annotations++import base64+import functools+import requests+import sys+from enum import Enum+from pathlib import Path++from flask import jsonify, request+++class ScreenshotMode(Enum):+ SAVE = "save" # saves screenshot to png file+ PRINT = "print" # prints base64 encoded screenshot to stdout+++def normalize_url(url: str) -> str:+ # if starts with http:// or https://, return as is+ # if starts with file://, return as is+ # elif local file path exists, return as file://+ # else: return as https://+ if any(url.startswith(prefix) for prefix in ["http://", "https://", "file://"]):+ return url+ elif Path(url).exists():+ return f"file://{Path(url).resolve()}"+ else:+ return "https://" + url+++def validate_request(*required_keys):+ """Decorator to validate that all required keys are present in request JSON."""+ def decorator(func):+ @functools.wraps(func)+ def wrapper(*args, **kwargs):+ if not request.is_json:+ return jsonify({"status": "error", "message": "Request must be JSON"})++ request_data = request.get_json()+ if not request_data:+ return jsonify({"status": "error", "message": "Request body cannot be empty"})++ missing_keys = [key for key in required_keys if key not in request_data]+ if missing_keys:+ return jsonify({+ "status": "error",+ "message": f"Missing required fields: {', '.join(missing_keys)}"+ })++ return func(*args, **kwargs)+ return wrapper+ return decorator+++def catch_error(func):+ """Decorator to catch exceptions and return them as JSON."""+ @functools.wraps(func)+ def wrapper(*args, **kwargs):+ try:+ return func(*args, **kwargs)+ except Exception as e:+ return jsonify({"status": "error", "message": str(e)})+ return wrapper+++def _print_error(message, error_type="ERROR"):+ """Print error message in a normalized format."""+ print(f"{error_type}: {message}", file=sys.stderr)+++def _format_metadata_info(response):+ """Format metadata information from API response for display."""+ if "metadata" not in response or not response["metadata"]:+ return ""+ return "\n".join(f"{key}: {value}" for key, value in response["metadata"].items())+++def send_request(port, endpoint, method="GET", data=None):+ url = f"http://localhost:{port}/{endpoint}"+ if method == "GET":+ response = requests.get(url)+ else:+ response = requests.post(url, json=data)+ if response.status_code != 200:+ _print_error(f"Internal error communicating with backend: {response.text}", "INTERNAL ERROR")+ return None+ data = response.json()+ if data["status"] == "error":+ metadata_info = _format_metadata_info(data)+ error_message = data['message']+ _print_error(f"ACTION ERROR:\n{error_message}")+ if metadata_info:+ print(f"\nMETADATA:\n{metadata_info}", file=sys.stderr)+ return None+ return data+++def _print_response_with_metadata(response):+ """Print response message with formatted metadata information."""+ message = response.get("message", "")+ metadata_info = _format_metadata_info(response)+ print(f"ACTION RESPONSE:\n{message}")++ if metadata_info:+ print(f"\nMETADATA:\n{metadata_info}")+++def _handle_screenshot(screenshot_data, mode):+ """Handle screenshot data according to the specified mode"""+ if mode == ScreenshotMode.SAVE:+ path = Path("latest_screenshot.png")+ path.write_bytes(base64.b64decode(screenshot_data))+ print(f"")+ elif mode == ScreenshotMode.PRINT:+ print(f"")+ else:+ raise ValueError(f"Invalid screenshot mode: {mode}")+++def _autosave_screenshot_from_response(response, mode):+ """Handle screenshot from response data according to the specified mode"""+ if "screenshot" in response:+ _handle_screenshot(response["screenshot"], mode)diff --git a/tools/web_browser/test_console.html b/tools/web_browser/test_console.htmlnew file mode 100644index 00000000..5a5c11ca--- /dev/null+++ b/tools/web_browser/test_console.html@@ -0,0 +1 @@+<script>console.log("Hello from console!"); console.error("Test error"); console.warn("Test warning");</script><h1>Test Page</h1>