π OpenHands: AI-Driven Development
Removing the deprecated agenthub package (#14024)
Tim O'Farrellfd014e8e23fa
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 13e601937b..07887fe95e 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -36,7 +36,6 @@ Full details in our [Development Guide](./Development.md).- **[Frontend](./frontend/README.md)** - React application- **[App Server (V1)](./openhands/app_server/README.md)** - Current FastAPI application server and REST API modules-- **[Agents](./openhands/agenthub/README.md)** - AI agent implementations- **[Runtime](./openhands/runtime/README.md)** - Execution environments- **[Evaluation](https://github.com/OpenHands/benchmarks)** - Testing and benchmarksdiff --git a/containers/app/Dockerfile b/containers/app/Dockerfileindex c1ecc46575..ce0ca62f7e 100644--- a/containers/app/Dockerfile+++ b/containers/app/Dockerfile@@ -91,8 +91,6 @@ COPY --chown=openhands:openhands --chmod=770 ./openhands ./openhandsCOPY --chown=openhands:openhands --chmod=777 ./openhands/runtime/plugins ./openhands/runtime/pluginsCOPY --chown=openhands:openhands pyproject.toml poetry.lock README.md MANIFEST.in LICENSE ./-# This is run as "openhands" user, and will create __pycache__ with openhands:openhands ownership-RUN python openhands/core/download.py # No-op to download assets# Add this line to set group ownership of all files/directories not already in "app" group# openhands:openhands -> openhands:openhandsRUN find /app \! -group openhands -exec chgrp openhands {} +diff --git a/openhands/agenthub/README.md b/openhands/agenthub/README.mddeleted file mode 100644index 1c4d669e80..0000000000--- a/openhands/agenthub/README.md+++ /dev/null@@ -1,143 +0,0 @@-# Agent Hub--In this folder, there may exist multiple implementations of `Agent` that will be used by the framework.--For example, `openhands/agenthub/codeact_agent`, etc.-Contributors from different backgrounds and interests can choose to contribute to any (or all!) of these directions.--## Constructing an Agent--The abstraction for an agent can be found [here](../controller/agent.py).--Agents are run inside of a loop. At each iteration, `agent.step()` is called with a-[State](../controller/state/state.py) input, and the agent must output an [Action](../events/action).--Every agent also has a `self.llm` which it can use to interact with the LLM configured by the user.-See the [LiteLLM docs for `self.llm.completion`](https://docs.litellm.ai/docs/completion).--## State--The `state` represents the running state of an agent in the OpenHands system. The class handles saving and restoring the agent session. It is serialized in a pickle.--The State object stores information about:--* Multi-agent state / delegates:- * the 'root task' (conversation between the agent and the user)- * the subtask (conversation between an agent and the user or another agent)- * global and local iterations- * delegate levels for multi-agent interactions- * almost stuck state-* Running state of an agent:- * current agent state (e.g., LOADING, RUNNING, PAUSED)- * traffic control state for rate limiting- * confirmation mode- * the last error encountered-* History:- * start and end IDs for events in agent's history. This allows to retrieve the actions taken by the agent, and observations (e.g. file content, command output) from the current or past sessions.-* Metrics:- * global metrics for the current task- * local metrics for the current subtask-* Extra data:- * additional task-specific data--The agent can manage a structured task list through [`TaskTrackingAction`](../events/action/agent.py),-which powers the `task_tracker` tool used by agents such as `CodeActAgent`.--## Actions--Here is a list of available Actions, which can be returned by `agent.step()`:--- [`CmdRunAction`](../events/action/commands.py) - Runs a command inside a sandboxed terminal-- [`IPythonRunCellAction`](../events/action/commands.py) - Execute a block of Python code interactively (in Jupyter notebook) and receives `CmdOutputObservation`. Requires setting up `jupyter` [plugin](../runtime/plugins) as a requirement.-- [`FileReadAction`](../events/action/files.py) - Reads the content of a file-- [`FileWriteAction`](../events/action/files.py) - Writes new content to a file-- [`BrowseURLAction`](../events/action/browse.py) - Gets the content of a URL-- [`TaskTrackingAction`](../events/action/agent.py) - Views or updates the task list used for task management.-- [`AgentFinishAction`](../events/action/agent.py) - Stops the control loop, allowing the user/delegator agent to enter a new task-- [`AgentRejectAction`](../events/action/agent.py) - Stops the control loop, allowing the user/delegator agent to enter a new task-- [`AgentFinishAction`](../events/action/agent.py) - Stops the control loop, allowing the user to enter a new task-- [`MessageAction`](../events/action/message.py) - Represents a message from an agent or the user--To serialize and deserialize an action, you can use:-- `action.to_dict()` to serialize the action to a dictionary to be sent to the UI, including a user-friendly string representation of the message-- `action.to_memory()` to serialize the action to a dictionary to be sent to the LLM. It may include raw information, such as the underlying exceptions that occurred during the action execution.-- `action_from_dict(action_dict)` to deserialize the action from a dictionary.--## Observations--There are also several types of Observations. These are typically available in the step following the corresponding Action.-But they may also appear as a result of asynchronous events (e.g. a message from the user).--Here is a list of available Observations:--- [`CmdOutputObservation`](../events/observation/commands.py)-- [`BrowserOutputObservation`](../events/observation/browse.py)-- [`FileReadObservation`](../events/observation/files.py)-- [`FileWriteObservation`](../events/observation/files.py)-- [`TaskTrackingObservation`](../events/observation/task_tracking.py)-- [`ErrorObservation`](../events/observation/error.py)-- [`SuccessObservation`](../events/observation/success.py)--You can use `observation.to_dict()` and `observation_from_dict` to serialize and deserialize observations.--## Interface--Every agent must implement the following methods:--### `step`--```-def step(self, state: "State") -> "Action"-```--`step` moves the agent forward one step towards its goal. This probably means-sending a prompt to the LLM, then parsing the response into an `Action`.--## Agent Delegation--OpenHands is a multi-agentic system. Agents can delegate tasks to other agents, whether-prompted by the user, or when the agent decides to ask another agent for help. For example,-the `CodeActAgent` might delegate to the `BrowsingAgent` to answer questions that involve browsing-the web. The Delegator Agent forwards tasks to micro-agents, such as 'RepoStudyAgent' to study a repo,-or 'VerifierAgent' to verify a task completion.--### Understanding the terminology--A `task` is an end-to-end conversation between OpenHands (the whole system) and the user,-which might involve one or more inputs from the user. It starts with an initial input-(typically a task statement) from the user, and ends with either an `AgentFinishAction`-initiated by the agent, a stop initiated by the user, or an error.--A `subtask` is an end-to-end conversation between an agent and the user, or-another agent. If a `task` is conducted by a single agent, then it's also a `subtask`-itself. Otherwise, a `task` consists of multiple `subtasks`, each executed by-one agent.--For example, considering a task from the user: `tell me how many GitHub stars-OpenHands repo has`. Let's assume the default agent is CodeActAgent.--```--- TASK STARTS (SUBTASK 0 STARTS) ----DELEGATE_LEVEL 0, ITERATION 0, LOCAL_ITERATION 0-CodeActAgent: I should request help from BrowsingAgent---- DELEGATE STARTS (SUBTASK 1 STARTS) ----DELEGATE_LEVEL 1, ITERATION 1, LOCAL_ITERATION 0-BrowsingAgent: Let me find the answer on GitHub--DELEGATE_LEVEL 1, ITERATION 2, LOCAL_ITERATION 1-BrowsingAgent: I found the answer, let me convey the result and finish---- DELEGATE ENDS (SUBTASK 1 ENDS) ----DELEGATE_LEVEL 0, ITERATION 3, LOCAL_ITERATION 1-CodeActAgent: I got the answer from BrowsingAgent, let me convey the result-and finish---- TASK ENDS (SUBTASK 0 ENDS) ---```--Note how ITERATION counter is shared across agents, while LOCAL_ITERATION-is local to each subtask.diff --git a/openhands/agenthub/__init__.py b/openhands/agenthub/__init__.pydeleted file mode 100644index ab0aa7ae1a..0000000000--- a/openhands/agenthub/__init__.py+++ /dev/null@@ -1,24 +0,0 @@-from dotenv import load_dotenv--load_dotenv()---from openhands.agenthub import ( # noqa: E402- browsing_agent,- codeact_agent,- dummy_agent,- loc_agent,- readonly_agent,- visualbrowsing_agent,-)-from openhands.controller.agent import Agent # noqa: E402--__all__ = [- 'Agent',- 'codeact_agent',- 'dummy_agent',- 'browsing_agent',- 'visualbrowsing_agent',- 'readonly_agent',- 'loc_agent',-]diff --git a/openhands/agenthub/browsing_agent/README.md b/openhands/agenthub/browsing_agent/README.mddeleted file mode 100644index f134212159..0000000000--- a/openhands/agenthub/browsing_agent/README.md+++ /dev/null@@ -1,16 +0,0 @@-# Browsing Agent Framework--This folder implements the basic BrowserGym [demo agent](https://github.com/ServiceNow/BrowserGym/tree/main/demo_agent) that enables full-featured web browsing.---## Test run--Note that for browsing tasks, GPT-4 is usually a requirement to get reasonable results, due to the complexity of the web page structures.--```-poetry run python ./openhands/core/main.py \- -i 10 \- -t "tell me the usa's president using google search" \- -c BrowsingAgent \- -m claude-3-5-sonnet-20241022-```diff --git a/openhands/agenthub/browsing_agent/__init__.py b/openhands/agenthub/browsing_agent/__init__.pydeleted file mode 100644index 436d69d135..0000000000--- a/openhands/agenthub/browsing_agent/__init__.py+++ /dev/null@@ -1,4 +0,0 @@-from openhands.agenthub.browsing_agent.browsing_agent import BrowsingAgent-from openhands.controller.agent import Agent--Agent.register('BrowsingAgent', BrowsingAgent)diff --git a/openhands/agenthub/browsing_agent/browsing_agent.py b/openhands/agenthub/browsing_agent/browsing_agent.pydeleted file mode 100644index b9cc15837d..0000000000--- a/openhands/agenthub/browsing_agent/browsing_agent.py+++ /dev/null@@ -1,230 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import os--from browsergym.core.action.highlevel import HighLevelActionSet-from browsergym.utils.obs import flatten_axtree_to_str--from openhands.agenthub.browsing_agent.response_parser import BrowsingResponseParser-from openhands.controller.agent import Agent-from openhands.controller.state.state import State-from openhands.core.config import AgentConfig-from openhands.core.logger import openhands_logger as logger-from openhands.core.message import Message, TextContent-from openhands.events.action import (- Action,- AgentFinishAction,- BrowseInteractiveAction,- MessageAction,-)-from openhands.events.event import EventSource-from openhands.events.observation import BrowserOutputObservation-from openhands.events.observation.observation import Observation-from openhands.llm.llm_registry import LLMRegistry-from openhands.runtime.plugins import (- PluginRequirement,-)--USE_NAV = (- os.environ.get('USE_NAV', 'true') == 'true'-) # only disable NAV actions when running webarena and miniwob benchmarks-USE_CONCISE_ANSWER = (- os.environ.get('USE_CONCISE_ANSWER', 'false') == 'true'-) # only return concise answer when running webarena and miniwob benchmarks--if not USE_NAV and USE_CONCISE_ANSWER:- EVAL_MODE = True # disabled NAV actions and only return concise answer, for webarena and miniwob benchmarks\-else:- EVAL_MODE = False---def get_error_prefix(last_browser_action: str) -> str:- return f'IMPORTANT! Last action is incorrect:\n{last_browser_action}\nThink again with the current observation of the page.\n'---def get_system_message(goal: str, action_space: str) -> str:- return f"""\-# Instructions-Review the current state of the page and all other information to find the best-possible next action to accomplish your goal. Your answer will be interpreted-and executed by a program, make sure to follow the formatting instructions.--# Goal:-{goal}--# Action Space-{action_space}-"""---CONCISE_INSTRUCTION = """\--Here is another example with chain of thought of a valid action when providing a concise answer to user:-"-In order to accomplish my goal I need to send the information asked back to the user. This page list the information of HP Inkjet Fax Machine, which is the product identified in the objective. Its price is $279.49. I will send a message back to user with the answer.-```send_msg_to_user("$279.49")```-"-"""---def get_prompt(- error_prefix: str, cur_url: str, cur_axtree_txt: str, prev_action_str: str-) -> str:- prompt = f"""\-{error_prefix}--# Current Page URL:-{cur_url}--# Current Accessibility Tree:-{cur_axtree_txt}--# Previous Actions-{prev_action_str}--Here is an example with chain of thought of a valid action when clicking on a button:-"-In order to accomplish my goal I need to click on the button with bid 12-```click("12")```-"-""".strip()- if USE_CONCISE_ANSWER:- prompt += CONCISE_INSTRUCTION- return prompt---class BrowsingAgent(Agent):- VERSION = '1.0'- """- An agent that interacts with the browser.- """-- sandbox_plugins: list[PluginRequirement] = []- response_parser = BrowsingResponseParser()-- def __init__(- self,- config: AgentConfig,- llm_registry: LLMRegistry,- ) -> None:- """Initializes a new instance of the BrowsingAgent class.-- Parameters:- - llm (LLM): The llm to be used by this agent- """- super().__init__(config, llm_registry)- # define a configurable action space, with chat functionality, web navigation, and webpage grounding using accessibility tree and HTML.- # see https://github.com/ServiceNow/BrowserGym/blob/main/core/src/browsergym/core/action/highlevel.py for more details- action_subsets = ['chat', 'bid']- if USE_NAV:- action_subsets.append('nav')- self.action_space = HighLevelActionSet(- subsets=action_subsets,- strict=False, # less strict on the parsing of the actions- multiaction=True, # enable to agent to take multiple actions at once- )-- self.reset()-- def reset(self) -> None:- """Resets the Browsing Agent's internal state."""- super().reset()- # Reset agent-specific counters but not LLM metrics- self.error_accumulator = 0-- def step(self, state: State) -> Action:- """Performs one step using the Browsing Agent.- This includes gathering information on previous steps and prompting the model to make a browsing command to execute.-- Parameters:- - state (State): used to get updated info-- Returns:- - BrowseInteractiveAction(browsergym_command) - BrowserGym commands to run- - MessageAction(content) - Message action to run (e.g. ask for clarification)- - AgentFinishAction() - end the interaction- """- messages: list[Message] = []- prev_actions = []- cur_url = ''- cur_axtree_txt = ''- error_prefix = ''- last_obs = None- last_action = None-- if EVAL_MODE and len(state.view) == 1:- # for webarena and miniwob++ eval, we need to retrieve the initial observation already in browser env- # initialize and retrieve the first observation by issuing an noop OP- # For non-benchmark browsing, the browser env starts with a blank page, and the agent is expected to first navigate to desired websites- return BrowseInteractiveAction(browser_actions='noop()')-- for event in state.view:- if isinstance(event, BrowseInteractiveAction):- prev_actions.append(event.browser_actions)- last_action = event- elif isinstance(event, MessageAction) and event.source == EventSource.AGENT:- # agent has responded, task finished.- return AgentFinishAction(outputs={'content': event.content})- elif isinstance(event, Observation):- last_obs = event-- if EVAL_MODE:- prev_actions = prev_actions[1:] # remove the first noop action-- prev_action_str = '\n'.join(prev_actions)- # if the final BrowserInteractiveAction exec BrowserGym's send_msg_to_user,- # we should also send a message back to the user in OpenHands and call it a day- if (- isinstance(last_action, BrowseInteractiveAction)- and last_action.browsergym_send_msg_to_user- ):- return MessageAction(last_action.browsergym_send_msg_to_user)-- if isinstance(last_obs, BrowserOutputObservation):- if last_obs.error:- # add error recovery prompt prefix- error_prefix = get_error_prefix(last_obs.last_browser_action)- self.error_accumulator += 1- if self.error_accumulator > 5:- return MessageAction('Too many errors encountered. Task failed.')-- cur_url = last_obs.url-- try:- cur_axtree_txt = flatten_axtree_to_str(- last_obs.axtree_object,- extra_properties=last_obs.extra_element_properties,- with_clickable=True,- filter_visible_only=True,- )- except Exception as e:- logger.error(- 'Error when trying to process the accessibility tree: %s', e- )- return MessageAction('Error encountered when browsing.')-- goal, _ = state.get_current_user_intent()-- if goal is None:- goal = state.inputs['task']-- system_msg = get_system_message(- goal,- self.action_space.describe(with_long_description=False, with_examples=True),- )-- messages.append(Message(role='system', content=[TextContent(text=system_msg)]))-- prompt = get_prompt(error_prefix, cur_url, cur_axtree_txt, prev_action_str)- messages.append(Message(role='user', content=[TextContent(text=prompt)]))-- response = self.llm.completion(- messages=messages,- stop=[')```', ')\n```'],- )- return self.response_parser.parse(response)diff --git a/openhands/agenthub/browsing_agent/response_parser.py b/openhands/agenthub/browsing_agent/response_parser.pydeleted file mode 100644index 3a932907cd..0000000000--- a/openhands/agenthub/browsing_agent/response_parser.py+++ /dev/null@@ -1,133 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import ast-import re--from openhands.controller.action_parser import ActionParser, ResponseParser-from openhands.core.logger import openhands_logger as logger-from openhands.events.action import (- Action,- BrowseInteractiveAction,-)---class BrowsingResponseParser(ResponseParser):- def __init__(self) -> None:- # Need to pay attention to the item order in self.action_parsers- super().__init__()- self.action_parsers = [BrowsingActionParserMessage()]- self.default_parser = BrowsingActionParserBrowseInteractive()-- def parse(- self, response: str | dict[str, list[dict[str, dict[str, str | None]]]]- ) -> Action:- if isinstance(response, str):- action_str = response- else:- action_str = self.parse_response(response)- return self.parse_action(action_str)-- def parse_response(- self, response: dict[str, list[dict[str, dict[str, str | None]]]]- ) -> str:- action_str = response['choices'][0]['message']['content']- if action_str is None:- return ''- action_str = action_str.strip()- # Ensure action_str ends with ')```'- if action_str:- if not action_str.endswith('```'):- if action_str.endswith(')'):- action_str += '```' # prevent duplicate ending paranthesis, e.g. send_msg_to_user('Done'))- else:- action_str += ')```' # expected format- logger.debug(action_str)- return action_str-- def parse_action(self, action_str: str) -> Action:- for action_parser in self.action_parsers:- if action_parser.check_condition(action_str):- return action_parser.parse(action_str)- return self.default_parser.parse(action_str)---class BrowsingActionParserMessage(ActionParser):- """Parser action:- - BrowseInteractiveAction(browser_actions) - unexpected response format, message back to user- """-- def __init__(self) -> None:- pass-- def check_condition(self, action_str: str) -> bool:- return '```' not in action_str-- def parse(self, action_str: str) -> Action:- msg = f'send_msg_to_user("""{action_str}""")'- return BrowseInteractiveAction(- browser_actions=msg,- thought=action_str,- browsergym_send_msg_to_user=action_str,- )---class BrowsingActionParserBrowseInteractive(ActionParser):- """Parser action:- - BrowseInteractiveAction(browser_actions) - handle send message to user function call in BrowserGym- """-- def __init__(self) -> None:- pass-- def check_condition(self, action_str: str) -> bool:- return True-- def parse(self, action_str: str) -> Action:- # parse the action string into browser_actions and thought- # the LLM can return only one string, or both-- # when both are returned, it looks like this:- ### Based on the current state of the page and the goal of finding out the president of the USA, the next action should involve searching for information related to the president.- ### To achieve this, we can navigate to a reliable source such as a search engine or a specific website that provides information about the current president of the USA.- ### Here is an example of a valid action to achieve this:- ### ```- ### goto('https://www.whitehouse.gov/about-the-white-house/presidents/'- # in practice, BrowsingResponseParser.parse_response also added )``` to the end of the string-- # when the LLM returns only one string, it looks like this:- ### goto('https://www.whitehouse.gov/about-the-white-house/presidents/')- # and parse_response added )``` to the end of the string- parts = action_str.split('```')- browser_actions = (- parts[1].strip() if parts[1].strip() != '' else parts[0].strip()- )- thought = parts[0].strip() if parts[1].strip() != '' else ''-- # if the LLM wants to talk to the user, we extract the message- msg_content = ''- for sub_action in browser_actions.split('\n'):- if 'send_msg_to_user(' in sub_action:- try:- tree = ast.parse(sub_action)- args = tree.body[0].value.args # type: ignore- msg_content = args[0].value- except SyntaxError:- logger.error(f'Error parsing action: {sub_action}')- # the syntax was not correct, but we can still try to get the message- # e.g. send_msg_to_user("Hello, world!") or send_msg_to_user('Hello, world!'- match = re.search(r'send_msg_to_user\((["\'])(.*?)\1\)', sub_action)- if match:- msg_content = match.group(2)- else:- msg_content = ''-- return BrowseInteractiveAction(- browser_actions=browser_actions,- thought=thought,- browsergym_send_msg_to_user=msg_content,- )diff --git a/openhands/agenthub/browsing_agent/utils.py b/openhands/agenthub/browsing_agent/utils.pydeleted file mode 100644index b33b62468b..0000000000--- a/openhands/agenthub/browsing_agent/utils.py+++ /dev/null@@ -1,181 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import collections-import re-from warnings import warn--import yaml---def yaml_parser(message: str) -> tuple[dict, bool, str]:- """Parse a yaml message for the retry function."""- # saves gpt-3.5 from some yaml parsing errors- message = re.sub(r':\s*\n(?=\S|\n)', ': ', message)-- try:- value = yaml.safe_load(message)- valid = True- retry_message = ''- except yaml.YAMLError as e:- warn(str(e), stacklevel=2)- value = {}- valid = False- retry_message = "Your response is not a valid yaml. Please try again and be careful to the format. Don't add any apology or comment, just the answer."- return value, valid, retry_message---def _compress_chunks(- text: str, identifier: str, skip_list: list[str], split_regex: str = '\n\n+'-) -> tuple[dict[str, str], str]:- """Compress a string by replacing redundant chunks by identifiers. Chunks are defined by the split_regex."""- text_list = re.split(split_regex, text)- text_list = [chunk.strip() for chunk in text_list]- counter = collections.Counter(text_list)- def_dict = {}- id = 0-- # Store items that occur more than once in a dictionary- for item, count in counter.items():- if count > 1 and item not in skip_list and len(item) > 10:- def_dict[f'{identifier}-{id}'] = item- id += 1-- # Replace redundant items with their identifiers in the text- compressed_text = '\n'.join(text_list)- for key, value in def_dict.items():- compressed_text = compressed_text.replace(value, key)-- return def_dict, compressed_text---def compress_string(text: str) -> str:- """Compress a string by replacing redundant paragraphs and lines with identifiers."""- # Perform paragraph-level compression- def_dict, compressed_text = _compress_chunks(- text, identifier='Β§', skip_list=[], split_regex='\n\n+'- )-- # Perform line-level compression, skipping any paragraph identifiers- line_dict, compressed_text = _compress_chunks(- compressed_text, 'ΒΆ', list(def_dict.keys()), split_regex='\n+'- )- def_dict.update(line_dict)-- # Create a definitions section- def_lines = ['<definitions>']- for key, value in def_dict.items():- def_lines.append(f'{key}:\n{value}')- def_lines.append('</definitions>')- definitions = '\n'.join(def_lines)-- return definitions + '\n' + compressed_text---def extract_html_tags(text: str, keys: list[str]) -> dict[str, list[str]]:- """Extract the content within HTML tags for a list of keys.-- Parameters- ----------- text : str- The input string containing the HTML tags.- keys : list of str- The HTML tags to extract the content from.-- Returns:- -------- dict- A dictionary mapping each key to a list of subset in `text` that match the key.-- Notes:- ------ All text and keys will be converted to lowercase before matching.-- """- content_dict = {}- # text = text.lower()- # keys = set([k.lower() for k in keys])- for key in keys:- pattern = f'<{key}>(.*?)</{key}>'- matches = re.findall(pattern, text, re.DOTALL)- if matches:- content_dict[key] = [match.strip() for match in matches]- return content_dict---class ParseError(Exception):- pass---def parse_html_tags_raise(- text: str,- keys: list[str] | None = None,- optional_keys: list[str] | None = None,- merge_multiple: bool = False,-) -> dict[str, str]:- """A version of parse_html_tags that raises an exception if the parsing is not successful."""- content_dict, valid, retry_message = parse_html_tags(- text, keys, optional_keys, merge_multiple=merge_multiple- )- if not valid:- raise ParseError(retry_message)- return content_dict---def parse_html_tags(- text: str,- keys: list[str] | None = None,- optional_keys: list[str] | None = None,- merge_multiple: bool = False,-) -> tuple[dict[str, str], bool, str]:- """Satisfy the parse api, extracts 1 match per key and validates that all keys are present-- Parameters- ----------- text : str- The input string containing the HTML tags.- keys : list of str- The HTML tags to extract the content from.- optional_keys : list of str- The HTML tags to extract the content from, but are optional.-- Returns:- -------- dict- A dictionary mapping each key to subset of `text` that match the key.- bool- Whether the parsing was successful.- str- A message to be displayed to the agent if the parsing was not successful.- """- keys = keys or []- optional_keys = optional_keys or []- all_keys = list(keys) + list(optional_keys)- content_dict = extract_html_tags(text, all_keys)- retry_messages = []- result_dict: dict[str, str] = {}-- for key in all_keys:- if key not in content_dict:- if key not in optional_keys:- retry_messages.append(f'Missing the key <{key}> in the answer.')- else:- val = content_dict[key]- if len(val) > 1:- if not merge_multiple:- retry_messages.append(- f'Found multiple instances of the key {key}. You should have only one of them.'- )- else:- # merge the multiple instances- result_dict[key] = '\n'.join(val)- else:- result_dict[key] = val[0]-- valid = len(retry_messages) == 0- retry_message = '\n'.join(retry_messages)- return result_dict, valid, retry_messagediff --git a/openhands/agenthub/codeact_agent/README.md b/openhands/agenthub/codeact_agent/README.mddeleted file mode 100644index 3a36f6b3c2..0000000000--- a/openhands/agenthub/codeact_agent/README.md+++ /dev/null@@ -1,113 +0,0 @@-# CodeAct Agent Framework--This folder is an implementation of OpenHands's main agent, the CodeAct Agent. It is based on ([CodeAct](https://arxiv.org/abs/2402.01030), [tweet](https://twitter.com/xingyaow_/status/1754556835703751087)), an idea of consolidating LLM agents' **act**ions into a unified **code** action space for both *simplicity* and *performance*.--## Overview--The CodeAct agent operates through a function calling interface. At each turn, the agent can:--1. **Converse**: Communicate with humans in natural language to ask for clarification, confirmation, etc.-2. **CodeAct**: Execute actions through a set of well-defined tools:- - Execute Linux `bash` commands with `execute_bash`- - Run Python code in an [IPython](https://ipython.org/) environment with `execute_ipython_cell`- - Interact with web browsers using `browser` and `fetch`- - Edit files using `str_replace_editor` or `edit_file`----## Built-in Tools--The agent provides several built-in tools:--### 1. `execute_bash`-- Execute any valid Linux bash command-- Handles long-running commands by running them in background with output redirection-- Supports interactive processes with STDIN input and process interruption-- Handles command timeouts with automatic retry in background mode--### 2. `execute_ipython_cell`-- Run Python code in an IPython environment-- Supports magic commands like `%pip`-- Variables are scoped to the IPython environment-- Requires defining variables and importing packages before use--### 3. `web_read` and `browser`-- `web_read`: Read and convert webpage content to markdown-- `browser`: Interact with webpages through Python code-- Supports common browser actions like navigation, clicking, form filling, scrolling-- Handles file uploads and drag-and-drop operations--### 4. `str_replace_editor`-- View, create and edit files through string replacement-- Persistent state across command calls-- File viewing with line numbers-- String replacement with exact matching-- Undo functionality for edits--### 5. `edit_file` (LLM-based)-- Edit files using LLM-based content generation-- Support for partial file edits with line ranges-- Handles large files by editing specific sections-- Append mode for adding content to files--## Configuration--Tools can be enabled/disabled through configuration parameters:-- `enable_browsing`: Enable browser interaction tools-- `enable_jupyter`: Enable IPython code execution-- `enable_llm_editor`: Enable LLM-based file editing (falls back to string replacement editor if disabled)--## Micro-agents--The agent includes specialized micro-agents for specific tasks:--1. **npm**: Handles npm package installation with non-interactive shell workarounds-2. **github**: Manages GitHub operations with API token support and PR creation guidelines-3. **flarglebargle**: Easter egg response handler--## Adding New Tools--The CodeAct agent uses a function calling interface based on `litellm`'s `ChatCompletionToolParam`. To add a new tool:--1. Define the tool in `function_calling.py`:-```python-MyTool = ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name='my_tool',- description='Description of what the tool does and how to use it',- parameters={- 'type': 'object',- 'properties': {- 'param1': {- 'type': 'string',- 'description': 'Description of parameter 1',- },- 'param2': {- 'type': 'integer',- 'description': 'Description of parameter 2',- },- },- 'required': ['param1'], # List required parameters here- },- ),-)-```--2. Add the tool to `get_tools()` in `function_calling.py`-3. Implement the corresponding action handler in the agent class--## Implementation Details--The agent is implemented in two main files:--1. `codeact_agent.py`: Core agent implementation with:- - Message history management- - Tool execution handling- - State management- - Action/observation processing--2. `function_calling.py`: Tool definitions and function calling interface with:- - Tool parameter specifications- - Tool descriptions and examples- - Function calling response parsingdiff --git a/openhands/agenthub/codeact_agent/__init__.py b/openhands/agenthub/codeact_agent/__init__.pydeleted file mode 100644index 63f1fdb820..0000000000--- a/openhands/agenthub/codeact_agent/__init__.py+++ /dev/null@@ -1,4 +0,0 @@-from openhands.agenthub.codeact_agent.codeact_agent import CodeActAgent-from openhands.controller.agent import Agent--Agent.register('CodeActAgent', CodeActAgent)diff --git a/openhands/agenthub/codeact_agent/codeact_agent.py b/openhands/agenthub/codeact_agent/codeact_agent.pydeleted file mode 100644index 18960a0eca..0000000000--- a/openhands/agenthub/codeact_agent/codeact_agent.py+++ /dev/null@@ -1,317 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-# V1 replacement for this module lives in the Software Agent SDK.-import os-import sys-from collections import deque-from typing import TYPE_CHECKING--from openhands.llm.llm_registry import LLMRegistry--if TYPE_CHECKING:- from litellm import ChatCompletionToolParam-- from openhands.events.action import Action- from openhands.llm.llm import ModelResponse--import openhands.agenthub.codeact_agent.function_calling as codeact_function_calling-from openhands.agenthub.codeact_agent.tools.bash import create_cmd_run_tool-from openhands.agenthub.codeact_agent.tools.browser import BrowserTool-from openhands.agenthub.codeact_agent.tools.condensation_request import (- CondensationRequestTool,-)-from openhands.agenthub.codeact_agent.tools.finish import FinishTool-from openhands.agenthub.codeact_agent.tools.ipython import IPythonTool-from openhands.agenthub.codeact_agent.tools.llm_based_edit import LLMBasedFileEditTool-from openhands.agenthub.codeact_agent.tools.str_replace_editor import (- create_str_replace_editor_tool,-)-from openhands.agenthub.codeact_agent.tools.task_tracker import (- create_task_tracker_tool,-)-from openhands.agenthub.codeact_agent.tools.think import ThinkTool-from openhands.controller.agent import Agent-from openhands.controller.state.state import State-from openhands.core.config import AgentConfig-from openhands.core.logger import openhands_logger as logger-from openhands.core.message import Message-from openhands.events.action import AgentFinishAction, MessageAction-from openhands.events.event import Event-from openhands.llm.llm_utils import check_tools-from openhands.memory.condenser import Condenser-from openhands.memory.condenser.condenser import Condensation, View-from openhands.memory.conversation_memory import ConversationMemory-from openhands.runtime.plugins import (- AgentSkillsRequirement,- JupyterRequirement,- PluginRequirement,-)-from openhands.utils.prompt import PromptManager---class CodeActAgent(Agent):- VERSION = '2.2'- """- The Code Act Agent is a minimalist agent.- The agent works by passing the model a list of action-observation pairs and prompting the model to take the next step.-- ### Overview-- This agent implements the CodeAct idea ([paper](https://arxiv.org/abs/2402.01030), [tweet](https://twitter.com/xingyaow_/status/1754556835703751087)) that consolidates LLM agents' **act**ions into a unified **code** action space for both *simplicity* and *performance* (see paper for more details).-- The conceptual idea is illustrated below. At each turn, the agent can:-- 1. **Converse**: Communicate with humans in natural language to ask for clarification, confirmation, etc.- 2. **CodeAct**: Choose to perform the task by executing code- - Execute any valid Linux `bash` command- - Execute any valid `Python` code with [an interactive Python interpreter](https://ipython.org/). This is simulated through `bash` command, see plugin system below for more details.-- -- """-- sandbox_plugins: list[PluginRequirement] = [- # NOTE: AgentSkillsRequirement need to go before JupyterRequirement, since- # AgentSkillsRequirement provides a lot of Python functions,- # and it needs to be initialized before Jupyter for Jupyter to use those functions.- AgentSkillsRequirement(),- JupyterRequirement(),- ]-- def __init__(self, config: AgentConfig, llm_registry: LLMRegistry) -> None:- """Initializes a new instance of the CodeActAgent class.-- Parameters:- - config (AgentConfig): The configuration for this agent- """- super().__init__(config, llm_registry)- self.pending_actions: deque['Action'] = deque()- self.reset()- self.tools = self._get_tools()-- # Create a ConversationMemory instance- self.conversation_memory = ConversationMemory(self.config, self.prompt_manager)-- self.condenser = Condenser.from_config(self.config.condenser, llm_registry)- logger.debug(f'Using condenser: {type(self.condenser)}')-- # Override with router if needed- self.llm = self.llm_registry.get_router(self.config)-- @property- def prompt_manager(self) -> PromptManager:- if self._prompt_manager is None:- self._prompt_manager = PromptManager(- prompt_dir=os.path.join(os.path.dirname(__file__), 'prompts'),- system_prompt_filename=self.config.resolved_system_prompt_filename,- )-- return self._prompt_manager-- def _get_tools(self) -> list['ChatCompletionToolParam']:- # For these models, we use short tool descriptions ( < 1024 tokens)- # to avoid hitting the OpenAI token limit for tool descriptions.- SHORT_TOOL_DESCRIPTION_LLM_SUBSTRS = ['gpt-4', 'o3', 'o1', 'o4']-- use_short_tool_desc = False- if self.llm is not None:- # For historical reasons, previously OpenAI enforces max function description length of 1k characters- # https://community.openai.com/t/function-call-description-max-length/529902- # But it no longer seems to be an issue recently- # https://community.openai.com/t/was-the-character-limit-for-schema-descriptions-upgraded/1225975- # Tested on GPT-5 and longer description still works. But we still keep the logic to be safe for older models.- use_short_tool_desc = any(- model_substr in self.llm.config.model- for model_substr in SHORT_TOOL_DESCRIPTION_LLM_SUBSTRS- )-- tools = []- if self.config.enable_cmd:- tools.append(create_cmd_run_tool(use_short_description=use_short_tool_desc))- if self.config.enable_think:- tools.append(ThinkTool)- if self.config.enable_finish:- tools.append(FinishTool)- if self.config.enable_condensation_request:- tools.append(CondensationRequestTool)- if self.config.enable_browsing:- if sys.platform == 'win32':- logger.warning('Windows runtime does not support browsing yet')- else:- tools.append(BrowserTool)- if self.config.enable_jupyter:- tools.append(IPythonTool)- if self.config.enable_plan_mode:- # In plan mode, we use the task_tracker tool for task management- tools.append(create_task_tracker_tool(use_short_tool_desc))- if self.config.enable_llm_editor:- tools.append(LLMBasedFileEditTool)- elif self.config.enable_editor:- tools.append(- create_str_replace_editor_tool(- use_short_description=use_short_tool_desc,- runtime_type=self.config.runtime,- )- )- return tools-- def reset(self) -> None:- """Resets the CodeAct Agent's internal state."""- super().reset()- # Only clear pending actions, not LLM metrics- self.pending_actions.clear()-- def step(self, state: State) -> 'Action':- """Performs one step using the CodeAct Agent.-- This includes gathering info on previous steps and prompting the model to make a command to execute.-- Parameters:- - state (State): used to get updated info-- Returns:- - CmdRunAction(command) - bash command to run- - IPythonRunCellAction(code) - IPython code to run- - AgentDelegateAction(agent, inputs) - delegate action for (sub)task- - MessageAction(content) - Message action to run (e.g. ask for clarification)- - AgentFinishAction() - end the interaction- - CondensationAction(...) - condense conversation history by forgetting specified events and optionally providing a summary- - FileReadAction(path, ...) - read file content from specified path- - FileEditAction(path, ...) - edit file using LLM-based (deprecated) or ACI-based editing- - AgentThinkAction(thought) - log agent's thought/reasoning process- - CondensationRequestAction() - request condensation of conversation history- - BrowseInteractiveAction(browser_actions) - interact with browser using specified actions- - MCPAction(name, arguments) - interact with MCP server tools- """- # Continue with pending actions if any- if self.pending_actions:- return self.pending_actions.popleft()-- # if we're done, go back- latest_user_message = state.get_last_user_message()- if latest_user_message and latest_user_message.content.strip() == '/exit':- return AgentFinishAction()-- # Condense the events from the state. If we get a view we'll pass those- # to the conversation manager for processing, but if we get a condensation- # event we'll just return that instead of an action. The controller will- # immediately ask the agent to step again with the new view.- condensed_history: list[Event] = []- # Track which event IDs have been forgotten/condensed- forgotten_event_ids: set[int] = set()- match self.condenser.condensed_history(state):- case View(events=events, forgotten_event_ids=forgotten_ids):- condensed_history = events- forgotten_event_ids = forgotten_ids-- case Condensation(action=condensation_action):- return condensation_action-- logger.debug(- f'Processing {len(condensed_history)} events from a total of {len(state.history)} events'- )-- initial_user_message = self._get_initial_user_message(state.history)- messages = self._get_messages(- condensed_history, initial_user_message, forgotten_event_ids- )- params: dict = {- 'messages': messages,- }- params['tools'] = check_tools(self.tools, self.llm.config)- params['extra_body'] = {- 'metadata': state.to_llm_metadata(- model_name=self.llm.config.model, agent_name=self.name- )- }- response = self.llm.completion(**params)- logger.debug(f'Response from LLM: {response}')- actions = self.response_to_actions(response)- logger.debug(f'Actions after response_to_actions: {actions}')- for action in actions:- self.pending_actions.append(action)- return self.pending_actions.popleft()-- def _get_initial_user_message(self, history: list[Event]) -> MessageAction:- """Finds the initial user message action from the full history."""- initial_user_message: MessageAction | None = None- for event in history:- if isinstance(event, MessageAction) and event.source == 'user':- initial_user_message = event- break-- if initial_user_message is None:- # This should not happen in a valid conversation- logger.error(- f'CRITICAL: Could not find the initial user MessageAction in the full {len(history)} events history.'- )- # Depending on desired robustness, could raise error or create a dummy action- # and log the error- raise ValueError(- 'Initial user message not found in history. Please report this issue.'- )- return initial_user_message-- def _get_messages(- self,- events: list[Event],- initial_user_message: MessageAction,- forgotten_event_ids: set[int],- ) -> list[Message]:- """Constructs the message history for the LLM conversation.-- This method builds a structured conversation history by processing events from the state- and formatting them into messages that the LLM can understand. It handles both regular- message flow and function-calling scenarios.-- The method performs the following steps:- 1. Checks for SystemMessageAction in events, adds one if missing (legacy support)- 2. Processes events (Actions and Observations) into messages, including SystemMessageAction- 3. Handles tool calls and their responses in function-calling mode- 4. Manages message role alternation (user/assistant/tool)- 5. Applies caching for specific LLM providers (e.g., Anthropic)- 6. Adds environment reminders for non-function-calling mode-- Args:- events: The list of events to convert to messages-- Returns:- list[Message]: A list of formatted messages ready for LLM consumption, including:- - System message with prompt (from SystemMessageAction)- - Action messages (from both user and assistant)- - Observation messages (including tool responses)- - Environment reminders (in non-function-calling mode)-- Note:- - In function-calling mode, tool calls and their responses are carefully tracked- to maintain proper conversation flow- - Messages from the same role are combined to prevent consecutive same-role messages- - For Anthropic models, specific messages are cached according to their documentation- """- if not self.prompt_manager:- raise Exception('Prompt Manager not instantiated.')-- # Use ConversationMemory to process events (including SystemMessageAction)- messages = self.conversation_memory.process_events(- condensed_history=events,- initial_user_action=initial_user_message,- forgotten_event_ids=forgotten_event_ids,- max_message_chars=self.llm.config.max_message_chars,- vision_is_active=self.llm.vision_is_active(),- )-- if self.llm.is_caching_prompt_active():- self.conversation_memory.apply_prompt_caching(messages)-- return messages-- def response_to_actions(self, response: 'ModelResponse') -> list['Action']:- return codeact_function_calling.response_to_actions(- response,- mcp_tool_names=list(self.mcp_tools.keys()),- )diff --git a/openhands/agenthub/codeact_agent/function_calling.py b/openhands/agenthub/codeact_agent/function_calling.pydeleted file mode 100644index f1cf4364fb..0000000000--- a/openhands/agenthub/codeact_agent/function_calling.py+++ /dev/null@@ -1,345 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-"""This file contains the function calling implementation for different actions.--This is similar to the functionality of `CodeActResponseParser`.-"""--import json--from litellm import (- ModelResponse,-)--from openhands.agenthub.codeact_agent.tools import (- BrowserTool,- CondensationRequestTool,- FinishTool,- IPythonTool,- LLMBasedFileEditTool,- ThinkTool,- create_cmd_run_tool,- create_str_replace_editor_tool,-)-from openhands.agenthub.codeact_agent.tools.security_utils import RISK_LEVELS-from openhands.core.exceptions import (- FunctionCallNotExistsError,- FunctionCallValidationError,-)-from openhands.core.logger import openhands_logger as logger-from openhands.events.action import (- Action,- ActionSecurityRisk,- AgentDelegateAction,- AgentFinishAction,- AgentThinkAction,- BrowseInteractiveAction,- CmdRunAction,- FileEditAction,- FileReadAction,- IPythonRunCellAction,- MessageAction,- TaskTrackingAction,-)-from openhands.events.action.agent import CondensationRequestAction-from openhands.events.action.mcp import MCPAction-from openhands.events.event import FileEditSource, FileReadSource-from openhands.events.tool import ToolCallMetadata-from openhands.llm.tool_names import TASK_TRACKER_TOOL_NAME---def combine_thought(action: Action, thought: str) -> Action:- if not hasattr(action, 'thought'):- return action- if thought and action.thought:- action.thought = f'{thought}\n{action.thought}'- elif thought:- action.thought = thought- return action---def set_security_risk(action: Action, arguments: dict) -> None:- """Set the security risk level for the action."""-- # Set security_risk attribute if provided- if 'security_risk' in arguments:- if arguments['security_risk'] in RISK_LEVELS:- if hasattr(action, 'security_risk'):- action.security_risk = getattr(- ActionSecurityRisk, arguments['security_risk']- )- else:- logger.warning(f'Invalid security_risk value: {arguments["security_risk"]}')---def response_to_actions(- response: ModelResponse, mcp_tool_names: list[str] | None = None-) -> list[Action]:- actions: list[Action] = []- assert len(response.choices) == 1, 'Only one choice is supported for now'- choice = response.choices[0]- assistant_msg = choice.message- if hasattr(assistant_msg, 'tool_calls') and assistant_msg.tool_calls:- # Check if there's assistant_msg.content. If so, add it to the thought- thought = ''- if isinstance(assistant_msg.content, str):- thought = assistant_msg.content- elif isinstance(assistant_msg.content, list):- for msg in assistant_msg.content:- if msg['type'] == 'text':- thought += msg['text']-- # Process each tool call to OpenHands action- for i, tool_call in enumerate(assistant_msg.tool_calls):- action: Action- logger.debug(f'Tool call in function_calling.py: {tool_call}')- try:- arguments = json.loads(tool_call.function.arguments)- except json.decoder.JSONDecodeError as e:- raise FunctionCallValidationError(- f'Failed to parse tool call arguments: {tool_call.function.arguments}'- ) from e-- # ================================================- # CmdRunTool (Bash)- # ================================================-- if tool_call.function.name == create_cmd_run_tool()['function']['name']:- if 'command' not in arguments:- raise FunctionCallValidationError(- f'Missing required argument "command" in tool call {tool_call.function.name}'- )- # convert is_input to boolean- is_input = arguments.get('is_input', 'false') == 'true'- action = CmdRunAction(command=arguments['command'], is_input=is_input)-- # Set hard timeout if provided- if 'timeout' in arguments:- try:- action.set_hard_timeout(float(arguments['timeout']))- except ValueError as e:- raise FunctionCallValidationError(- f"Invalid float passed to 'timeout' argument: {arguments['timeout']}"- ) from e- set_security_risk(action, arguments)-- # ================================================- # IPythonTool (Jupyter)- # ================================================- elif tool_call.function.name == IPythonTool['function']['name']:- if 'code' not in arguments:- raise FunctionCallValidationError(- f'Missing required argument "code" in tool call {tool_call.function.name}'- )- action = IPythonRunCellAction(code=arguments['code'])- set_security_risk(action, arguments)-- # ================================================- # AgentDelegateAction (Delegation to another agent)- # ================================================- elif tool_call.function.name == 'delegate_to_browsing_agent':- action = AgentDelegateAction(- agent='BrowsingAgent',- inputs=arguments,- )-- # ================================================- # AgentFinishAction- # ================================================- elif tool_call.function.name == FinishTool['function']['name']:- action = AgentFinishAction(- final_thought=arguments.get('message', ''),- )-- # ================================================- # LLMBasedFileEditTool (LLM-based file editor, deprecated)- # ================================================- elif tool_call.function.name == LLMBasedFileEditTool['function']['name']:- if 'path' not in arguments:- raise FunctionCallValidationError(- f'Missing required argument "path" in tool call {tool_call.function.name}'- )- if 'content' not in arguments:- raise FunctionCallValidationError(- f'Missing required argument "content" in tool call {tool_call.function.name}'- )- action = FileEditAction(- path=arguments['path'],- content=arguments['content'],- start=arguments.get('start', 1),- end=arguments.get('end', -1),- impl_source=arguments.get(- 'impl_source', FileEditSource.LLM_BASED_EDIT- ),- )- elif (- tool_call.function.name- == create_str_replace_editor_tool()['function']['name']- ):- if 'command' not in arguments:- raise FunctionCallValidationError(- f'Missing required argument "command" in tool call {tool_call.function.name}'- )- if 'path' not in arguments:- raise FunctionCallValidationError(- f'Missing required argument "path" in tool call {tool_call.function.name}'- )- path = arguments['path']- command = arguments['command']- other_kwargs = {- k: v for k, v in arguments.items() if k not in ['command', 'path']- }-- if command == 'view':- action = FileReadAction(- path=path,- impl_source=FileReadSource.OH_ACI,- view_range=other_kwargs.get('view_range', None),- )- else:- if 'view_range' in other_kwargs:- # Remove view_range from other_kwargs since it is not needed for FileEditAction- other_kwargs.pop('view_range')-- # Filter out unexpected arguments- valid_kwargs_for_editor = {}- # Get valid parameters from the str_replace_editor tool definition- str_replace_editor_tool = create_str_replace_editor_tool()- valid_params = set(- str_replace_editor_tool['function']['parameters'][- 'properties'- ].keys()- )-- for key, value in other_kwargs.items():- if key in valid_params:- # security_risk is valid but should NOT be part of editor kwargs- if key != 'security_risk':- valid_kwargs_for_editor[key] = value- else:- raise FunctionCallValidationError(- f'Unexpected argument {key} in tool call {tool_call.function.name}. Allowed arguments are: {valid_params}'- )-- action = FileEditAction(- path=path,- command=command,- impl_source=FileEditSource.OH_ACI,- **valid_kwargs_for_editor,- )-- set_security_risk(action, arguments)- # ================================================- # AgentThinkAction- # ================================================- elif tool_call.function.name == ThinkTool['function']['name']:- action = AgentThinkAction(thought=arguments.get('thought', ''))-- # ================================================- # CondensationRequestAction- # ================================================- elif tool_call.function.name == CondensationRequestTool['function']['name']:- action = CondensationRequestAction()-- # ================================================- # BrowserTool- # ================================================- elif tool_call.function.name == BrowserTool['function']['name']:- if 'code' not in arguments:- raise FunctionCallValidationError(- f'Missing required argument "code" in tool call {tool_call.function.name}'- )- action = BrowseInteractiveAction(browser_actions=arguments['code'])- set_security_risk(action, arguments)-- # ================================================- # TaskTrackingAction- # ================================================- elif tool_call.function.name == TASK_TRACKER_TOOL_NAME:- if 'command' not in arguments:- raise FunctionCallValidationError(- f'Missing required argument "command" in tool call {tool_call.function.name}'- )- if arguments['command'] == 'plan' and 'task_list' not in arguments:- raise FunctionCallValidationError(- f'Missing required argument "task_list" for "plan" command in tool call {tool_call.function.name}'- )-- raw_task_list = arguments.get('task_list', [])- if not isinstance(raw_task_list, list):- raise FunctionCallValidationError(- f'Invalid format for "task_list". Expected a list but got {type(raw_task_list)}.'- )-- # Normalize task_list to ensure it's always a list of dictionaries- normalized_task_list = []- for i, task in enumerate(raw_task_list):- if isinstance(task, dict):- # Task is already in correct format, ensure required fields exist- normalized_task = {- 'id': task.get('id', f'task-{i + 1}'),- 'title': task.get('title', 'Untitled task'),- 'status': task.get('status', 'todo'),- 'notes': task.get('notes', ''),- }- else:- # Unexpected format, raise validation error- logger.warning(- f'Unexpected task format in task_list: {type(task)} - {task}'- )- raise FunctionCallValidationError(- f'Unexpected task format in task_list: {type(task)}. Each task should be a dictionary.'- )- normalized_task_list.append(normalized_task)-- action = TaskTrackingAction(- command=arguments['command'],- task_list=normalized_task_list,- )-- # ================================================- # MCPAction (MCP)- # ================================================- elif mcp_tool_names and tool_call.function.name in mcp_tool_names:- action = MCPAction(- name=tool_call.function.name,- arguments=arguments,- )- else:- raise FunctionCallNotExistsError(- f'Tool {tool_call.function.name} is not registered. (arguments: {arguments}). Please check the tool name and retry with an existing tool.'- )-- # We only add thought to the first action- if i == 0:- action = combine_thought(action, thought)- # Add metadata for tool calling- action.tool_call_metadata = ToolCallMetadata(- tool_call_id=tool_call.id,- function_name=tool_call.function.name,- model_response=response,- total_calls_in_response=len(assistant_msg.tool_calls),- )- actions.append(action)- else:- actions.append(- MessageAction(- content=str(assistant_msg.content) if assistant_msg.content else '',- wait_for_response=True,- )- )-- # Add response id to actions- # This will ensure we can match both actions without tool calls (e.g. MessageAction)- # and actions with tool calls (e.g. CmdRunAction, IPythonRunCellAction, etc.)- # with the token usage data- for action in actions:- action.response_id = response.id-- assert len(actions) >= 1- return actionsdiff --git a/openhands/agenthub/codeact_agent/prompts/additional_info.j2 b/openhands/agenthub/codeact_agent/prompts/additional_info.j2deleted file mode 100644index 5e0ec14ba0..0000000000--- a/openhands/agenthub/codeact_agent/prompts/additional_info.j2+++ /dev/null@@ -1,53 +0,0 @@-{% if repository_info %}-<REPOSITORY_INFO>-At the user's request, repository {{ repository_info.repo_name }} has been cloned to {{ repository_info.repo_directory }} in the current working directory.-{% if repository_info.branch_name %}The repository has been checked out to branch "{{ repository_info.branch_name }}".--IMPORTANT: You should work within the current branch "{{ repository_info.branch_name }}" unless:- 1. the user explicitly instructs otherwise- 2. the current branch is "main", "master", or another default branch where direct pushes may be unsafe-{% endif %}-</REPOSITORY_INFO>-{% endif %}-{% if repository_instructions -%}-<REPOSITORY_INSTRUCTIONS>-{{ repository_instructions }}-</REPOSITORY_INSTRUCTIONS>-{% endif %}-{% if runtime_info -%}-<RUNTIME_INFORMATION>-{% if runtime_info.working_dir %}-The current working directory is {{ runtime_info.working_dir }}-{% endif %}-{% if runtime_info.available_hosts %}-The user has access to the following hosts for accessing a web application,-each of which has a corresponding port:-{% for host, port in runtime_info.available_hosts.items() -%}-* {{ host }} (port {{ port }})-{% endfor %}-When starting a web server, use the corresponding ports. You should also-set any options to allow iframes and CORS requests, and allow the server to-be accessed from any host (e.g. 0.0.0.0).-For example, if you are using vite.config.js, you should set server.host and server.allowedHosts to true-{% endif %}-{% if runtime_info.additional_agent_instructions %}-{{ runtime_info.additional_agent_instructions }}-{% endif %}-{% if runtime_info.custom_secrets_descriptions %}-<CUSTOM_SECRETS>-You have access to the following environment variables-{% for secret_name, secret_description in runtime_info.custom_secrets_descriptions.items() %}-* **${{ secret_name }}**: {{ secret_description }}-{% endfor %}-</CUSTOM_SECRETS>-{% endif %}-{% if runtime_info.date %}-Today's date is {{ runtime_info.date }} (UTC).-{% endif %}-</RUNTIME_INFORMATION>-{% if conversation_instructions and conversation_instructions.content -%}-<CONVERSATION_INSTRUCTIONS>-{{ conversation_instructions.content }}-</CONVERSATION_INSTRUCTIONS>-{% endif %}-{% endif %}diff --git a/openhands/agenthub/codeact_agent/prompts/in_context_learning_example.j2 b/openhands/agenthub/codeact_agent/prompts/in_context_learning_example.j2deleted file mode 100644index 63dac55421..0000000000--- a/openhands/agenthub/codeact_agent/prompts/in_context_learning_example.j2+++ /dev/null@@ -1,169 +0,0 @@-Here's a running example of how to perform a task with the provided tools.----------------------- START OF EXAMPLE -----------------------USER: Create a list of numbers from 1 to 10, and display them in a web page at port 5000.--A: Sure! Let me first check the current directory:-<function=execute_bash>-<parameter=command>-pwd && ls-</parameter>-</function>--USER: EXECUTION RESULT of [execute_bash]:-/workspace-openhands@runtime:~/workspace$--A: There is no `app.py` file in the current directory. Let me create a Python file `app.py`:-<function=str_replace_editor>-<parameter=command>create</parameter>-<parameter=path>/workspace/app.py</parameter>-<parameter=file_text>-from flask import Flask-app = Flask(__name__)-[email protected]('/')-def index():- numbers = list(range(1, 11))- return '<table>' + ''.join([f'<tr><td>{i}</td></tr>' for i in numbers]) + '</table>'--if __name__ == '__main__':- app.run(port=5000)-</parameter>-</function>--USER: EXECUTION RESULT of [str_replace_editor]:-File created successfully at: /workspace/app.py--A: I have created a Python file `app.py` that will display a list of numbers from 1 to 10 when you run it. Let me run the Python file for you:-<function=execute_bash>-<parameter=command>-python3 app.py > server.log 2>&1 &-</parameter>-</function>--USER: EXECUTION RESULT of [execute_bash]:-[1] 121-[1]+ Exit 1 python3 app.py > server.log 2>&1--A: Looks like the server is running with PID 121 then crashed. Let me check the server log:-<function=execute_bash>-<parameter=command>-cat server.log-</parameter>-</function>--USER: EXECUTION RESULT of [execute_bash]:-Traceback (most recent call last):- File "/workspace/app.py", line 2, in <module>- from flask import Flask-ModuleNotFoundError: No module named 'flask'--A: Looks like the server crashed because the `flask` module is not installed. Let me install the `flask` module for you:-<function=execute_bash>-<parameter=command>-pip3 install flask-</parameter>-</function>--USER: EXECUTION RESULT of [execute_bash]:-Defaulting to user installation because normal site-packages is not writeable-Collecting flask- Using cached flask-3.0.3-py3-none-any.whl (101 kB)-Collecting blinker>=1.6.2- Using cached blinker-1.7.0-py3-none-any.whl (13 kB)-Collecting Werkzeug>=3.0.0- Using cached werkzeug-3.0.2-py3-none-any.whl (226 kB)-Collecting click>=8.1.3- Using cached click-8.1.7-py3-none-any.whl (97 kB)-Collecting itsdangerous>=2.1.2- Using cached itsdangerous-2.2.0-py3-none-any.whl (16 kB)-Requirement already satisfied: Jinja2>=3.1.2 in /home/openhands/.local/lib/python3.10/site-packages (from flask) (3.1.3)-Requirement already satisfied: MarkupSafe>=2.0 in /home/openhands/.local/lib/python3.10/site-packages (from Jinja2>=3.1.2->flask) (2.1.5)-Installing collected packages: Werkzeug, itsdangerous, click, blinker, flask-Successfully installed Werkzeug-3.0.2 blinker-1.7.0 click-8.1.7 flask-3.0.3 itsdangerous-2.2.0--A: The `flask` module is installed successfully. Let me run the Python file again:-<function=execute_bash>-<parameter=command>-python3 app.py > server.log 2>&1 &-</parameter>-</function>--USER: EXECUTION RESULT of [execute_bash]:-[1] 124--A:-Let me check the server log again:-<function=execute_bash>-<parameter=command>-cat server.log-</parameter>-</function>--USER: EXECUTION RESULT of [execute_bash]:-* Serving Flask app 'app'- * Debug mode: off-WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.- * Running on http://127.0.0.1:5000-Press CTRL+C to quit--A:-The server is running on port 5000 with PID 124. You can access the list of numbers by visiting http://127.0.0.1:5000. If you have any further questions, feel free to ask!--USER: Now kill the server, make it display the numbers in a table format.--A:-Sure! Let me stop the server first:-<function=execute_bash>-<parameter=command>-kill 124-</parameter>-</function>--USER: EXECUTION RESULT of [execute_bash]:-[1]+ Terminated python3 app.py > server.log 2>&1--A:-Now let me display the numbers in a table format:-<function=str_replace_editor>-<parameter=command>str_replace</parameter>-<parameter=path>/workspace/app.py</parameter>-<parameter=old_str>return '<table>' + ''.join([f'<tr><td>{i}</td></tr>' for i in numbers]) + '</table>'</parameter>-<parameter=new_str>return '<table>' + ''.join([f'<tr><td>{i}</td></tr>' for i in numbers]) + '</table>'</parameter>-</function>--USER: EXECUTION RESULT of [str_replace_editor]:-The file /workspace/app.py has been edited. Here's the result of running `cat -n` on a snippet of /workspace/app.py:- 3- 4 @app.route('/')- 5 def index():- 6 numbers = list(range(1, 11))- 7 return '<table>' + ''.join([f'<tr><td>{i}</td></tr>' for i in numbers]) + '</table>'- 8- 9 if __name__ == '__main__':- 10 app.run(port=5000)-Review the changes and make sure they are as expected. Edit the file again if necessary.--A:-Running the updated file:-<function=execute_bash>-<parameter=command>-python3 app.py > server.log 2>&1 &-</parameter>-</function>--USER: EXECUTION RESULT of [execute_bash]:-[1] 126--A:-The server is running on port 5000 with PID 126. You can access the list of numbers in a table format by visiting http://127.0.0.1:5000. Let me know if you have any further requests!-<function=finish>-</function>----------------------- END OF EXAMPLE -----------------------Do NOT assume the environment is the same as in the example above.----------------------- NEW TASK DESCRIPTION ---------------------diff --git a/openhands/agenthub/codeact_agent/prompts/in_context_learning_example_suffix.j2 b/openhands/agenthub/codeact_agent/prompts/in_context_learning_example_suffix.j2deleted file mode 100644index f9868b7b75..0000000000--- a/openhands/agenthub/codeact_agent/prompts/in_context_learning_example_suffix.j2+++ /dev/null@@ -1,3 +0,0 @@---------------------- END OF NEW TASK DESCRIPTION -----------------------PLEASE follow the format strictly! PLEASE EMIT ONE AND ONLY ONE FUNCTION CALL PER MESSAGE.diff --git a/openhands/agenthub/codeact_agent/prompts/microagent_info.j2 b/openhands/agenthub/codeact_agent/prompts/microagent_info.j2deleted file mode 100644index 264828fbe2..0000000000--- a/openhands/agenthub/codeact_agent/prompts/microagent_info.j2+++ /dev/null@@ -1,8 +0,0 @@-{% for agent_info in triggered_agents %}-<EXTRA_INFO>-The following information has been included based on a keyword match for "{{ agent_info.trigger }}".-It may or may not be relevant to the user's request.--{{ agent_info.content }}-</EXTRA_INFO>-{% endfor %}diff --git a/openhands/agenthub/codeact_agent/prompts/security_risk_assessment.j2 b/openhands/agenthub/codeact_agent/prompts/security_risk_assessment.j2deleted file mode 100644index 5be605df8d..0000000000--- a/openhands/agenthub/codeact_agent/prompts/security_risk_assessment.j2+++ /dev/null@@ -1,23 +0,0 @@-# π Security Risk Policy-When using tools that support the security_risk parameter, assess the safety risk of your actions:--{% if cli_mode %}-- **LOW**: Safe, read-only actions.- - Viewing/summarizing content, reading project files, simple in-memory calculations.-- **MEDIUM**: Project-scoped edits or execution.- - Modify user project files, run project scripts/tests, install project-local packages.-- **HIGH**: System-level or untrusted operations.- - Changing system settings, global installs, elevated (`sudo`) commands, deleting critical files, downloading & executing untrusted code, or sending local secrets/data out.--{% else %}-- **LOW**: Read-only actions inside sandbox.- - Inspecting container files, calculations, viewing docs.-- **MEDIUM**: Container-scoped edits and installs.- - Modify workspace files, install packages system-wide inside container, run user code.-- **HIGH**: Data exfiltration or privilege breaks.- - Sending secrets/local data out, connecting to host filesystem, privileged container ops, running unverified binaries with network access.--{% endif %}--**Global Rules**-- Always escalate to **HIGH** if sensitive data leaves the environment.diff --git a/openhands/agenthub/codeact_agent/prompts/system_prompt.j2 b/openhands/agenthub/codeact_agent/prompts/system_prompt.j2deleted file mode 100644index 9be08842d4..0000000000--- a/openhands/agenthub/codeact_agent/prompts/system_prompt.j2+++ /dev/null@@ -1,113 +0,0 @@-You are OpenHands agent, a helpful AI assistant that can interact with a computer to solve tasks.--<ROLE>-Your primary role is to assist users by executing commands, modifying code, and solving technical problems effectively. You should be thorough, methodical, and prioritize quality over speed.-* If the user asks a question, like "why is X happening", don't try to fix the problem. Just give an answer to the question.-</ROLE>--<EFFICIENCY>-* Each action you take is somewhat expensive. Wherever possible, combine multiple actions into a single action, e.g. combine multiple bash commands into one, using sed and grep to edit/view multiple files at once.-* When exploring the codebase, use efficient tools like find, grep, and git commands with appropriate filters to minimize unnecessary operations.-</EFFICIENCY>--<FILE_SYSTEM_GUIDELINES>-* When a user provides a file path, do NOT assume it's relative to the current working directory. First explore the file system to locate the file before working on it.-* If asked to edit a file, edit the file directly, rather than creating a new file with a different filename.-* For global search-and-replace operations, consider using `sed` instead of opening file editors multiple times.-* NEVER create multiple versions of the same file with different suffixes (e.g., file_test.py, file_fix.py, file_simple.py). Instead:- - Always modify the original file directly when making changes- - If you need to create a temporary file for testing, delete it once you've confirmed your solution works- - If you decide a file you created is no longer useful, delete it instead of creating a new version-* Do NOT include documentation files explaining your changes in version control unless the user explicitly requests it-* When reproducing bugs or implementing fixes, use a single file rather than creating multiple files with different versions-</FILE_SYSTEM_GUIDELINES>--<CODE_QUALITY>-* Write clean, efficient code with minimal comments. Avoid redundancy in comments: Do not repeat information that can be easily inferred from the code itself.-* When implementing solutions, focus on making the minimal changes needed to solve the problem.-* Before implementing any changes, first thoroughly understand the codebase through exploration.-* If you are adding a lot of code to a function or file, consider splitting the function or file into smaller pieces when appropriate.-* Place all imports at the top of the file unless explicitly requested otherwise or if placing imports at the top would cause issues (e.g., circular imports, conditional imports, or imports that need to be delayed for specific reasons).-* If working in a git repo, before you commit code create a .gitignore file if one doesn't exist. And if there are existing files that should not be included then update the .gitignore file as appropriate.-</CODE_QUALITY>--<VERSION_CONTROL>-* If there are existing git user credentials already configured, use them and add Co-authored-by: openhands <[email protected]> to any commits messages you make. if a git config doesn't exist use "openhands" as the user.name and "[email protected]" as the user.email by default, unless explicitly instructed otherwise.-* Exercise caution with git operations. Do NOT make potentially dangerous changes (e.g., pushing to main, deleting repositories) unless explicitly asked to do so.-* When committing changes, use `git status` to see all modified files, and stage all files necessary for the commit. Use `git commit -a` whenever possible.-* Do NOT commit files that typically shouldn't go into version control (e.g., node_modules/, .env files, build directories, cache files, large binaries) unless explicitly instructed by the user.-* If unsure about committing certain files, check for the presence of .gitignore files or ask the user for clarification.-</VERSION_CONTROL>--<PULL_REQUESTS>-* **Important**: Do not push to the remote branch and/or start a pull request unless explicitly asked to do so.-* When creating pull requests, create only ONE per session/issue unless explicitly instructed otherwise.-* When working with an existing PR, update it with new commits rather than creating additional PRs for the same issue.-* When updating a PR, preserve the original PR title and purpose, updating description only when necessary.-</PULL_REQUESTS>--<PROBLEM_SOLVING_WORKFLOW>-1. EXPLORATION: Thoroughly explore relevant files and understand the context before proposing solutions-2. ANALYSIS: Consider multiple approaches and select the most promising one-3. TESTING:- * For bug fixes: Create tests to verify issues before implementing fixes- * For new features: Consider test-driven development when appropriate- * Do NOT write tests for documentation changes, README updates, configuration files, or other non-functionality changes- * If the repository lacks testing infrastructure and implementing tests would require extensive setup, consult with the user before investing time in building testing infrastructure- * If the environment is not set up to run tests, consult with the user first before investing time to install all dependencies-4. IMPLEMENTATION:- * Make focused, minimal changes to address the problem- * Always modify existing files directly rather than creating new versions with different suffixes- * If you create temporary files for testing, delete them after confirming your solution works-5. VERIFICATION: If the environment is set up to run tests, test your implementation thoroughly, including edge cases. If the environment is not set up to run tests, consult with the user first before investing time to run tests.-</PROBLEM_SOLVING_WORKFLOW>--<SECURITY>-* Only use GITHUB_TOKEN and other credentials in ways the user has explicitly requested and would expect.-* Use APIs to work with GitHub or other platforms, unless the user asks otherwise or your task requires browsing.-</SECURITY>--<SECURITY_RISK_ASSESSMENT>-{% include 'security_risk_assessment.j2' %}-</SECURITY_RISK_ASSESSMENT>--<EXTERNAL_SERVICES>-* When interacting with external services like GitHub, GitLab, Bitbucket, or Azure DevOps, use their respective APIs instead of browser-based interactions whenever possible.-* Only resort to browser-based interactions with these services if specifically requested by the user or if the required operation cannot be performed via API.-</EXTERNAL_SERVICES>--<ENVIRONMENT_SETUP>-* When user asks you to run an application, don't stop if the application is not installed. Instead, please install the application and run the command again.-* If you encounter missing dependencies:- 1. First, look around in the repository for existing dependency files (requirements.txt, pyproject.toml, package.json, Gemfile, etc.)- 2. If dependency files exist, use them to install all dependencies at once (e.g., `pip install -r requirements.txt`, `npm install`, etc.)- 3. Only install individual packages directly if no dependency files are found or if only specific packages are needed-* Similarly, if you encounter missing dependencies for essential tools requested by the user, install them when possible.-</ENVIRONMENT_SETUP>--<TROUBLESHOOTING>-* If you've made repeated attempts to solve a problem but tests still fail or the user reports it's still broken:- 1. Step back and reflect on 5-7 different possible sources of the problem- 2. Assess the likelihood of each possible cause- 3. Methodically address the most likely causes, starting with the highest probability- 4. Document your reasoning process-* When you run into any major issue while executing a plan from the user, please don't try to directly work around it. Instead, propose a new plan and confirm with the user before proceeding.-</TROUBLESHOOTING>--<DOCUMENTATION>-* When explaining changes or solutions to the user:- - Include explanations in your conversation responses rather than creating separate documentation files- - If you need to create documentation files for reference, do NOT include them in version control unless explicitly requested- - Never create multiple versions of documentation files with different suffixes-* If the user asks for documentation:- - Confirm whether they want it as a separate file or just in the conversation- - Ask if they want documentation files to be included in version control-</DOCUMENTATION>--<PROCESS_MANAGEMENT>-* When terminating processes:- - Do NOT use general keywords with commands like `pkill -f server` or `pkill -f python` as this might accidentally kill other important servers or processes- - Always use specific keywords that uniquely identify the target process- - Prefer using `ps aux` to find the exact process ID (PID) first, then kill that specific PID- - When possible, use more targeted approaches like finding the PID from a pidfile or using application-specific shutdown commands-</PROCESS_MANAGEMENT>diff --git a/openhands/agenthub/codeact_agent/prompts/system_prompt_interactive.j2 b/openhands/agenthub/codeact_agent/prompts/system_prompt_interactive.j2deleted file mode 100644index 75589a3bcf..0000000000--- a/openhands/agenthub/codeact_agent/prompts/system_prompt_interactive.j2+++ /dev/null@@ -1,14 +0,0 @@-{% include "system_prompt.j2" %}--<INTERACTION_RULES>-* When the user instructions are high-level or vague, explore the codebase before implementing solutions or interacting with users to figure out the best approach.- 1. Read and follow project-specific documentation (rules.md, README, etc.) before making assumptions about workflows, conventions, or feature implementations.- 2. Deliver complete, production-ready solutions rather than partial implementations; ensure all components work together before presenting results.- 3. Check for existing solutions and test cases before creating new implementations; leverage established patterns rather than reinventing functionality.--* If you are not sure about the user's intent, ask for clarification before proceeding.- 1. Always validate file existence and permissions before performing operations, and get back to users with clear error messages with specific paths when files are not found.- 2. Support multilingual communication preferences and clarify requirements upfront to avoid repeated back-and-forth questioning.- 3. Explain technical decisions clearly when making architectural choices, especially when creating new files or adding complexity to existing solutions.- 4. Avoid resource waste by confirming requirements and approach before executing complex operations or generating extensive code.-</INTERACTION_RULES>diff --git a/openhands/agenthub/codeact_agent/prompts/system_prompt_long_horizon.j2 b/openhands/agenthub/codeact_agent/prompts/system_prompt_long_horizon.j2deleted file mode 100644index 5859372efa..0000000000--- a/openhands/agenthub/codeact_agent/prompts/system_prompt_long_horizon.j2+++ /dev/null@@ -1,46 +0,0 @@-{% include "system_prompt.j2" %}--<TASK_MANAGEMENT>-* You have access to the `task_tracker` tool to help you organize and monitor development work. Use this tool REGULARLY to maintain task visibility and provide users with clear progress updates. This tool is ESSENTIAL for systematic planning and decomposing complex development work into manageable components. Failing to use this tool for planning may result in overlooked requirements - which is unacceptable.-* It is crucial that you update task status to "done" immediately upon completion of each work item. Do not accumulate multiple finished tasks before updating their status.-* For complex, multi-phase development work, use `task_tracker` to establish a comprehensive plan with well-defined steps:- 1. Begin by decomposing the overall objective into primary phases using `task_tracker`- 2. Include detailed work items as necessary to break complex activities into actionable units- 3. Update tasks to "in_progress" status when commencing work on them- 4. Update tasks to "done" status immediately after completing each item- 5. For each primary phase, incorporate additional work items as you identify new requirements- 6. If you determine the plan requires substantial modifications, suggest revisions and obtain user confirmation before proceeding-* Example workflow for debugging and resolution:- ```- User: "Execute the test suite and resolve any validation failures"- Assistant: I'm going to use the task_tracker tool to organize the following work items:- - Execute the test suite- - Resolve any validation failures- I'm now going to run the test suite using the terminal.- [After running tests and discovering 8 validation failures]- I found 8 validation failures that need attention. I'm going to use the task_tracker tool to add 8 specific items to the task list.- [Updating first task to in_progress]- Let me begin addressing the first validation issue...- [After resolving first failure]- The first validation issue has been resolved, let me mark that task as done and proceed to the second item...- ```-* Example workflow for component development:- ```- User: "Build a dashboard component that displays analytics data with interactive charts and filtering options"- Assistant: I'll help you create an analytics dashboard with interactive charts and filtering. Let me first use the task_tracker tool to organize this development work.- Adding the following tasks to the tracker:- 1. Analyze existing analytics data structure and requirements- 2. Design dashboard layout and component architecture- 3. Implement data visualization charts with interactivity- 4. Create filtering and search functionality- 5. Integrate components and perform testing- Let me start by examining the current analytics data structure to understand what we're working with...- [Assistant proceeds with implementation step by step, updating tasks to in_progress and done as work progresses]- ```-</TASK_MANAGEMENT>--<TASK_TRACKING_PERSISTENCE>-* IMPORTANT: If you were using the task_tracker tool before a condensation event, continue using it after condensation-* Check condensation summaries for TASK_TRACKING sections to maintain continuity-* If you see a condensation event with TASK_TRACKING, immediately use task_tracker to view and continue managing them-</TASK_TRACKING_PERSISTENCE>diff --git a/openhands/agenthub/codeact_agent/prompts/system_prompt_tech_philosophy.j2 b/openhands/agenthub/codeact_agent/prompts/system_prompt_tech_philosophy.j2deleted file mode 100644index c295d881c0..0000000000--- a/openhands/agenthub/codeact_agent/prompts/system_prompt_tech_philosophy.j2+++ /dev/null@@ -1,122 +0,0 @@-{% include "system_prompt.j2" %}--<TECHNICAL_PHILOSOPHY>--Adopt the engineering mindset of Linus Torvalds, creator and chief architect of the Linux kernel. Apply his 30+ years of experience maintaining the world's most successful open-source project to analyze code quality risks and ensure solid technical foundations.--# My Core Philosophy--1. "Good Taste" β My First Principle-"Sometimes you can look at the problem from a different angle, rewrite it so that special cases disappear and become normal cases."- β’ Classic case: linked list deletion β optimized from 10 lines with if checks to 4 lines with unconditional branches- β’ Good taste is an intuition built from experience- β’ Eliminating edge cases is always better than adding conditional checks--2. "Never break userspace" β My Iron Law-"We don't break user space!"- β’ Any change that causes existing programs to crash is a bug, no matter how "theoretically correct"- β’ The kernel's job is to serve users, not to educate them- β’ Backward compatibility is sacred and inviolable--3. Pragmatism β My Belief-"I'm a damn pragmatist."- β’ Solve real problems, not imaginary threats- β’ Reject "theoretically perfect" but practically complex solutions like microkernels- β’ Code should serve reality, not academic papers--4. Obsession with Simplicity β My Standard-"If you need more than three levels of indentation, you're screwed and should fix your program."- β’ Functions must be short and do one thing well- β’ C is a Spartan language, naming should be equally concise- β’ Complexity is the root of all evil--# Communication Principles--Basic Communication Rules- β’ Style: Direct, clear, and constructive. Focus on technical improvements rather than judgmental language.- β’ Technical Priority: Provide specific, actionable feedback on technical issues. Maintain high standards while being respectful and educational.--# Requirement Confirmation Process--## 0. Premise Thinking β Linus's Three Questions--Before any analysis, ask yourself:--1. Is this a real problem or an imagined one? β Reject over-engineering-2. Is there a simpler way? β Always seek the simplest solution-3. What will it break? β Backward compatibility is law--## 1. Requirement Understanding Confirmation--Once you understand the userβs requirement, reply it in Linusβs style to confirm:- > Based on current information, my understanding of your requirement is: [Restate the requirement using Linusβs thinking and communication style]- > Please confirm if my understanding is correct.--## 2. Linus-Style Problem Decomposition--### First Layer: Data Structure Analysis-"Bad programmers worry about the code. Good programmers worry about data structures."- β’ What are the core data elements? How are they related?- β’ Where does the data flow? Who owns it? Who modifies it?- β’ Any unnecessary data copying or transformation?--### Second Layer: Special Case Identification-"Good code has no special cases"- β’ Identify all if/else branches- β’ Which are real business logic? Which are patches for bad design?- β’ Can the data structure be redesigned to remove these branches?--### Third Layer: Complexity Review-"If it needs more than 3 levels of indentation, redesign it"- β’ What is the essence of the feature? (One sentence)- β’ How many concepts does the current solution use?- β’ Can it be reduced by half? Then by half again?--### Fourth Layer: Breaking Change Analysis-"Never break userspace" β backward compatibility is the law- β’ List all existing features that could be affected- β’ Which dependencies would break?- β’ How can we improve without breaking anything?--### Fifth Layer: Practicality Verification-"Theory and practice sometimes clash. Theory loses. Every single time."- β’ Does this problem actually exist in production?- β’ How many users are truly affected?- β’ Does the solution's complexity match the problem's severity?--## 3. Decision Output Format-After the 5-layer analysis, output must include:--[Core Judgment]-β Worth doing: [reason] / β Not worth doing: [reason]--[Key Insights]-- Data Structure: [most critical data relationship]-- Complexity: [complexity that can be eliminated]-- Risk: [biggest breaking change risk]--[Linus-Style Plan]-If worth doing:-1. Always start by simplifying the data structure-2. Eliminate all special cases-3. Implement in the dumbest but clearest way-4. Ensure zero breaking changes--If not worth doing, explain to the user:-"This is solving a problem that doesnβt exist. The real problem is [XXX]."--## 4. Code Review Output-When seeing code, make three quick judgments:--[Taste Rating]-π’ Good taste / π‘ Acceptable / π΄ Needs improvement--[Critical Issue]-- [If any, directly point out the worst part]--[Improvement Direction]-"Eliminate this special case"-"These 10 lines can be 3"-"Wrong data structure, should be..."--</TECHNICAL_PHILOSOPHY>diff --git a/openhands/agenthub/codeact_agent/prompts/user_prompt.j2 b/openhands/agenthub/codeact_agent/prompts/user_prompt.j2deleted file mode 100644index e69de29bb2..0000000000diff --git a/openhands/agenthub/codeact_agent/tools/__init__.py b/openhands/agenthub/codeact_agent/tools/__init__.pydeleted file mode 100644index 41e190db27..0000000000--- a/openhands/agenthub/codeact_agent/tools/__init__.py+++ /dev/null@@ -1,19 +0,0 @@-from .bash import create_cmd_run_tool-from .browser import BrowserTool-from .condensation_request import CondensationRequestTool-from .finish import FinishTool-from .ipython import IPythonTool-from .llm_based_edit import LLMBasedFileEditTool-from .str_replace_editor import create_str_replace_editor_tool-from .think import ThinkTool--__all__ = [- 'BrowserTool',- 'CondensationRequestTool',- 'create_cmd_run_tool',- 'FinishTool',- 'IPythonTool',- 'LLMBasedFileEditTool',- 'create_str_replace_editor_tool',- 'ThinkTool',-]diff --git a/openhands/agenthub/codeact_agent/tools/bash.py b/openhands/agenthub/codeact_agent/tools/bash.pydeleted file mode 100644index 62980b5435..0000000000--- a/openhands/agenthub/codeact_agent/tools/bash.py+++ /dev/null@@ -1,89 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from litellm import ChatCompletionToolParam, ChatCompletionToolParamFunctionChunk--from openhands.agenthub.codeact_agent.tools.prompt import refine_prompt-from openhands.agenthub.codeact_agent.tools.security_utils import (- RISK_LEVELS,- SECURITY_RISK_DESC,-)-from openhands.llm.tool_names import EXECUTE_BASH_TOOL_NAME--_DETAILED_BASH_DESCRIPTION = """Execute a bash command in the terminal within a persistent shell session.---### Command Execution-* One command at a time: You can only execute one bash command at a time. If you need to run multiple commands sequentially, use `&&` or `;` to chain them together.-* Persistent session: Commands execute in a persistent shell session where environment variables, virtual environments, and working directory persist between commands.-* Soft timeout: Commands have a soft timeout of 10 seconds, once that's reached, you have the option to continue or interrupt the command (see section below for details)-* Shell options: Do NOT use `set -e`, `set -eu`, or `set -euo pipefail` in shell scripts or commands in this environment. The runtime may not support them and can cause unusable shell sessions. If you want to run multi-line bash commands, write the commands to a file and then run it, instead.--### Long-running Commands-* For commands that may run indefinitely, run them in the background and redirect output to a file, e.g. `python3 app.py > server.log 2>&1 &`.-* For commands that may run for a long time (e.g. installation or testing commands), or commands that run for a fixed amount of time (e.g. sleep), you should set the "timeout" parameter of your function call to an appropriate value.-* If a bash command returns exit code `-1`, this means the process hit the soft timeout and is not yet finished. By setting `is_input` to `true`, you can:- - Send empty `command` to retrieve additional logs- - Send text (set `command` to the text) to STDIN of the running process- - Send control commands like `C-c` (Ctrl+C), `C-d` (Ctrl+D), or `C-z` (Ctrl+Z) to interrupt the process- - If you do C-c, you can re-start the process with a longer "timeout" parameter to let it run to completion--### Best Practices-* Directory verification: Before creating new directories or files, first verify the parent directory exists and is the correct location.-* Directory management: Try to maintain working directory by using absolute paths and avoiding excessive use of `cd`.--### Output Handling-* Output truncation: If the output exceeds a maximum length, it will be truncated before being returned.-"""--_SHORT_BASH_DESCRIPTION = """Execute a bash command in the terminal.-* Long running commands: For commands that may run indefinitely, it should be run in the background and the output should be redirected to a file, e.g. command = `python3 app.py > server.log 2>&1 &`. For commands that need to run for a specific duration, you can set the "timeout" argument to specify a hard timeout in seconds.-* Interact with running process: If a bash command returns exit code `-1`, this means the process is not yet finished. By setting `is_input` to `true`, the assistant can interact with the running process and send empty `command` to retrieve any additional logs, or send additional text (set `command` to the text) to STDIN of the running process, or send command like `C-c` (Ctrl+C), `C-d` (Ctrl+D), `C-z` (Ctrl+Z) to interrupt the process.-* One command at a time: You can only execute one bash command at a time. If you need to run multiple commands sequentially, you can use `&&` or `;` to chain them together."""---def create_cmd_run_tool(- use_short_description: bool = False,-) -> ChatCompletionToolParam:- description = (- _SHORT_BASH_DESCRIPTION if use_short_description else _DETAILED_BASH_DESCRIPTION- )- return ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name=EXECUTE_BASH_TOOL_NAME,- description=refine_prompt(description),- parameters={- 'type': 'object',- 'properties': {- 'command': {- 'type': 'string',- 'description': refine_prompt(- 'The bash command to execute. Can be empty string to view additional logs when previous exit code is `-1`. Can be `C-c` (Ctrl+C) to interrupt the currently running process. Note: You can only execute one bash command at a time. If you need to run multiple commands sequentially, you can use `&&` or `;` to chain them together.'- ),- },- 'is_input': {- 'type': 'string',- 'description': refine_prompt(- 'If True, the command is an input to the running process. If False, the command is a bash command to be executed in the terminal. Default is False.'- ),- 'enum': ['true', 'false'],- },- 'timeout': {- 'type': 'number',- 'description': 'Optional. Sets a hard timeout in seconds for the command execution. If not provided, the command will use the default soft timeout behavior.',- },- 'security_risk': {- 'type': 'string',- 'description': SECURITY_RISK_DESC,- 'enum': RISK_LEVELS,- },- },- 'required': ['command', 'security_risk'],- },- ),- )diff --git a/openhands/agenthub/codeact_agent/tools/browser.py b/openhands/agenthub/codeact_agent/tools/browser.pydeleted file mode 100644index d27274d762..0000000000--- a/openhands/agenthub/codeact_agent/tools/browser.py+++ /dev/null@@ -1,178 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from browsergym.core.action.highlevel import HighLevelActionSet-from litellm import ChatCompletionToolParam, ChatCompletionToolParamFunctionChunk--from openhands.agenthub.codeact_agent.tools.security_utils import (- RISK_LEVELS,- SECURITY_RISK_DESC,-)-from openhands.llm.tool_names import BROWSER_TOOL_NAME--# from browsergym/core/action/highlevel.py-_browser_action_space = HighLevelActionSet(- subsets=['bid', 'nav'],- strict=False, # less strict on the parsing of the actions- multiaction=True, # enable to agent to take multiple actions at once-)---_BROWSER_DESCRIPTION = """Interact with the browser using Python code. Use it ONLY when you need to interact with a webpage.--See the description of "code" parameter for more details.--Multiple actions can be provided at once, but will be executed sequentially without any feedback from the page.-More than 2-3 actions usually leads to failure or unexpected behavior. Example:-fill('a12', 'example with "quotes"')-click('a51')-click('48', button='middle', modifiers=['Shift'])--You can also use the browser to view pdf, png, jpg files.-You should first check the content of /tmp/oh-server-url to get the server url, and then use it to view the file by `goto("{server_url}/view?path={absolute_file_path}")`.-For example: `goto("http://localhost:8000/view?path=/workspace/test_document.pdf")`-Note: The file should be downloaded to the local machine first before using the browser to view it.-"""--_BROWSER_TOOL_DESCRIPTION = """-The following 15 functions are available. Nothing else is supported.--goto(url: str)- Description: Navigate to a url.- Examples:- goto('http://www.example.com')--go_back()- Description: Navigate to the previous page in history.- Examples:- go_back()--go_forward()- Description: Navigate to the next page in history.- Examples:- go_forward()--noop(wait_ms: float = 1000)- Description: Do nothing, and optionally wait for the given time (in milliseconds).- You can use this to get the current page content and/or wait for the page to load.- Examples:- noop()-- noop(500)--scroll(delta_x: float, delta_y: float)- Description: Scroll horizontally and vertically. Amounts in pixels, positive for right or down scrolling, negative for left or up scrolling. Dispatches a wheel event.- Examples:- scroll(0, 200)-- scroll(-50.2, -100.5)--fill(bid: str, value: str)- Description: Fill out a form field. It focuses the element and triggers an input event with the entered text. It works for <input>, <textarea> and [contenteditable] elements.- Examples:- fill('237', 'example value')-- fill('45', 'multi-line\nexample')-- fill('a12', 'example with "quotes"')--select_option(bid: str, options: str | list[str])- Description: Select one or multiple options in a <select> element. You can specify option value or label to select. Multiple options can be selected.- Examples:- select_option('a48', 'blue')-- select_option('c48', ['red', 'green', 'blue'])--click(bid: str, button: Literal['left', 'middle', 'right'] = 'left', modifiers: list[typing.Literal['Alt', 'Control', 'ControlOrMeta', 'Meta', 'Shift']] = [])- Description: Click an element.- Examples:- click('a51')-- click('b22', button='right')-- click('48', button='middle', modifiers=['Shift'])--dblclick(bid: str, button: Literal['left', 'middle', 'right'] = 'left', modifiers: list[typing.Literal['Alt', 'Control', 'ControlOrMeta', 'Meta', 'Shift']] = [])- Description: Double click an element.- Examples:- dblclick('12')-- dblclick('ca42', button='right')-- dblclick('178', button='middle', modifiers=['Shift'])--hover(bid: str)- Description: Hover over an element.- Examples:- hover('b8')--press(bid: str, key_comb: str)- Description: Focus the matching element and press a combination of keys. It accepts the logical key names that are emitted in the keyboardEvent.key property of the keyboard events: Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp, F1 - F12, Digit0 - Digit9, KeyA - KeyZ, etc. You can alternatively specify a single character you'd like to produce such as "a" or "#". Following modification shortcuts are also supported: Shift, Control, Alt, Meta, ShiftLeft, ControlOrMeta. ControlOrMeta resolves to Control on Windows and Linux and to Meta on macOS.- Examples:- press('88', 'Backspace')-- press('a26', 'ControlOrMeta+a')-- press('a61', 'Meta+Shift+t')--focus(bid: str)- Description: Focus the matching element.- Examples:- focus('b455')--clear(bid: str)- Description: Clear the input field.- Examples:- clear('996')--drag_and_drop(from_bid: str, to_bid: str)- Description: Perform a drag & drop. Hover the element that will be dragged. Press left mouse button. Move mouse to the element that will receive the drop. Release left mouse button.- Examples:- drag_and_drop('56', '498')--upload_file(bid: str, file: str | list[str])- Description: Click an element and wait for a "filechooser" event, then select one or multiple input files for upload. Relative file paths are resolved relative to the current working directory. An empty list clears the selected files.- Examples:- upload_file('572', '/home/user/my_receipt.pdf')-- upload_file('63', ['/home/bob/Documents/image.jpg', '/home/bob/Documents/file.zip'])-"""---for _, action in _browser_action_space.action_set.items():- assert action.signature in _BROWSER_TOOL_DESCRIPTION, (- f'Browser description mismatch. Please double check if the BrowserGym updated their action space.\n\nAction: {action.signature}'- )- assert action.description in _BROWSER_TOOL_DESCRIPTION, (- f'Browser description mismatch. Please double check if the BrowserGym updated their action space.\n\nAction: {action.description}'- )--BrowserTool = ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name=BROWSER_TOOL_NAME,- description=_BROWSER_DESCRIPTION,- parameters={- 'type': 'object',- 'properties': {- 'code': {- 'type': 'string',- 'description': (- 'The Python code that interacts with the browser.\n'- + _BROWSER_TOOL_DESCRIPTION- ),- },- 'security_risk': {- 'type': 'string',- 'description': SECURITY_RISK_DESC,- 'enum': RISK_LEVELS,- },- },- 'required': ['code', 'security_risk'],- },- ),-)diff --git a/openhands/agenthub/codeact_agent/tools/condensation_request.py b/openhands/agenthub/codeact_agent/tools/condensation_request.pydeleted file mode 100644index 64d86ddead..0000000000--- a/openhands/agenthub/codeact_agent/tools/condensation_request.py+++ /dev/null@@ -1,23 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from litellm import ChatCompletionToolParam, ChatCompletionToolParamFunctionChunk--_CONDENSATION_REQUEST_DESCRIPTION = 'Request a condensation of the conversation history when the context becomes too long or when you need to focus on the most relevant information.'--CondensationRequestTool = ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name='request_condensation',- description=_CONDENSATION_REQUEST_DESCRIPTION,- parameters={- 'type': 'object',- 'properties': {},- 'required': [],- },- ),-)diff --git a/openhands/agenthub/codeact_agent/tools/finish.py b/openhands/agenthub/codeact_agent/tools/finish.pydeleted file mode 100644index 415c02f5ca..0000000000--- a/openhands/agenthub/codeact_agent/tools/finish.py+++ /dev/null@@ -1,41 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from litellm import ChatCompletionToolParam, ChatCompletionToolParamFunctionChunk--from openhands.llm.tool_names import FINISH_TOOL_NAME--_FINISH_DESCRIPTION = """Signals the completion of the current task or conversation.--Use this tool when:-- You have successfully completed the user's requested task-- You cannot proceed further due to technical limitations or missing information--The message should include:-- A clear summary of actions taken and their results-- Any next steps for the user-- Explanation if you're unable to complete the task-- Any follow-up questions if more information is needed-"""--FinishTool = ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name=FINISH_TOOL_NAME,- description=_FINISH_DESCRIPTION,- parameters={- 'type': 'object',- 'required': ['message'],- 'properties': {- 'message': {- 'type': 'string',- 'description': 'Final message to send to the user',- },- },- },- ),-)diff --git a/openhands/agenthub/codeact_agent/tools/ipython.py b/openhands/agenthub/codeact_agent/tools/ipython.pydeleted file mode 100644index a28040b805..0000000000--- a/openhands/agenthub/codeact_agent/tools/ipython.py+++ /dev/null@@ -1,41 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from litellm import ChatCompletionToolParam, ChatCompletionToolParamFunctionChunk--from openhands.agenthub.codeact_agent.tools.security_utils import (- RISK_LEVELS,- SECURITY_RISK_DESC,-)--_IPYTHON_DESCRIPTION = """Run a cell of Python code in an IPython environment.-* The assistant should define variables and import packages before using them.-* The variable defined in the IPython environment will not be available outside the IPython environment (e.g., in terminal).-"""--IPythonTool = ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name='execute_ipython_cell',- description=_IPYTHON_DESCRIPTION,- parameters={- 'type': 'object',- 'properties': {- 'code': {- 'type': 'string',- 'description': 'The Python code to execute. Supports magic commands like %pip.',- },- 'security_risk': {- 'type': 'string',- 'description': SECURITY_RISK_DESC,- 'enum': RISK_LEVELS,- },- },- 'required': ['code', 'security_risk'],- },- ),-)diff --git a/openhands/agenthub/codeact_agent/tools/llm_based_edit.py b/openhands/agenthub/codeact_agent/tools/llm_based_edit.pydeleted file mode 100644index b6fee388c3..0000000000--- a/openhands/agenthub/codeact_agent/tools/llm_based_edit.py+++ /dev/null@@ -1,162 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from litellm import ChatCompletionToolParam, ChatCompletionToolParamFunctionChunk--from openhands.agenthub.codeact_agent.tools.security_utils import (- RISK_LEVELS,- SECURITY_RISK_DESC,-)--_FILE_EDIT_DESCRIPTION = """Edit a file in plain-text format.-* The assistant can edit files by specifying the file path and providing a draft of the new file content.-* The draft content doesn't need to be exactly the same as the existing file; the assistant may skip unchanged lines using comments like `# ... existing code ...` to indicate unchanged sections.-* IMPORTANT: For large files (e.g., > 300 lines), specify the range of lines to edit using `start` and `end` (1-indexed, inclusive). The range should be smaller than 300 lines.-* -1 indicates the last line of the file when used as the `start` or `end` value.-* Keep at least one unchanged line before the changed section and after the changed section wherever possible.-* Make sure to set the `start` and `end` to include all the lines in the original file referred to in the draft of the new file content. Failure to do so will result in bad edits.-* To append to a file, set both `start` and `end` to `-1`.-* If the file doesn't exist, a new file will be created with the provided content.-* IMPORTANT: Make sure you include all the required indentations for each line of code in the draft, otherwise the edited code will be incorrectly indented.-* IMPORTANT: Make sure that the first line of the draft is also properly indented and has the required whitespaces.-* IMPORTANT: NEVER include or make references to lines from outside the `start` and `end` range in the draft.-* IMPORTANT: Start the content with a comment in the format: #EDIT: Reason for edit-* IMPORTANT: If you are not appending to the file, avoid setting `start` and `end` to the same value.--**Example 1: general edit for short files**-For example, given an existing file `/path/to/file.py` that looks like this:-(this is the beginning of the file)-1|class MyClass:-2| def __init__(self):-3| self.x = 1-4| self.y = 2-5| self.z = 3-6|-7|print(MyClass().z)-8|print(MyClass().x)-(this is the end of the file)--The assistant wants to edit the file to look like this:-(this is the beginning of the file)-1|class MyClass:-2| def __init__(self):-3| self.x = 1-4| self.y = 2-5|-6|print(MyClass().y)-(this is the end of the file)--The assistant may produce an edit action like this:-path="/path/to/file.txt" start=1 end=-1-content=```-#EDIT: I want to change the value of y to 2-class MyClass:- def __init__(self):- # ... existing code ...- self.y = 2--print(MyClass().y)-```--**Example 2: append to file for short files**-For example, given an existing file `/path/to/file.py` that looks like this:-(this is the beginning of the file)-1|class MyClass:-2| def __init__(self):-3| self.x = 1-4| self.y = 2-5| self.z = 3-6|-7|print(MyClass().z)-8|print(MyClass().x)-(this is the end of the file)--To append the following lines to the file:-```python-#EDIT: I want to print the value of y-print(MyClass().y)-```--The assistant may produce an edit action like this:-path="/path/to/file.txt" start=-1 end=-1-content=```-print(MyClass().y)-```--**Example 3: edit for long files**--Given an existing file `/path/to/file.py` that looks like this:-(1000 more lines above)-1001|class MyClass:-1002| def __init__(self):-1003| self.x = 1-1004| self.y = 2-1005| self.z = 3-1006|-1007|print(MyClass().z)-1008|print(MyClass().x)-(2000 more lines below)--The assistant wants to edit the file to look like this:--(1000 more lines above)-1001|class MyClass:-1002| def __init__(self):-1003| self.x = 1-1004| self.y = 2-1005|-1006|print(MyClass().y)-(2000 more lines below)--The assistant may produce an edit action like this:-path="/path/to/file.txt" start=1002 end=1008-content=```-#EDIT: I want to change the value of y to 2- def __init__(self):- # no changes before- self.y = 2- # self.z is removed--# MyClass().z is removed-print(MyClass().y)-```-"""--LLMBasedFileEditTool = ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name='edit_file',- description=_FILE_EDIT_DESCRIPTION,- parameters={- 'type': 'object',- 'properties': {- 'path': {- 'type': 'string',- 'description': 'The absolute path to the file to be edited.',- },- 'content': {- 'type': 'string',- 'description': 'A draft of the new content for the file being edited. Note that the assistant may skip unchanged lines.',- },- 'start': {- 'type': 'integer',- 'description': 'The starting line number for the edit (1-indexed, inclusive). Default is 1.',- },- 'end': {- 'type': 'integer',- 'description': 'The ending line number for the edit (1-indexed, inclusive). Default is -1 (end of file).',- },- 'security_risk': {- 'type': 'string',- 'description': SECURITY_RISK_DESC,- 'enum': RISK_LEVELS,- },- },- 'required': ['path', 'content', 'security_risk'],- },- ),-)diff --git a/openhands/agenthub/codeact_agent/tools/prompt.py b/openhands/agenthub/codeact_agent/tools/prompt.pydeleted file mode 100644index 11878bb671..0000000000--- a/openhands/agenthub/codeact_agent/tools/prompt.py+++ /dev/null@@ -1,35 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import re-import sys---def refine_prompt(prompt: str):- """Refines the prompt based on the platform.-- On Windows systems, replaces 'bash' with 'powershell' and 'execute_bash' with 'execute_powershell'- to ensure commands work correctly on the Windows platform.-- Args:- prompt: The prompt text to refine-- Returns:- The refined prompt text- """- if sys.platform == 'win32':- # Replace 'bash' with 'powershell' including tool names like 'execute_bash'- # First replace 'execute_bash' with 'execute_powershell' to handle tool names- result = re.sub(- r'\bexecute_bash\b', 'execute_powershell', prompt, flags=re.IGNORECASE- )- # Then replace standalone 'bash' with 'powershell'- result = re.sub(- r'(?<!execute_)(?<!_)\bbash\b', 'powershell', result, flags=re.IGNORECASE- )- return result- return promptdiff --git a/openhands/agenthub/codeact_agent/tools/security_utils.py b/openhands/agenthub/codeact_agent/tools/security_utils.pydeleted file mode 100644index 2568c55f97..0000000000--- a/openhands/agenthub/codeact_agent/tools/security_utils.py+++ /dev/null@@ -1,17 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-"""Security utility constants for tool risk descriptions.--This file contains standardized risk description text for various tools.-"""--# Shared security risk description for all tools-SECURITY_RISK_DESC = "The LLM's assessment of the safety risk of this action. See the SECURITY_RISK_ASSESSMENT section in the system prompt for risk level definitions."--# Risk level enum values - common across all tools-RISK_LEVELS = ['LOW', 'MEDIUM', 'HIGH']diff --git a/openhands/agenthub/codeact_agent/tools/str_replace_editor.py b/openhands/agenthub/codeact_agent/tools/str_replace_editor.pydeleted file mode 100644index 158ec2e5e1..0000000000--- a/openhands/agenthub/codeact_agent/tools/str_replace_editor.py+++ /dev/null@@ -1,168 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-import os--from litellm import ChatCompletionToolParam, ChatCompletionToolParamFunctionChunk--from openhands.agenthub.codeact_agent.tools.security_utils import (- RISK_LEVELS,- SECURITY_RISK_DESC,-)-from openhands.core.config.config_utils import DEFAULT_WORKSPACE_MOUNT_PATH_IN_SANDBOX-from openhands.llm.tool_names import STR_REPLACE_EDITOR_TOOL_NAME--_DETAILED_STR_REPLACE_EDITOR_DESCRIPTION = """Custom editing tool for viewing, creating and editing files in plain-text format-* State is persistent across command calls and discussions with the user-* If `path` is a text file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep-* The following binary file extensions can be viewed in Markdown format: [".xlsx", ".pptx", ".wav", ".mp3", ".m4a", ".flac", ".pdf", ".docx"]. IT DOES NOT HANDLE IMAGES.-* The `create` command cannot be used if the specified `path` already exists as a file-* If a `command` generates a long output, it will be truncated and marked with `<response clipped>`-* The `undo_edit` command will revert the last edit made to the file at `path`-* This tool can be used for creating and editing files in plain-text format.---Before using this tool:-1. Use the view tool to understand the file's contents and context-2. Verify the directory path is correct (only applicable when creating new files):- - Use the view tool to verify the parent directory exists and is the correct location--When making edits:- - Ensure the edit results in idiomatic, correct code- - Do not leave the code in a broken state- - Always use absolute file paths (starting with /)--CRITICAL REQUIREMENTS FOR USING THIS TOOL:--1. EXACT MATCHING: The `old_str` parameter must match EXACTLY one or more consecutive lines from the file, including all whitespace and indentation. The tool will fail if `old_str` matches multiple locations or doesn't match exactly with the file content.--2. UNIQUENESS: The `old_str` must uniquely identify a single instance in the file:- - Include sufficient context before and after the change point (3-5 lines recommended)- - If not unique, the replacement will not be performed--3. REPLACEMENT: The `new_str` parameter should contain the edited lines that replace the `old_str`. Both strings must be different.--Remember: when making multiple file edits in a row to the same file, you should prefer to send all edits in a single message with multiple calls to this tool, rather than multiple messages with a single call each.-"""--_SHORT_STR_REPLACE_EDITOR_DESCRIPTION = """Custom editing tool for viewing, creating and editing files in plain-text format-* State is persistent across command calls and discussions with the user-* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep-* The `create` command cannot be used if the specified `path` already exists as a file-* If a `command` generates a long output, it will be truncated and marked with `<response clipped>`-* The `undo_edit` command will revert the last edit made to the file at `path`-Notes for using the `str_replace` command:-* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!-* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique-* The `new_str` parameter should contain the edited lines that should replace the `old_str`-"""---def _get_workspace_mount_path_from_env(runtime_type: str | None = None) -> str:- """Get the workspace mount path from SANDBOX_VOLUMES environment variable.-- For LocalRuntime and CLIRuntime, returns the host path from SANDBOX_VOLUMES.- For other runtimes, returns the default container path (/workspace).-- Args:- runtime_type: The runtime type ('local', 'cli', 'docker', etc.)-- Returns:- The workspace mount path in sandbox, defaults to '/workspace' if not found.- """- # For LocalRuntime/CLIRuntime, try to get host path from SANDBOX_VOLUMES- if runtime_type in ('local', 'cli'):- sandbox_volumes = os.environ.get('SANDBOX_VOLUMES')- if sandbox_volumes:- # Split by commas to handle multiple mounts- mounts = sandbox_volumes.split(',')-- # Check if any mount explicitly targets /workspace- for mount in mounts:- parts = mount.split(':')- if len(parts) >= 2 and parts[1] == '/workspace':- host_path = os.path.abspath(parts[0])- return host_path-- # Fallback for local/CLI runtimes when SANDBOX_VOLUMES is not set:- # Use current working directory as it's likely the workspace root- return os.getcwd()-- # For all other runtimes (docker, remote, etc.), use default container path- return DEFAULT_WORKSPACE_MOUNT_PATH_IN_SANDBOX---def create_str_replace_editor_tool(- use_short_description: bool = False,- workspace_mount_path_in_sandbox: str | None = None,- runtime_type: str | None = None,-) -> ChatCompletionToolParam:- # If no workspace path is provided, try to get it from environment- if workspace_mount_path_in_sandbox is None:- workspace_mount_path_in_sandbox = _get_workspace_mount_path_from_env(- runtime_type- )-- description = (- _SHORT_STR_REPLACE_EDITOR_DESCRIPTION- if use_short_description- else _DETAILED_STR_REPLACE_EDITOR_DESCRIPTION- )- return ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name=STR_REPLACE_EDITOR_TOOL_NAME,- description=description,- parameters={- 'type': 'object',- 'properties': {- 'command': {- 'description': 'The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.',- 'enum': [- 'view',- 'create',- 'str_replace',- 'insert',- 'undo_edit',- ],- 'type': 'string',- },- 'path': {- 'description': f'Absolute path to file or directory, e.g. `{workspace_mount_path_in_sandbox}/file.py` or `{workspace_mount_path_in_sandbox}`.',- 'type': 'string',- },- 'file_text': {- 'description': 'Required parameter of `create` command, with the content of the file to be created.',- 'type': 'string',- },- 'old_str': {- 'description': 'Required parameter of `str_replace` command containing the string in `path` to replace.',- 'type': 'string',- },- 'new_str': {- 'description': 'Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.',- 'type': 'string',- },- 'insert_line': {- 'description': 'Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.',- 'type': 'integer',- },- 'view_range': {- 'description': 'Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.',- 'items': {'type': 'integer'},- 'type': 'array',- },- 'security_risk': {- 'type': 'string',- 'description': SECURITY_RISK_DESC,- 'enum': RISK_LEVELS,- },- },- 'required': ['command', 'path', 'security_risk'],- },- ),- )diff --git a/openhands/agenthub/codeact_agent/tools/task_tracker.py b/openhands/agenthub/codeact_agent/tools/task_tracker.pydeleted file mode 100644index 1747091ab5..0000000000--- a/openhands/agenthub/codeact_agent/tools/task_tracker.py+++ /dev/null@@ -1,210 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from litellm import ChatCompletionToolParam, ChatCompletionToolParamFunctionChunk--from openhands.llm.tool_names import TASK_TRACKER_TOOL_NAME--_DETAILED_TASK_TRACKER_DESCRIPTION = """This tool provides structured task management capabilities for development workflows.-It enables systematic tracking of work items, progress monitoring, and efficient-organization of complex development activities.--The tool maintains visibility into project status and helps communicate-progress effectively to users.--## Application Guidelines--Utilize this tool in the following situations:--1. Multi-phase development work - When projects involve multiple sequential or- parallel activities-2. Complex implementation tasks - Work requiring systematic planning and- coordination across multiple components-3. Explicit user request for task organization - When users specifically ask- for structured task management-4. Multiple concurrent requirements - When users present several work items- that need coordination-5. Project initiation - Capture and organize user requirements at project start-6. Work commencement - Update task status to in_progress before beginning- implementation. Maintain focus by limiting active work to one task-7. Task completion - Update status to done and identify any additional work- that emerged during implementation--## Situations Where Tool Usage Is Unnecessary--Avoid using this tool when:--1. Single atomic tasks that require no decomposition-2. Trivial operations where tracking adds no organizational value-3. Simple activities completable in minimal steps-4. Pure information exchange or discussion--Note: For single straightforward tasks, proceed with direct implementation-rather than creating tracking overhead.--## Usage Scenarios--**Scenario A: Feature Development with Validation**-User request: "Build a user authentication system with login/logout functionality.-Don't forget to include input validation and error handling!"--Response approach: I'll implement a user authentication system with comprehensive-validation. Let me organize this work systematically.--*Task breakdown includes:*-1. Design authentication API endpoints and data models-2. Implement user login/logout controllers with session management-3. Add client-side form validation and error display-4. Create backend input sanitization and security checks-5. Implement comprehensive error handling for edge cases-6. Perform integration testing and fix any issues--**Scenario B: Codebase Refactoring**-User request: "I need to update all instances of the method 'fetchData' to-'retrieveInformation' throughout the entire project"--Response approach: Let me first analyze your codebase to identify all locations-where 'fetchData' appears.--*After code analysis*--I've located 12 occurrences of 'fetchData' across 6 files in your project.-I'll create a systematic plan to update these references.--*Organized task list includes specific file-by-file updates*--**Scenario C: Multi-feature Development**-User request: "Set up a blog platform with these components: admin dashboard,-article management, comment system, and user profiles."--Response approach: I'll help build your blog platform. Let me break down these-components into manageable implementation phases.--*Creates structured plan with each feature decomposed into specific development tasks*--## Counter-examples - Direct Implementation Preferred--**Counter-example A: Simple inquiry**-User request: "What's the syntax for a for loop in JavaScript?"--Response approach: Here's how to write a for loop in JavaScript:--```javascript-for (let i = 0; i < array.length; i++) {- console.log(array[i]);-}-```--*No task tracking needed - single informational response*--**Counter-example B: Minor modification**-User request: "Please add a docstring to the processPayment function explaining-its parameters."--Response approach: I'll add a docstring to explain the processPayment function.--*Direct edit without task tracking for simple modification*--## Status Management and Workflow--1. **Status Values**: Track work using these states:- - todo: Not yet initiated- - in_progress: Currently active (maintain single focus)- - done: Successfully completed--2. **Workflow Practices**:- - Update status dynamically as work progresses- - Mark completion immediately upon task finish- - Limit active work to ONE task at any given time- - Complete current activities before initiating new ones- - Remove obsolete tasks from tracking entirely--3. **Completion Criteria**:- - Mark tasks as done only when fully achieved- - Keep status as in_progress if errors, blocks, or partial completion exist- - Create new tasks for discovered issues or dependencies- - Never mark done when:- - Test suites are failing- - Implementation remains incomplete- - Unresolved errors persist- - Required resources are unavailable--4. **Task Organization**:- - Write precise, actionable descriptions- - Decompose complex work into manageable units- - Use descriptive, clear naming conventions--When uncertain, favor using this tool. Proactive task management demonstrates-systematic approach and ensures comprehensive requirement fulfillment.-"""--_SHORT_TASK_TRACKER_DESCRIPTION = """Provides structured task management for development workflows, enabling progress-tracking and systematic organization of complex coding activities.--* Apply to multi-phase projects (3+ distinct steps) or when managing multiple user requirements-* Update status (todo/in_progress/done) dynamically throughout work-* Maintain single active task focus at any time-* Mark completion immediately upon task finish-* Decompose complex work into manageable, actionable units-"""---def create_task_tracker_tool(- use_short_description: bool = False,-) -> ChatCompletionToolParam:- description = (- _SHORT_TASK_TRACKER_DESCRIPTION- if use_short_description- else _DETAILED_TASK_TRACKER_DESCRIPTION- )- return ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name=TASK_TRACKER_TOOL_NAME,- description=description,- parameters={- 'type': 'object',- 'properties': {- 'command': {- 'type': 'string',- 'enum': ['view', 'plan'],- 'description': 'The command to execute. `view` shows the current task list. `plan` creates or updates the task list based on provided requirements and progress. Always `view` the current list before making changes.',- },- 'task_list': {- 'type': 'array',- 'description': 'The full task list. Required parameter of `plan` command.',- 'items': {- 'type': 'object',- 'properties': {- 'id': {- 'type': 'string',- 'description': 'Unique task identifier',- },- 'title': {- 'type': 'string',- 'description': 'Brief task description',- },- 'status': {- 'type': 'string',- 'description': 'Current task status',- 'enum': ['todo', 'in_progress', 'done'],- },- 'notes': {- 'type': 'string',- 'description': 'Optional additional context or details',- },- },- 'required': ['title', 'status', 'id'],- 'additionalProperties': False,- },- },- },- 'required': ['command'],- 'additionalProperties': False,- },- ),- )diff --git a/openhands/agenthub/codeact_agent/tools/think.py b/openhands/agenthub/codeact_agent/tools/think.pydeleted file mode 100644index 9e24418fdd..0000000000--- a/openhands/agenthub/codeact_agent/tools/think.py+++ /dev/null@@ -1,34 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from litellm import ChatCompletionToolParam, ChatCompletionToolParamFunctionChunk--_THINK_DESCRIPTION = """Use the tool to think about something. It will not obtain new information or make any changes to the repository, but just log the thought. Use it when complex reasoning or brainstorming is needed.--Common use cases:-1. When exploring a repository and discovering the source of a bug, call this tool to brainstorm several unique ways of fixing the bug, and assess which change(s) are likely to be simplest and most effective.-2. After receiving test results, use this tool to brainstorm ways to fix failing tests.-3. When planning a complex refactoring, use this tool to outline different approaches and their tradeoffs.-4. When designing a new feature, use this tool to think through architecture decisions and implementation details.-5. When debugging a complex issue, use this tool to organize your thoughts and hypotheses.--The tool simply logs your thought process for better transparency and does not execute any code or make changes."""--ThinkTool = ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name='think',- description=_THINK_DESCRIPTION,- parameters={- 'type': 'object',- 'properties': {- 'thought': {'type': 'string', 'description': 'The thought to log.'},- },- 'required': ['thought'],- },- ),-)diff --git a/openhands/agenthub/dummy_agent/__init__.py b/openhands/agenthub/dummy_agent/__init__.pydeleted file mode 100644index d0db8e26c9..0000000000--- a/openhands/agenthub/dummy_agent/__init__.py+++ /dev/null@@ -1,4 +0,0 @@-from openhands.agenthub.dummy_agent.agent import DummyAgent-from openhands.controller.agent import Agent--Agent.register('DummyAgent', DummyAgent)diff --git a/openhands/agenthub/dummy_agent/agent.py b/openhands/agenthub/dummy_agent/agent.pydeleted file mode 100644index 47e48062b4..0000000000--- a/openhands/agenthub/dummy_agent/agent.py+++ /dev/null@@ -1,183 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from typing import TypedDict--from openhands.controller.agent import Agent-from openhands.controller.state.state import State-from openhands.core.config import AgentConfig-from openhands.core.schema import AgentState-from openhands.events.action import (- Action,- AgentFinishAction,- AgentRejectAction,- CmdRunAction,- FileReadAction,- FileWriteAction,- MessageAction,-)-from openhands.events.observation import (- AgentStateChangedObservation,- CmdOutputMetadata,- CmdOutputObservation,- FileReadObservation,- FileWriteObservation,- Observation,-)-from openhands.events.serialization.event import event_to_dict-from openhands.llm.llm_registry import LLMRegistry--"""-FIXME: There are a few problems this surfaced-* FileWrites seem to add an unintended newline at the end of the file-* Browser not working-"""--ActionObs = TypedDict(- 'ActionObs', {'action': Action, 'observations': list[Observation]}-)---class DummyAgent(Agent):- VERSION = '1.0'- """- The DummyAgent is used for e2e testing. It just sends the same set of actions deterministically,- without making any LLM calls.- """-- def __init__(- self,- config: AgentConfig,- llm_registry: LLMRegistry,- ):- super().__init__(config, llm_registry)- self.steps: list[ActionObs] = [- {- 'action': MessageAction('Time to get started!'),- 'observations': [],- },- {- 'action': CmdRunAction(command='echo "foo"'),- 'observations': [- CmdOutputObservation(- 'foo',- command='echo "foo"',- metadata=CmdOutputMetadata(exit_code=0),- )- ],- },- {- 'action': FileWriteAction(- content='echo "Hello, World!"', path='hello.sh'- ),- 'observations': [FileWriteObservation(content='', path='hello.sh')],- },- {- 'action': FileReadAction(path='hello.sh'),- 'observations': [- FileReadObservation('echo "Hello, World!"\n', path='hello.sh')- ],- },- {- 'action': CmdRunAction(command='bash hello.sh'),- 'observations': [- CmdOutputObservation(- 'Hello, World!',- command='bash hello.sh',- metadata=CmdOutputMetadata(exit_code=0),- )- ],- },- {- 'action': AgentRejectAction(),- 'observations': [AgentStateChangedObservation('', AgentState.REJECTED)],- },- {- 'action': AgentFinishAction(- outputs={}, thought='Task completed', action='finish'- ),- 'observations': [AgentStateChangedObservation('', AgentState.FINISHED)],- },- ]-- def step(self, state: State) -> Action:- if state.iteration_flag.current_value >= len(self.steps):- return AgentFinishAction()-- current_step = self.steps[state.iteration_flag.current_value]- action = current_step['action']-- if state.iteration_flag.current_value > 0:- prev_step = self.steps[state.iteration_flag.current_value - 1]-- if 'observations' in prev_step and prev_step['observations']:- expected_observations = prev_step['observations']- hist_events = state.view[-len(expected_observations) :]-- if len(hist_events) < len(expected_observations):- print(- f'Warning: Expected {len(expected_observations)} observations, but got {len(hist_events)}'- )-- for i in range(min(len(expected_observations), len(hist_events))):- hist_obs = event_to_dict(hist_events[i])- expected_obs = event_to_dict(expected_observations[i])-- # Remove dynamic fields for comparison- for obs in [hist_obs, expected_obs]:- obs.pop('id', None)- obs.pop('timestamp', None)- obs.pop('cause', None)- obs.pop('source', None)- # Remove dynamic metadata fields that vary between runs- if 'extras' in obs and 'metadata' in obs['extras']:- metadata = obs['extras']['metadata']- if isinstance(metadata, dict):- metadata.pop('pid', None)- metadata.pop('username', None)- metadata.pop('hostname', None)- metadata.pop('working_dir', None)- metadata.pop('py_interpreter_path', None)- metadata.pop('suffix', None)- # Normalize file paths for comparison - extract just the filename- if 'extras' in obs and 'path' in obs['extras']:- path = obs['extras']['path']- if isinstance(path, str):- # Extract just the filename from the path- import os-- obs['extras']['path'] = os.path.basename(path)- # Normalize message field to handle path differences- if 'message' in obs:- import os-- message = obs['message']- if isinstance(message, str):- # Replace full paths with just filenames in messages- if 'I wrote to the file ' in message:- parts = message.split('I wrote to the file ')- if len(parts) == 2:- filename = os.path.basename(- parts[1].rstrip('.')- )- obs['message'] = (- f'I wrote to the file {filename}.'- )- elif 'I read the file ' in message:- parts = message.split('I read the file ')- if len(parts) == 2:- filename = os.path.basename(- parts[1].rstrip('.')- )- obs['message'] = f'I read the file {filename}.'-- if hist_obs != expected_obs:- print(- f'Warning: Observation mismatch. Expected {expected_obs}, got {hist_obs}'- )-- return actiondiff --git a/openhands/agenthub/loc_agent/README.md b/openhands/agenthub/loc_agent/README.mddeleted file mode 100644index b9c1b879d2..0000000000--- a/openhands/agenthub/loc_agent/README.md+++ /dev/null@@ -1,14 +0,0 @@-# LocAgent Framework--This folder is an implementation of Locagent. It is based on ([LocAgent](https://arxiv.org/abs/2503.09089), [tweet](https://x.com/XiangruTang/status/1900392655009333338)), a framework that addresses code localization through graph-based representation. By parsing codebases into directed heterogeneous graphs, LocAgent creates a lightweight representation that captures code structures and their dependencies, enabling LLM agents to effectively search and locate relevant entities through powerful multi-hop reasoning.--<!-- ## Overview -->---## Built-in Tools--The agent provides several built-in tools:-- 1. `search_code_snippets`- 2. `get_entity_contents`- 3. `explore_tree_structure`diff --git a/openhands/agenthub/loc_agent/__init__.py b/openhands/agenthub/loc_agent/__init__.pydeleted file mode 100644index 082d3f7fb7..0000000000--- a/openhands/agenthub/loc_agent/__init__.py+++ /dev/null@@ -1,4 +0,0 @@-from openhands.agenthub.loc_agent.loc_agent import LocAgent-from openhands.controller.agent import Agent--Agent.register('LocAgent', LocAgent)diff --git a/openhands/agenthub/loc_agent/function_calling.py b/openhands/agenthub/loc_agent/function_calling.pydeleted file mode 100644index dd3b74c6ff..0000000000--- a/openhands/agenthub/loc_agent/function_calling.py+++ /dev/null@@ -1,132 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-"""This file contains the function calling implementation for different actions.--This is similar to the functionality of `CodeActResponseParser`.-"""--import json--from litellm import (- ChatCompletionToolParam,- ModelResponse,-)--from openhands.agenthub.codeact_agent.function_calling import combine_thought-from openhands.agenthub.codeact_agent.tools import FinishTool-from openhands.agenthub.loc_agent.tools import (- SearchEntityTool,- SearchRepoTool,- create_explore_tree_structure_tool,-)-from openhands.core.exceptions import (- FunctionCallNotExistsError,-)-from openhands.core.logger import openhands_logger as logger-from openhands.events.action import (- Action,- AgentFinishAction,- IPythonRunCellAction,- MessageAction,-)-from openhands.events.tool import ToolCallMetadata---def response_to_actions(- response: ModelResponse,- mcp_tool_names: list[str] | None = None,-) -> list[Action]:- actions: list[Action] = []- assert len(response.choices) == 1, 'Only one choice is supported for now'- choice = response.choices[0]- assistant_msg = choice.message-- if hasattr(assistant_msg, 'tool_calls') and assistant_msg.tool_calls:- # Check if there's assistant_msg.content. If so, add it to the thought- thought = ''- if isinstance(assistant_msg.content, str):- thought = assistant_msg.content- elif isinstance(assistant_msg.content, list):- for msg in assistant_msg.content:- if msg['type'] == 'text':- thought += msg['text']-- # Process each tool call to OpenHands action- for i, tool_call in enumerate(assistant_msg.tool_calls):- action: Action- logger.debug(f'Tool call in function_calling.py: {tool_call}')- try:- arguments = json.loads(tool_call.function.arguments)- except json.decoder.JSONDecodeError as e:- raise RuntimeError(- f'Failed to parse tool call arguments: {tool_call.function.arguments}'- ) from e-- # ================================================- # LocAgent's Tools- # ================================================- ALL_FUNCTIONS = [- 'explore_tree_structure',- 'search_code_snippets',- 'get_entity_contents',- ]- if tool_call.function.name in ALL_FUNCTIONS:- # We implement this in agent_skills, which can be used via Jupyter- func_name = tool_call.function.name- code = f'print({func_name}(**{arguments}))'- logger.debug(f'TOOL CALL: {func_name} with code: {code}')- action = IPythonRunCellAction(code=code)-- # ================================================- # AgentFinishAction- # ================================================- elif tool_call.function.name == FinishTool['function']['name']:- action = AgentFinishAction(- final_thought=arguments.get('message', ''),- )- else:- raise FunctionCallNotExistsError(- f'Tool {tool_call.function.name} is not registered. (arguments: {arguments}). Please check the tool name and retry with an existing tool.'- )-- # We only add thought to the first action- if i == 0:- action = combine_thought(action, thought)- # Add metadata for tool calling- action.tool_call_metadata = ToolCallMetadata(- tool_call_id=tool_call.id,- function_name=tool_call.function.name,- model_response=response,- total_calls_in_response=len(assistant_msg.tool_calls),- )- actions.append(action)- else:- actions.append(- MessageAction(- content=str(assistant_msg.content) if assistant_msg.content else '',- wait_for_response=True,- )- )-- # Add response id to actions- # This will ensure we can match both actions without tool calls (e.g. MessageAction)- # and actions with tool calls (e.g. CmdRunAction, IPythonRunCellAction, etc.)- # with the token usage data- for action in actions:- action.response_id = response.id-- assert len(actions) >= 1- return actions---def get_tools() -> list[ChatCompletionToolParam]:- tools = [FinishTool]- tools.append(SearchRepoTool)- tools.append(SearchEntityTool)- tools.append(create_explore_tree_structure_tool(use_simplified_description=True))- return toolsdiff --git a/openhands/agenthub/loc_agent/loc_agent.py b/openhands/agenthub/loc_agent/loc_agent.pydeleted file mode 100644index 4e4034aca5..0000000000--- a/openhands/agenthub/loc_agent/loc_agent.py+++ /dev/null@@ -1,47 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from typing import TYPE_CHECKING--import openhands.agenthub.loc_agent.function_calling as locagent_function_calling-from openhands.agenthub.codeact_agent import CodeActAgent-from openhands.core.config import AgentConfig-from openhands.core.logger import openhands_logger as logger-from openhands.llm.llm_registry import LLMRegistry--if TYPE_CHECKING:- from openhands.events.action import Action- from openhands.llm.llm import ModelResponse---class LocAgent(CodeActAgent):- VERSION = '1.0'-- def __init__(- self,- config: AgentConfig,- llm_registry: LLMRegistry,- ) -> None:- """Initializes a new instance of the LocAgent class.-- Parameters:- - llm (LLM): The llm to be used by this agent- - config (AgentConfig): The configuration for the agent- """-- super().__init__(config, llm_registry)-- self.tools = locagent_function_calling.get_tools()- logger.debug(- f'TOOLS loaded for LocAgent: {", ".join([tool.get("function").get("name") for tool in self.tools])}'- )-- def response_to_actions(self, response: 'ModelResponse') -> list['Action']:- return locagent_function_calling.response_to_actions(- response,- mcp_tool_names=list(self.mcp_tools.keys()),- )diff --git a/openhands/agenthub/loc_agent/tools/__init__.py b/openhands/agenthub/loc_agent/tools/__init__.pydeleted file mode 100644index 78e414f5bd..0000000000--- a/openhands/agenthub/loc_agent/tools/__init__.py+++ /dev/null@@ -1,8 +0,0 @@-from .explore_structure import create_explore_tree_structure_tool-from .search_content import SearchEntityTool, SearchRepoTool--__all__ = [- 'SearchEntityTool',- 'SearchRepoTool',- 'create_explore_tree_structure_tool',-]diff --git a/openhands/agenthub/loc_agent/tools/explore_structure.py b/openhands/agenthub/loc_agent/tools/explore_structure.pydeleted file mode 100644index b7a534a8cb..0000000000--- a/openhands/agenthub/loc_agent/tools/explore_structure.py+++ /dev/null@@ -1,192 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from litellm import (- ChatCompletionToolParam,- ChatCompletionToolParamFunctionChunk,-)--_SIMPLIFIED_STRUCTURE_EXPLORER_DESCRIPTION = """-A unified tool that traverses a pre-built code graph to retrieve dependency structure around specified entities,-with options to explore upstream or downstream, and control traversal depth and filters for entity and dependency types.-"""---_SIMPLIFIED_TREE_EXAMPLE = """-Example Usage:-1. Exploring Downstream Dependencies:- ```- explore_tree_structure(- start_entities=['src/module_a.py:ClassA'],- direction='downstream',- traversal_depth=2,- dependency_type_filter=['invokes', 'imports']- )- ```-2. Exploring the repository structure from the root directory (/) up to two levels deep:- ```- explore_tree_structure(- start_entities=['/'],- traversal_depth=2,- dependency_type_filter=['contains']- )- ```-3. Generate Class Diagrams:- ```- explore_tree_structure(- start_entities=selected_entity_ids,- direction='both',- traverse_depth=-1,- dependency_type_filter=['inherits']- )- ```-"""---_DETAILED_STRUCTURE_EXPLORER_DESCRIPTION = """-Unified repository exploring tool that traverses a pre-built code graph to retrieve dependency structure around specified entities.-The search can be controlled to traverse upstream (exploring dependencies that entities rely on) or downstream (exploring how entities impact others), with optional limits on traversal depth and filters for entity and dependency types.--Code Graph Definition:-* Entity Types: 'directory', 'file', 'class', 'function'.-* Dependency Types: 'contains', 'imports', 'invokes', 'inherits'.-* Hierarchy:- - Directories contain files and subdirectories.- - Files contain classes and functions.- - Classes contain inner classes and methods.- - Functions can contain inner functions.-* Interactions:- - Files/classes/functions can import classes and functions.- - Classes can inherit from other classes.- - Classes and functions can invoke others (invocations in a class's `__init__` are attributed to the class).-Entity ID:-* Unique identifier including file path and module path.-* Here's an example of an Entity ID: `"interface/C.py:C.method_a.inner_func"` identifies function `inner_func` within `method_a` of class `C` in `"interface/C.py"`.--Notes:-* Traversal Control: The `traversal_depth` parameter specifies how deep the function should explore the graph starting from the input entities.-* Filtering: Use `entity_type_filter` and `dependency_type_filter` to narrow down the scope of the search, focusing on specific entity types and relationships.--"""---_DETAILED_TREE_EXAMPLE = """-Example Usage:-1. Exploring Outward Dependencies:- ```- explore_tree_structure(- start_entities=['src/module_a.py:ClassA'],- direction='downstream',- traversal_depth=2,- dependency_type_filter=['invokes', 'imports']- )- ```- This retrieves the dependencies of `ClassA` up to 2 levels deep, focusing only on classes and functions with 'invokes' and 'imports' relationships.--2. Exploring Inward Dependencies:- ```- explore_tree_structure(- start_entities=['src/module_b.py:FunctionY'],- direction='upstream',- traversal_depth=-1- )- ```- This finds all entities that depend on `FunctionY` without restricting the traversal depth.-3. Exploring Repository Structure:- ```- explore_tree_structure(- start_entities=['/'],- traversal_depth=2,- dependency_type_filter=['contains']- )- ```- This retrieves the tree repository structure from the root directory (/), traversing up to two levels deep and focusing only on 'contains' relationship.-4. Generate Class Diagrams:- ```- explore_tree_structure(- start_entities=selected_entity_ids,- direction='both',- traverse_depth=-1,- dependency_type_filter=['inherits']- )- ```-"""---_STRUCTURE_EXPLORER_PARAMETERS = {- 'type': 'object',- 'properties': {- 'start_entities': {- 'description': (- 'List of entities (e.g., class, function, file, or directory paths) to begin the search from.\n'- 'Entities representing classes or functions must be formatted as "file_path:QualifiedName" (e.g., `interface/C.py:C.method_a.inner_func`).\n'- 'For files or directories, provide only the file or directory path (e.g., `src/module_a.py` or `src/`).'- ),- 'type': 'array',- 'items': {'type': 'string'},- },- 'direction': {- 'description': (- 'Direction of traversal in the code graph; allowed options are: `upstream`, `downstream`, `both`.\n'- "- 'upstream': Traversal to explore dependencies that the specified entities rely on (how they depend on others).\n"- "- 'downstream': Traversal to explore the effects or interactions of the specified entities on others (how others depend on them).\n"- "- 'both': Traversal on both direction."- ),- 'type': 'string',- 'enum': ['upstream', 'downstream', 'both'],- 'default': 'downstream',- },- 'traversal_depth': {- 'description': (- 'Maximum depth of traversal. A value of -1 indicates unlimited depth (subject to a maximum limit).'- 'Must be either `-1` or a non-negative integer (β₯ 0).'- ),- 'type': 'integer',- 'default': 2,- },- 'entity_type_filter': {- 'description': (- "List of entity types (e.g., 'class', 'function', 'file', 'directory') to include in the traversal. If None, all entity types are included."- ),- 'type': ['array', 'null'],- 'items': {'type': 'string'},- 'default': None,- },- 'dependency_type_filter': {- 'description': (- "List of dependency types (e.g., 'contains', 'imports', 'invokes', 'inherits') to include in the traversal. If None, all dependency types are included."- ),- 'type': ['array', 'null'],- 'items': {'type': 'string'},- 'default': None,- },- },- 'required': ['start_entities'],-}---def create_explore_tree_structure_tool(- use_simplified_description: bool = False,-) -> ChatCompletionToolParam:- description = (- _SIMPLIFIED_STRUCTURE_EXPLORER_DESCRIPTION- if use_simplified_description- else _DETAILED_STRUCTURE_EXPLORER_DESCRIPTION- )- example = (- _SIMPLIFIED_TREE_EXAMPLE- if use_simplified_description- else _DETAILED_TREE_EXAMPLE- )- return ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name='explore_tree_structure',- description=description + example,- parameters=_STRUCTURE_EXPLORER_PARAMETERS,- ),- )diff --git a/openhands/agenthub/loc_agent/tools/search_content.py b/openhands/agenthub/loc_agent/tools/search_content.pydeleted file mode 100644index ab6537bd59..0000000000--- a/openhands/agenthub/loc_agent/tools/search_content.py+++ /dev/null@@ -1,105 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from litellm import (- ChatCompletionToolParam,- ChatCompletionToolParamFunctionChunk,-)--_SEARCH_ENTITY_DESCRIPTION = """-Searches the codebase to retrieve the complete implementations of specified entities based on the provided entity names.-The tool can handle specific entity queries such as function names, class names, or file paths.--**Usage Example:**-# Search for a specific function implementation-get_entity_contents(['src/my_file.py:MyClass.func_name'])--# Search for a file's complete content-get_entity_contents(['src/my_file.py'])--**Entity Name Format:**-- To specify a function or class, use the format: `file_path:QualifiedName`- (e.g., 'src/helpers/math_helpers.py:MathUtils.calculate_sum').-- To search for a file's content, use only the file path (e.g., 'src/my_file.py').-"""--SearchEntityTool = ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name='get_entity_contents',- description=_SEARCH_ENTITY_DESCRIPTION,- parameters={- 'type': 'object',- 'properties': {- 'entity_names': {- 'type': 'array',- 'items': {'type': 'string'},- 'description': (- 'A list of entity names to query. Each entity name can represent a function, class, or file. '- "For functions or classes, the format should be 'file_path:QualifiedName' "- "(e.g., 'src/helpers/math_helpers.py:MathUtils.calculate_sum'). "- "For files, use just the file path (e.g., 'src/my_file.py')."- ),- }- },- 'required': ['entity_names'],- },- ),-)---_SEARCH_REPO_DESCRIPTION = """Searches the codebase to retrieve relevant code snippets based on given queries(terms or line numbers).-** Note:-- Either `search_terms` or `line_nums` must be provided to perform a search.-- If `search_terms` are provided, it searches for code snippets based on each term:-- If `line_nums` is provided, it searches for code snippets around the specified lines within the file defined by `file_path_or_pattern`.--** Example Usage:-# Search for code content contain keyword `order`, `bill`-search_code_snippets(search_terms=["order", "bill"])--# Search for a class-search_code_snippets(search_terms=["MyClass"])--# Search for context around specific lines (10 and 15) within a file-search_code_snippets(line_nums=[10, 15], file_path_or_pattern='src/example.py')-"""--SearchRepoTool = ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name='search_code_snippets',- description=_SEARCH_REPO_DESCRIPTION,- parameters={- 'type': 'object',- 'properties': {- 'search_terms': {- 'type': 'array',- 'items': {'type': 'string'},- 'description': 'A list of names, keywords, or code snippets to search for within the codebase. '- 'This can include potential function names, class names, or general code fragments. '- 'Either `search_terms` or `line_nums` must be provided to perform a search.',- },- 'line_nums': {- 'type': 'array',- 'items': {'type': 'integer'},- 'description': 'Specific line numbers to locate code snippets within a specified file. '- 'Must be used alongside a valid `file_path_or_pattern`. '- 'Either `line_nums` or `search_terms` must be provided to perform a search.',- },- 'file_path_or_pattern': {- 'type': 'string',- 'description': 'A glob pattern or specific file path used to filter search results '- 'to particular files or directories. Defaults to "**/*.py", meaning all Python files are searched by default. '- 'If `line_nums` are provided, this must specify a specific file path.',- 'default': '**/*.py',- },- },- 'required': [],- },- ),-)diff --git a/openhands/agenthub/readonly_agent/__init__.py b/openhands/agenthub/readonly_agent/__init__.pydeleted file mode 100644index 0e91911887..0000000000--- a/openhands/agenthub/readonly_agent/__init__.py+++ /dev/null@@ -1,4 +0,0 @@-from openhands.agenthub.readonly_agent.readonly_agent import ReadOnlyAgent-from openhands.controller.agent import Agent--Agent.register('ReadOnlyAgent', ReadOnlyAgent)diff --git a/openhands/agenthub/readonly_agent/function_calling.py b/openhands/agenthub/readonly_agent/function_calling.pydeleted file mode 100644index 005ed8a252..0000000000--- a/openhands/agenthub/readonly_agent/function_calling.py+++ /dev/null@@ -1,255 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-"""This file contains the function calling implementation for different actions.--This is similar to the functionality of `CodeActResponseParser`.-"""--import json-import shlex--from litellm import (- ChatCompletionToolParam,- ModelResponse,-)--from openhands.agenthub.codeact_agent.function_calling import (- combine_thought,-)-from openhands.agenthub.codeact_agent.tools import (- FinishTool,- ThinkTool,-)-from openhands.agenthub.readonly_agent.tools import (- GlobTool,- GrepTool,- ViewTool,-)-from openhands.core.exceptions import (- FunctionCallNotExistsError,- FunctionCallValidationError,-)-from openhands.core.logger import openhands_logger as logger-from openhands.events.action import (- Action,- AgentFinishAction,- AgentThinkAction,- CmdRunAction,- FileReadAction,- MCPAction,- MessageAction,-)-from openhands.events.event import FileReadSource-from openhands.events.tool import ToolCallMetadata---def grep_to_cmdrun(- pattern: str, path: str | None = None, include: str | None = None-) -> str:- # NOTE: This function currently relies on `rg` (ripgrep).- # `rg` may not be installed when using CLIRuntime or LocalRuntime.- # TODO: Implement a fallback to `grep` if `rg` is not available.- """Convert grep tool arguments to a shell command string.-- Args:- pattern: The regex pattern to search for in file contents- path: The directory to search in (optional)- include: Optional file pattern to filter which files to search (e.g., "*.js")-- Returns:- A properly escaped shell command string for ripgrep- """- # Use shlex.quote to properly escape all shell special characters- quoted_pattern = shlex.quote(pattern)- path_arg = shlex.quote(path) if path else '.'-- # Build ripgrep command- rg_cmd = f'rg -li {quoted_pattern} --sortr=modified'-- if include:- quoted_include = shlex.quote(include)- rg_cmd += f' --glob {quoted_include}'-- # Build the complete command- complete_cmd = f'{rg_cmd} {path_arg} | head -n 100'-- # Add a header to the output- echo_cmd = f'echo "Below are the execution results of the search command: {complete_cmd}\n"; '- return echo_cmd + complete_cmd---def glob_to_cmdrun(pattern: str, path: str = '.') -> str:- # NOTE: This function currently relies on `rg` (ripgrep).- # `rg` may not be installed when using CLIRuntime or LocalRuntime- # TODO: Implement a fallback to `find` if `rg` is not available.- """Convert glob tool arguments to a shell command string.-- Args:- pattern: The glob pattern to match files (e.g., "**/*.js")- path: The directory to search in (defaults to current directory)-- Returns:- A properly escaped shell command string for ripgrep implementing glob- """- # Use shlex.quote to properly escape all shell special characters- quoted_path = shlex.quote(path)- quoted_pattern = shlex.quote(pattern)-- # Use ripgrep in a glob-only mode with -g flag and --files to list files- # This most closely matches the behavior of the NodeJS glob implementation- rg_cmd = f'rg --files {quoted_path} -g {quoted_pattern} --sortr=modified'-- # Sort results and limit to 100 entries (matching the Node.js implementation)- sort_and_limit_cmd = ' | head -n 100'-- complete_cmd = f'{rg_cmd}{sort_and_limit_cmd}'-- # Add a header to the output- echo_cmd = f'echo "Below are the execution results of the glob command: {complete_cmd}\n"; '- return echo_cmd + complete_cmd---def response_to_actions(- response: ModelResponse, mcp_tool_names: list[str] | None = None-) -> list[Action]:- actions: list[Action] = []- assert len(response.choices) == 1, 'Only one choice is supported for now'- choice = response.choices[0]- assistant_msg = choice.message- if hasattr(assistant_msg, 'tool_calls') and assistant_msg.tool_calls:- # Check if there's assistant_msg.content. If so, add it to the thought- thought = ''- if isinstance(assistant_msg.content, str):- thought = assistant_msg.content- elif isinstance(assistant_msg.content, list):- for msg in assistant_msg.content:- if msg['type'] == 'text':- thought += msg['text']-- # Process each tool call to OpenHands action- for i, tool_call in enumerate(assistant_msg.tool_calls):- action: Action- logger.debug(f'Tool call in function_calling.py: {tool_call}')- try:- arguments = json.loads(tool_call.function.arguments)- except json.decoder.JSONDecodeError as e:- raise FunctionCallValidationError(- f'Failed to parse tool call arguments: {tool_call.function.arguments}'- ) from e-- # ================================================- # AgentFinishAction- # ================================================- if tool_call.function.name == FinishTool['function']['name']:- action = AgentFinishAction(- final_thought=arguments.get('message', ''),- )-- # ================================================- # ViewTool (ACI-based file viewer, READ-ONLY)- # ================================================- elif tool_call.function.name == ViewTool['function']['name']:- if 'path' not in arguments:- raise FunctionCallValidationError(- f'Missing required argument "path" in tool call {tool_call.function.name}'- )- action = FileReadAction(- path=arguments['path'],- impl_source=FileReadSource.OH_ACI,- view_range=arguments.get('view_range', None),- )-- # ================================================- # AgentThinkAction- # ================================================- elif tool_call.function.name == ThinkTool['function']['name']:- action = AgentThinkAction(thought=arguments.get('thought', ''))-- # ================================================- # GrepTool (file content search)- # ================================================- elif tool_call.function.name == GrepTool['function']['name']:- if 'pattern' not in arguments:- raise FunctionCallValidationError(- f'Missing required argument "pattern" in tool call {tool_call.function.name}'- )-- pattern = arguments['pattern']- path = arguments.get('path')- include = arguments.get('include')-- grep_cmd = grep_to_cmdrun(pattern, path, include)- action = CmdRunAction(command=grep_cmd, is_input=False)-- # ================================================- # GlobTool (file pattern matching)- # ================================================- elif tool_call.function.name == GlobTool['function']['name']:- if 'pattern' not in arguments:- raise FunctionCallValidationError(- f'Missing required argument "pattern" in tool call {tool_call.function.name}'- )-- pattern = arguments['pattern']- path = arguments.get('path', '.')-- glob_cmd = glob_to_cmdrun(pattern, path)- action = CmdRunAction(command=glob_cmd, is_input=False)-- # ================================================- # MCPAction (MCP)- # ================================================- elif mcp_tool_names and tool_call.function.name in mcp_tool_names:- action = MCPAction(- name=tool_call.function.name,- arguments=arguments,- )-- else:- raise FunctionCallNotExistsError(- f'Tool {tool_call.function.name} is not registered. (arguments: {arguments}). Please check the tool name and retry with an existing tool.'- )-- # We only add thought to the first action- if i == 0:- action = combine_thought(action, thought)- # Add metadata for tool calling- action.tool_call_metadata = ToolCallMetadata(- tool_call_id=tool_call.id,- function_name=tool_call.function.name,- model_response=response,- total_calls_in_response=len(assistant_msg.tool_calls),- )- actions.append(action)- else:- actions.append(- MessageAction(- content=str(assistant_msg.content) if assistant_msg.content else '',- wait_for_response=True,- )- )-- # Add response id to actions- # This will ensure we can match both actions without tool calls (e.g. MessageAction)- # and actions with tool calls (e.g. CmdRunAction, IPythonRunCellAction, etc.)- # with the token usage data- for action in actions:- action.response_id = response.id-- assert len(actions) >= 1- return actions---def get_tools() -> list[ChatCompletionToolParam]:- return [- ThinkTool,- FinishTool,- GrepTool,- GlobTool,- ViewTool,- ]diff --git a/openhands/agenthub/readonly_agent/prompts/additional_info.j2 b/openhands/agenthub/readonly_agent/prompts/additional_info.j2deleted file mode 100644index d709733f25..0000000000--- a/openhands/agenthub/readonly_agent/prompts/additional_info.j2+++ /dev/null@@ -1,29 +0,0 @@-{% if repository_info %}-<REPOSITORY_INFO>-At the user's request, repository {{ repository_info.repo_name }} has been cloned to the current working directory {{ repository_info.repo_directory }}.-{% if repository_info.branch_name %}The repository has been checked out to branch "{{ repository_info.branch_name }}".--IMPORTANT: You should work within the current branch "{{ repository_info.branch_name }}" unless- 1. the user explicitly instructs otherwise- 2. if the current branch is "main", "master", or another default branch where direct pushes may be unsafe-{% endif %}-</REPOSITORY_INFO>-{% endif %}-{% if repository_instructions -%}-<REPOSITORY_INSTRUCTIONS>-{{ repository_instructions }}-</REPOSITORY_INSTRUCTIONS>-{% endif %}-{% if runtime_info and (runtime_info.additional_agent_instructions or runtime_info.date) -%}-<RUNTIME_INFORMATION>-{% if runtime_info.working_dir %}-The current working directory is {{ runtime_info.working_dir }}-{% endif %}-{% if runtime_info.additional_agent_instructions %}-{{ runtime_info.additional_agent_instructions }}-{% endif %}-{% if runtime_info.date %}-Today's date is {{ runtime_info.date }} (UTC).-{% endif %}-</RUNTIME_INFORMATION>-{% endif %}diff --git a/openhands/agenthub/readonly_agent/prompts/in_context_learning_example.j2 b/openhands/agenthub/readonly_agent/prompts/in_context_learning_example.j2deleted file mode 100644index c400791c90..0000000000--- a/openhands/agenthub/readonly_agent/prompts/in_context_learning_example.j2+++ /dev/null@@ -1,101 +0,0 @@-Here's a running example of how to perform a task with the provided tools.----------------------- START OF EXAMPLE -----------------------USER: I need to find all TypeScript files in the project and then search for files that contain React components.--A: I'll help you find TypeScript files and React components. Let's break this down into steps:--1. First, let's use the glob tool to find all TypeScript files:-<function=glob>-<parameter=pattern>**/*.{ts,tsx}</parameter>-</function>--USER: EXECUTION RESULT of [glob]:-Below are the execution results of the glob command: rg --files . -g **/*.{ts,tsx} --sortr=modified | head -n 100--src/components/Header.tsx-src/components/Button.tsx-src/pages/Home.tsx-src/utils/types.ts-src/App.tsx-src/index.tsx--A: Great! Now let's search for files that likely contain React components by looking for patterns like "export" followed by "function" or "class":-<function=grep>-<parameter=pattern>export\s+(default\s+)?(function|class)</parameter>-<parameter=include>*.{ts,tsx}</parameter>-</function>--USER: EXECUTION RESULT of [grep]:-Below are the execution results of the search command: rg -li export\s+(default\s+)?(function|class) --sortr=modified --glob *.{ts,tsx} .--src/components/Header.tsx-src/components/Button.tsx-src/pages/Home.tsx-src/App.tsx--A: Let's examine one of these components to confirm it's a React component. I'll look at the Header component:-<function=view>-<parameter=path>src/components/Header.tsx</parameter>-</function>--USER: EXECUTION RESULT of [view]:- 1 import React from 'react';- 2- 3 interface HeaderProps {- 4 title: string;- 5 subtitle?: string;- 6 }- 7- 8 export function Header({ title, subtitle }: HeaderProps) {- 9 return (- 10 <header className="app-header">- 11 <h1>{title}</h1>- 12 {subtitle && <h2>{subtitle}</h2>}- 13 </header>- 14 );- 15 }--A: Let me also check the Button component to see its implementation:-<function=view>-<parameter=path>src/components/Button.tsx</parameter>-</function>--USER: EXECUTION RESULT of [view]:- 1 import React from 'react';- 2- 3 interface ButtonProps {- 4 onClick: () => void;- 5 children: React.ReactNode;- 6 variant?: 'primary' | 'secondary';- 7 }- 8- 9 export default function Button({ onClick, children, variant = 'primary' }: ButtonProps) {- 10 return (- 11 <button- 12 className={`btn btn-${variant}`}- 13 onClick={onClick}- 14 >- 15 {children}- 16 </button>- 17 );- 18 }--A: I've found several React components in the project. Here's a summary:--1. Found TypeScript files using glob pattern `**/*.{ts,tsx}`-2. Identified potential React components using grep pattern `export\s+(default\s+)?(function|class)`-3. Confirmed two components:- - `Header.tsx`: A function component that renders a header with title and optional subtitle- - `Button.tsx`: A reusable button component with primary/secondary variants--Would you like me to examine any other components or search for specific features within these components?-<function=finish>-</function>----------------------- END OF EXAMPLE -----------------------Do NOT assume the environment is the same as in the example above.----------------------- NEW TASK DESCRIPTION ---------------------diff --git a/openhands/agenthub/readonly_agent/prompts/in_context_learning_example_suffix.j2 b/openhands/agenthub/readonly_agent/prompts/in_context_learning_example_suffix.j2deleted file mode 100644index f9868b7b75..0000000000--- a/openhands/agenthub/readonly_agent/prompts/in_context_learning_example_suffix.j2+++ /dev/null@@ -1,3 +0,0 @@---------------------- END OF NEW TASK DESCRIPTION -----------------------PLEASE follow the format strictly! PLEASE EMIT ONE AND ONLY ONE FUNCTION CALL PER MESSAGE.diff --git a/openhands/agenthub/readonly_agent/prompts/microagent_info.j2 b/openhands/agenthub/readonly_agent/prompts/microagent_info.j2deleted file mode 100644index 264828fbe2..0000000000--- a/openhands/agenthub/readonly_agent/prompts/microagent_info.j2+++ /dev/null@@ -1,8 +0,0 @@-{% for agent_info in triggered_agents %}-<EXTRA_INFO>-The following information has been included based on a keyword match for "{{ agent_info.trigger }}".-It may or may not be relevant to the user's request.--{{ agent_info.content }}-</EXTRA_INFO>-{% endfor %}diff --git a/openhands/agenthub/readonly_agent/prompts/system_prompt.j2 b/openhands/agenthub/readonly_agent/prompts/system_prompt.j2deleted file mode 100644index 7cb8d46f29..0000000000--- a/openhands/agenthub/readonly_agent/prompts/system_prompt.j2+++ /dev/null@@ -1,34 +0,0 @@-You are OpenHands ReadOnlyAgent, a helpful AI assistant focused on code analysis and exploration. You can:-- Explore and analyze codebases-- Browse the web for relevant information-- Plan potential changes-- Answer questions about code--<CAPABILITIES>-β READ-ONLY TOOLS:-- view: Read file contents-- grep: Search for patterns-- glob: List matching files-- think: Analyze information-- web_read: Access web resources-- finish: Complete current task--β RESTRICTIONS:-- Cannot modify any files-- Cannot execute state-changing commands-</CAPABILITIES>--<GUIDELINES>-1. When analyzing code or answering questions:- - Be thorough and methodical- - Prioritize accuracy over speed- - Provide detailed explanations--2. For file operations:- - Always verify file locations before accessing- - Don't assume paths are relative to current directory--3. If asked to make changes:- - Explain you are read-only- - Recommend using CodeActAgent instead-</GUIDELINES>diff --git a/openhands/agenthub/readonly_agent/prompts/user_prompt.j2 b/openhands/agenthub/readonly_agent/prompts/user_prompt.j2deleted file mode 100644index e69de29bb2..0000000000diff --git a/openhands/agenthub/readonly_agent/readonly_agent.py b/openhands/agenthub/readonly_agent/readonly_agent.pydeleted file mode 100644index 13fe6a7181..0000000000--- a/openhands/agenthub/readonly_agent/readonly_agent.py+++ /dev/null@@ -1,90 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-"""ReadOnlyAgent - A specialized version of CodeActAgent that only uses read-only tools."""--import os-from typing import TYPE_CHECKING--from openhands.llm.llm_registry import LLMRegistry--if TYPE_CHECKING:- from litellm import ChatCompletionToolParam-- from openhands.events.action import Action- from openhands.llm.llm import ModelResponse--from openhands.agenthub.codeact_agent.codeact_agent import CodeActAgent-from openhands.agenthub.readonly_agent import (- function_calling as readonly_function_calling,-)-from openhands.core.config import AgentConfig-from openhands.core.logger import openhands_logger as logger-from openhands.utils.prompt import PromptManager---class ReadOnlyAgent(CodeActAgent):- VERSION = '1.0'- """- The ReadOnlyAgent is a specialized version of CodeActAgent that only uses read-only tools.-- This agent is designed for safely exploring codebases without making any changes.- It only has access to tools that don't modify the system: grep, glob, view, think, finish, web_read.-- Use this agent when you want to:- 1. Explore a codebase to understand its structure- 2. Search for specific patterns or code- 3. Research without making any changes-- When you're ready to make changes, switch to the regular CodeActAgent.- """-- def __init__(- self,- config: AgentConfig,- llm_registry: LLMRegistry,- ) -> None:- """Initializes a new instance of the ReadOnlyAgent class.-- Parameters:- - config (AgentConfig): The configuration for this agent- """- # Initialize the CodeActAgent class; some of it is overridden with class methods- super().__init__(config, llm_registry)-- logger.debug(- f'TOOLS loaded for ReadOnlyAgent: {", ".join([tool.get("function").get("name") for tool in self.tools])}'- )-- @property- def prompt_manager(self) -> PromptManager:- # Set up our own prompt manager- if self._prompt_manager is None:- self._prompt_manager = PromptManager(- prompt_dir=os.path.join(os.path.dirname(__file__), 'prompts'),- )- return self._prompt_manager-- def _get_tools(self) -> list['ChatCompletionToolParam']:- # Override the tools to only include read-only tools- # Get the read-only tools from our own function_calling module- return readonly_function_calling.get_tools()-- def set_mcp_tools(self, mcp_tools: list[dict]) -> None:- """Sets the list of MCP tools for the agent.-- Args:- - mcp_tools (list[dict]): The list of MCP tools.- """- logger.warning(- 'ReadOnlyAgent does not support MCP tools. MCP tools will be ignored by the agent.'- )-- def response_to_actions(self, response: 'ModelResponse') -> list['Action']:- return readonly_function_calling.response_to_actions(- response, mcp_tool_names=list(self.mcp_tools.keys())- )diff --git a/openhands/agenthub/readonly_agent/tools/__init__.py b/openhands/agenthub/readonly_agent/tools/__init__.pydeleted file mode 100644index d4adaded89..0000000000--- a/openhands/agenthub/readonly_agent/tools/__init__.py+++ /dev/null@@ -1,21 +0,0 @@-"""Tools for the ReadOnlyAgent.--This module defines the read-only tools for the ReadOnlyAgent.-"""--from .glob import GlobTool-from .grep import GrepTool-from .view import ViewTool--__all__ = [- 'ViewTool',- 'GrepTool',- 'GlobTool',-]--# Define the list of read-only tools-READ_ONLY_TOOLS = [- ViewTool,- GrepTool,- GlobTool,-]diff --git a/openhands/agenthub/readonly_agent/tools/glob.py b/openhands/agenthub/readonly_agent/tools/glob.pydeleted file mode 100644index 7ec4792db1..0000000000--- a/openhands/agenthub/readonly_agent/tools/glob.py+++ /dev/null@@ -1,38 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from litellm import ChatCompletionToolParam, ChatCompletionToolParamFunctionChunk--_GLOB_DESCRIPTION = """Fast file pattern matching tool.-* Supports glob patterns like "**/*.js" or "src/**/*.ts"-* Use this tool when you need to find files by name patterns-* Returns matching file paths sorted by modification time-* Only the first 100 results are returned. Consider narrowing your search with stricter glob patterns or provide path parameter if you need more results.-* When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead-"""--GlobTool = ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name='glob',- description=_GLOB_DESCRIPTION,- parameters={- 'type': 'object',- 'properties': {- 'pattern': {- 'type': 'string',- 'description': 'The glob pattern to match files (e.g., "**/*.js", "src/**/*.ts")',- },- 'path': {- 'type': 'string',- 'description': 'The directory (absolute path) to search in. Defaults to the current working directory.',- },- },- 'required': ['pattern'],- },- ),-)diff --git a/openhands/agenthub/readonly_agent/tools/grep.py b/openhands/agenthub/readonly_agent/tools/grep.pydeleted file mode 100644index 2395f7e9a1..0000000000--- a/openhands/agenthub/readonly_agent/tools/grep.py+++ /dev/null@@ -1,44 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from litellm import ChatCompletionToolParam, ChatCompletionToolParamFunctionChunk--_GREP_DESCRIPTION = """Fast content search tool.-* Searches file contents using regular expressions-* Supports full regex syntax (eg. "log.*Error", "function\\s+\\w+", etc.)-* Filter files by pattern with the include parameter (eg. "*.js", "*.{ts,tsx}")-* Returns matching file paths sorted by modification time.-* Only the first 100 results are returned. Consider narrowing your search with stricter regex patterns or provide path parameter if you need more results.-* Use this tool when you need to find files containing specific patterns-* When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead-"""--GrepTool = ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name='grep',- description=_GREP_DESCRIPTION,- parameters={- 'type': 'object',- 'properties': {- 'pattern': {- 'type': 'string',- 'description': 'The regex pattern to search for in file contents',- },- 'path': {- 'type': 'string',- 'description': 'The directory (absolute path) to search in. Defaults to the current working directory.',- },- 'include': {- 'type': 'string',- 'description': 'Optional file pattern to filter which files to search (e.g., "*.js", "*.{ts,tsx}")',- },- },- 'required': ['pattern'],- },- ),-)diff --git a/openhands/agenthub/readonly_agent/tools/view.py b/openhands/agenthub/readonly_agent/tools/view.pydeleted file mode 100644index c3d1295742..0000000000--- a/openhands/agenthub/readonly_agent/tools/view.py+++ /dev/null@@ -1,41 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from litellm import ChatCompletionToolParam, ChatCompletionToolParamFunctionChunk--_VIEW_DESCRIPTION = """Reads a file or list directories from the local filesystem.-* The path parameter must be an absolute path, not a relative path.-* If `path` is a file, `view` displays the result of applying `cat -n`; if `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep.-* You can optionally specify a line range to view (especially handy for long files), but it's recommended to read the whole file by not providing this parameter.-* For image files, the tool will display the image for you.-* For large files that exceed the display limit:- - The output will be truncated and marked with `<response clipped>`- - Use the `view_range` parameter to view specific sections after the truncation point-"""--ViewTool = ChatCompletionToolParam(- type='function',- function=ChatCompletionToolParamFunctionChunk(- name='view',- description=_VIEW_DESCRIPTION,- parameters={- 'type': 'object',- 'properties': {- 'path': {- 'type': 'string',- 'description': 'The absolute path to the file to read or directory to list',- },- 'view_range': {- 'description': 'Optional parameter of `view` command when `path` points to a *file*. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.',- 'items': {'type': 'integer'},- 'type': 'array',- },- },- 'required': ['path'],- },- ),-)diff --git a/openhands/agenthub/visualbrowsing_agent/README.md b/openhands/agenthub/visualbrowsing_agent/README.mddeleted file mode 100644index 60ce2c6d09..0000000000--- a/openhands/agenthub/visualbrowsing_agent/README.md+++ /dev/null@@ -1,7 +0,0 @@-# Browsing Agent Framework--This folder implements the AgentLab [generic agent](https://github.com/ServiceNow/AgentLab/tree/main/src/agentlab/agents/generic_agent) that enables full-featured web browsing. The observations given to the agent include set-of-marks annotated web-page screenshot, accessibility tree of the web-page and all the thoughts and actions from previous steps.--## Test run--Note that for browsing tasks, GPT-4/Claude is usually a requirement to get reasonable results, due to the complexity of the web page structures. This agent has been evaluated on the VisualWebArena benchmark and the CodeAct agent does not call this VisualBrowsingAgent. CodeAct agent uses has in-built support for browsing (e.g., via browse_url and browser tool).diff --git a/openhands/agenthub/visualbrowsing_agent/__init__.py b/openhands/agenthub/visualbrowsing_agent/__init__.pydeleted file mode 100644index 834e81a643..0000000000--- a/openhands/agenthub/visualbrowsing_agent/__init__.py+++ /dev/null@@ -1,6 +0,0 @@-from openhands.agenthub.visualbrowsing_agent.visualbrowsing_agent import (- VisualBrowsingAgent,-)-from openhands.controller.agent import Agent--Agent.register('VisualBrowsingAgent', VisualBrowsingAgent)diff --git a/openhands/agenthub/visualbrowsing_agent/visualbrowsing_agent.py b/openhands/agenthub/visualbrowsing_agent/visualbrowsing_agent.pydeleted file mode 100644index 6ddb8278a9..0000000000--- a/openhands/agenthub/visualbrowsing_agent/visualbrowsing_agent.py+++ /dev/null@@ -1,317 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-from browsergym.core.action.highlevel import HighLevelActionSet-from browsergym.utils.obs import flatten_axtree_to_str--from openhands.agenthub.browsing_agent.response_parser import BrowsingResponseParser-from openhands.controller.agent import Agent-from openhands.controller.state.state import State-from openhands.core.config import AgentConfig-from openhands.core.logger import openhands_logger as logger-from openhands.core.message import ImageContent, Message, TextContent-from openhands.events.action import (- Action,- AgentFinishAction,- BrowseInteractiveAction,- MessageAction,-)-from openhands.events.event import EventSource-from openhands.events.observation import BrowserOutputObservation-from openhands.events.observation.observation import Observation-from openhands.llm.llm_registry import LLMRegistry-from openhands.runtime.plugins import (- PluginRequirement,-)---def get_error_prefix(obs: BrowserOutputObservation) -> str:- # temporary fix for OneStopMarket to ignore timeout errors- if 'timeout' in obs.last_browser_action_error:- return ''- return f'## Error from previous action:\n{obs.last_browser_action_error}\n'---def create_goal_prompt(- goal: str, image_urls: list[str] | None-) -> tuple[str, list[str]]:- goal_txt: str = f"""\-# Instructions-Review the current state of the page and all other information to find the best possible next action to accomplish your goal. Your answer will be interpreted and executed by a program, make sure to follow the formatting instructions.--## Goal:-{goal}-"""- goal_image_urls = []- if image_urls is not None:- for idx, url in enumerate(image_urls):- goal_txt = goal_txt + f'Images: Goal input image ({idx + 1})\n'- goal_image_urls.append(url)- goal_txt += '\n'- return goal_txt, goal_image_urls---def create_observation_prompt(- axtree_txt: str,- tabs: str,- focused_element: str,- error_prefix: str,- som_screenshot: str | None,-) -> tuple[str, str | None]:- txt_observation = f"""-# Observation of current step:-{tabs}{axtree_txt}{focused_element}{error_prefix}-"""-- # screenshot + som: will be a non-empty string if present in observation- screenshot_url = None- if (som_screenshot is not None) and (len(som_screenshot) > 0):- txt_observation += 'Image: Current page screenshot (Note that only visible portion of webpage is present in the screenshot. You may need to scroll to view the remaining portion of the web-page.\n'- screenshot_url = som_screenshot- else:- logger.info('SOM Screenshot not present in observation!')- txt_observation += '\n'- return txt_observation, screenshot_url---def get_tabs(obs: BrowserOutputObservation) -> str:- prompt_pieces = ['\n## Currently open tabs:']- for page_index, page_url in enumerate(obs.open_pages_urls):- active_or_not = ' (active tab)' if page_index == obs.active_page_index else ''- prompt_piece = f"""\-Tab {page_index}{active_or_not}:-URL: {page_url}-"""- prompt_pieces.append(prompt_piece)- return '\n'.join(prompt_pieces) + '\n'---def get_axtree(axtree_txt: str) -> str:- bid_info = """\-Note: [bid] is the unique alpha-numeric identifier at the beginning of lines for each element in the AXTree. Always use bid to refer to elements in your actions.--"""- visible_tag_info = """\-Note: You can only interact with visible elements. If the "visible" tag is not present, the element is not visible on the page.--"""- return f'\n## AXTree:\n{bid_info}{visible_tag_info}{axtree_txt}\n'---def get_action_prompt(action_set: HighLevelActionSet) -> str:- action_set_generic_info = """\-Note: This action set allows you to interact with your environment. Most of them are python function executing playwright code. The primary way of referring to elements in the page is through bid which are specified in your observations.--"""- action_description = action_set.describe(- with_long_description=False,- with_examples=False,- )- action_prompt = f'# Action space:\n{action_set_generic_info}{action_description}\n'- return action_prompt---def get_history_prompt(prev_actions: list[BrowseInteractiveAction]) -> str:- history_prompt = ['# History of all previous interactions with the task:\n']- for i in range(len(prev_actions)):- history_prompt.append(f'## step {i + 1}')- history_prompt.append(- f'\nOuput thought and action: {prev_actions[i].thought} ```{prev_actions[i].browser_actions}```\n'- )- return '\n'.join(history_prompt) + '\n'---class VisualBrowsingAgent(Agent):- VERSION = '1.0'- """- VisualBrowsing Agent that can uses webpage screenshots during browsing.- """-- sandbox_plugins: list[PluginRequirement] = []- response_parser = BrowsingResponseParser()-- def __init__(self, config: AgentConfig, llm_registry: LLMRegistry) -> None:- """Initializes a new instance of the VisualBrowsingAgent class.-- Parameters:- - llm (LLM): The llm to be used by this agent- """- super().__init__(config, llm_registry)- # define a configurable action space, with chat functionality, web navigation, and webpage grounding using accessibility tree and HTML.- # see https://github.com/ServiceNow/BrowserGym/blob/main/core/src/browsergym/core/action/highlevel.py for more details- action_subsets = [- 'chat',- 'bid',- 'nav',- 'tab',- 'infeas',- ]- self.action_space = HighLevelActionSet(- subsets=action_subsets,- strict=False, # less strict on the parsing of the actions- multiaction=False,- )- self.action_prompt = get_action_prompt(self.action_space)- self.abstract_example = f"""-# Abstract Example--Here is an abstract version of the answer with description of the content of each tag. Make sure you follow this structure, but replace the content with your answer:--You must mandatorily think step by step. If you need to make calculations such as coordinates, write them here. Describe the effect that your previous action had on the current content of the page. In summary the next action I will perform is ```{self.action_space.example_action(abstract=True)}```-"""- self.concrete_example = """-# Concrete Example--Here is a concrete example of how to format your answer. Make sure to generate the action in the correct format ensuring that the action is present inside ``````:--Let's think step-by-step. From previous action I tried to set the value of year to "2022", using select_option, but it doesn't appear to be in the form. It may be a dynamic dropdown, I will try using click with the bid "324" and look at the response from the page. In summary the next action I will perform is ```click('324')```-"""- self.hints = """-Note:-* Make sure to use bid to identify elements when using commands.-* Interacting with combobox, dropdowns and auto-complete fields can be tricky, sometimes you need to use select_option, while other times you need to use fill or click and wait for the reaction of the page.--"""- self.reset()-- def reset(self) -> None:- """Resets the VisualBrowsingAgent's internal state."""- super().reset()- # Reset agent-specific counters but not LLM metrics- self.error_accumulator = 0-- def step(self, state: State) -> Action:- """Performs one step using the VisualBrowsingAgent.-- This includes gathering information on previous steps and prompting the model to make a browsing command to execute.-- Parameters:- - state (State): used to get updated info-- Returns:- - BrowseInteractiveAction(browsergym_command) - BrowserGym commands to run- - MessageAction(content) - Message action to run (e.g. ask for clarification)- - AgentFinishAction() - end the interaction- """- messages: list[Message] = []- prev_actions = []- cur_axtree_txt = ''- error_prefix = ''- focused_element = ''- tabs = ''- last_obs = None- last_action = None- set_of_marks = None # Initialize set_of_marks to None-- if len(state.view) == 1:- # for visualwebarena, webarena and miniwob++ eval, we need to retrieve the initial observation already in browser env- # initialize and retrieve the first observation by issuing an noop OP- # For non-benchmark browsing, the browser env starts with a blank page, and the agent is expected to first navigate to desired websites- return BrowseInteractiveAction(- browser_actions='noop(1000)', return_axtree=True- )-- for event in state.view:- if isinstance(event, BrowseInteractiveAction):- prev_actions.append(event)- last_action = event- elif isinstance(event, MessageAction) and event.source == EventSource.AGENT:- # agent has responded, task finished.- return AgentFinishAction(outputs={'content': event.content})- elif isinstance(event, Observation):- # Only process BrowserOutputObservation and skip other observation types- if not isinstance(event, BrowserOutputObservation):- continue- last_obs = event-- if len(prev_actions) >= 1: # ignore noop()- prev_actions = prev_actions[1:] # remove the first noop action-- # if the final BrowserInteractiveAction exec BrowserGym's send_msg_to_user,- # we should also send a message back to the user in OpenHands and call it a day- if (- isinstance(last_action, BrowseInteractiveAction)- and last_action.browsergym_send_msg_to_user- ):- return MessageAction(last_action.browsergym_send_msg_to_user)-- history_prompt = get_history_prompt(prev_actions)- if isinstance(last_obs, BrowserOutputObservation):- if last_obs.error:- # add error recovery prompt prefix- error_prefix = get_error_prefix(last_obs)- if len(error_prefix) > 0:- self.error_accumulator += 1- if self.error_accumulator > 5:- return MessageAction(- 'Too many errors encountered. Task failed.'- )- focused_element = '## Focused element:\nNone\n'- if last_obs.focused_element_bid is not None:- focused_element = (- f"## Focused element:\nbid='{last_obs.focused_element_bid}'\n"- )- tabs = get_tabs(last_obs)- try:- # IMPORTANT: keep AX Tree of full webpage, add visible and clickable tags- cur_axtree_txt = flatten_axtree_to_str(- last_obs.axtree_object,- extra_properties=last_obs.extra_element_properties,- with_visible=True,- with_clickable=True,- with_center_coords=False,- with_bounding_box_coords=False,- filter_visible_only=False,- filter_with_bid_only=False,- filter_som_only=False,- )- cur_axtree_txt = get_axtree(axtree_txt=cur_axtree_txt)- except Exception as e:- logger.error(- 'Error when trying to process the accessibility tree: %s', e- )- return MessageAction('Error encountered when browsing.')- set_of_marks = last_obs.set_of_marks- goal, image_urls = state.get_current_user_intent()-- if goal is None:- goal = state.inputs['task']- goal_txt, goal_images = create_goal_prompt(goal, image_urls)- observation_txt, som_screenshot = create_observation_prompt(- cur_axtree_txt, tabs, focused_element, error_prefix, set_of_marks- )- human_prompt: list[TextContent | ImageContent] = [- TextContent(type='text', text=goal_txt)- ]- if len(goal_images) > 0:- human_prompt.append(ImageContent(image_urls=goal_images))- human_prompt.append(TextContent(type='text', text=observation_txt))- if som_screenshot is not None:- human_prompt.append(ImageContent(image_urls=[som_screenshot]))- remaining_content = f"""-{history_prompt}\-{self.action_prompt}\-{self.hints}\-{self.abstract_example}\-{self.concrete_example}\-"""- human_prompt.append(TextContent(type='text', text=remaining_content))-- system_msg = """\-You are an agent trying to solve a web task based on the content of the page and user instructions. You can interact with the page and explore, and send messages to the user when you finish the task. Each time you submit an action it will be sent to the browser and you will receive a new page.-""".strip()-- messages.append(Message(role='system', content=[TextContent(text=system_msg)]))- messages.append(Message(role='user', content=human_prompt))-- response = self.llm.completion(- messages=messages,- temperature=0.0,- stop=[')```', ')\n```'],- )-- return self.response_parser.parse(response)diff --git a/openhands/core/config/agent_config.py b/openhands/core/config/agent_config.pyindex c93c8b9058..8f994ccfa1 100644--- a/openhands/core/config/agent_config.py+++ b/openhands/core/config/agent_config.py@@ -25,7 +25,7 @@ class AgentConfig(BaseModel):llm_config: str | None = Field(default=None)"""The name of the llm config to use. If specified, this will override global llm config."""classpath: str | None = Field(default=None)- """The classpath of the agent to use. To be used for custom agents that are not defined in the openhands.agenthub package."""+ """The classpath of the agent to use. To be used for custom agents."""system_prompt_filename: str = Field(default='system_prompt.j2')"""Filename of the system prompt template file within the agent's prompt directory. Defaults to 'system_prompt.j2'."""enable_browsing: bool = Field(default=True)diff --git a/openhands/core/download.py b/openhands/core/download.pydeleted file mode 100644index 9d978ecaba..0000000000--- a/openhands/core/download.py+++ /dev/null@@ -1,9 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-# Run this file to trigger a model download-import openhands.agenthub # noqa F401 (we import this to get the agents registered)diff --git a/openhands/core/main.py b/openhands/core/main.pyindex 379f660a76..567154034c 100644--- a/openhands/core/main.py+++ b/openhands/core/main.py@@ -13,7 +13,6 @@ import sysfrom pathlib import Pathfrom typing import Callable, Protocol-import openhands.agenthub # noqa F401 (we import this to get the agents registered)from openhands.controller.replay import ReplayManagerfrom openhands.controller.state.state import Statefrom openhands.core.config import (diff --git a/openhands/core/setup.py b/openhands/core/setup.pyindex acfdfa4253..b589827939 100644--- a/openhands/core/setup.py+++ b/openhands/core/setup.py@@ -12,7 +12,6 @@ from typing import Callablefrom pydantic import SecretStr-import openhands.agenthub # noqa F401 (we import this to get the agents registered)from openhands.controller import AgentControllerfrom openhands.controller.agent import Agentfrom openhands.controller.state.state import Statediff --git a/openhands/llm/fn_call_converter.py b/openhands/llm/fn_call_converter.pyindex 7f8ccb138d..d5be059324 100644--- a/openhands/llm/fn_call_converter.py+++ b/openhands/llm/fn_call_converter.py@@ -69,8 +69,6 @@ def refine_prompt(prompt: str) -> str:return prompt-# NOTE: we need to make sure these examples are always in-sync with the tool interface designed in openhands/agenthub/codeact_agent/function_calling.py-# Example snippets for each toolTOOL_EXAMPLES = {'execute_bash': {diff --git a/openhands/runtime/utils/edit.py b/openhands/runtime/utils/edit.pyindex 37075a016a..3014811fb2 100644--- a/openhands/runtime/utils/edit.py+++ b/openhands/runtime/utils/edit.py@@ -414,32 +414,4 @@ class FileEditRuntimeMixin(FileEditRuntimeInterface):def correct_edit(self, file_content: str, error_obs: ErrorObservation, retry_num: int = 0) -> Observation:- import openhands.agenthub.codeact_agent.function_calling as codeact_function_calling- from openhands.agenthub.codeact_agent.tools import LLMBasedFileEditTool- from openhands.llm.llm_utils import check_tools-- _retry_num = retry_num + 1- if self.check_retry_num(_retry_num):- return error_obs- tools = check_tools([LLMBasedFileEditTool], self.draft_editor_llm.config)- messages = [- {'role': 'system', 'content': CORRECT_SYS_MSG},- {- 'role': 'user',- 'content': CORRECT_USER_MSG.format(- file_content=file_content, lint_error=error_obs.content- ),- },- ]- params: dict = {'messages': messages, 'tools': tools}- try:- response = self.draft_editor_llm.completion(**params)- actions = codeact_function_calling.response_to_actions(response)- if len(actions) != 1:- return error_obs- for action in actions:- if isinstance(action, FileEditAction):- return self.llm_based_edit(action, _retry_num)- except Exception as e:- logger.error(f'correct lint error is failed: {e}')return error_obsdiff --git a/openhands/server/app.py b/openhands/server/app.pyindex 52ca9c418e..7c6c19b399 100644--- a/openhands/server/app.py+++ b/openhands/server/app.py@@ -22,7 +22,6 @@ from fastapi import ()from fastapi.responses import JSONResponse-import openhands.agenthub # noqa F401 (we import this to get the agents registered)from openhands.app_server import v1_routerfrom openhands.app_server.config import get_app_lifespan_servicefrom openhands.app_server.status.status_router import router as health_routerdiff --git a/openhands/utils/prompt.py b/openhands/utils/prompt.pyindex 85c010138f..f74d94255c 100644--- a/openhands/utils/prompt.py+++ b/openhands/utils/prompt.py@@ -87,10 +87,8 @@ class PromptManager:raise FileNotFoundError(f'Prompt file {template_path} not found')def get_system_message(self, **context) -> str:- from openhands.agenthub.codeact_agent.tools.prompt import refine_prompt-system_message = self.system_template.render(**context).strip()- return refine_prompt(system_message)+ return system_messagedef get_example_user_message(self) -> str:"""This is an initial user message that can be provided to the agentdiff --git a/tests/runtime/test_glob_and_grep.py b/tests/runtime/test_glob_and_grep.pydeleted file mode 100644index 0b7f81724b..0000000000--- a/tests/runtime/test_glob_and_grep.py+++ /dev/null@@ -1,303 +0,0 @@-"""Tests for the command helper functions in function_calling.py."""--import os--import pytest-from conftest import (- _close_test_runtime,- _load_runtime,-)--from openhands.agenthub.readonly_agent.function_calling import (- glob_to_cmdrun,- grep_to_cmdrun,-)-from openhands.core.logger import openhands_logger as logger-from openhands.events.action import CmdRunAction-from openhands.events.observation import CmdOutputObservation, ErrorObservation--# Skip all tests in this file if running with CLIRuntime,-# as they depend on `rg` (ripgrep) which is not guaranteed to be available.-# The underlying ReadOnlyAgent tools (GrepTool, GlobTool) also currently depend on `rg`.-# TODO: implement a fallback version of these tools that uses `find` and `grep`.-pytestmark = pytest.mark.skipif(- os.environ.get('TEST_RUNTIME') == 'cli',- reason="CLIRuntime: ReadOnlyAgent's GrepTool/GlobTool tests require `rg` (ripgrep), which may not be installed.",-)---def _run_cmd_action(runtime, custom_command: str):- action = CmdRunAction(command=custom_command)- logger.info(action, extra={'msg_type': 'ACTION'})- obs = runtime.run_action(action)- assert isinstance(obs, (CmdOutputObservation, ErrorObservation))- logger.info(obs, extra={'msg_type': 'OBSERVATION'})- return obs---def test_grep_to_cmdrun_basic():- """Test basic pattern with no special characters."""- cmd = grep_to_cmdrun('function', 'src')- assert 'rg -li function' in cmd- assert 'Below are the execution results' in cmd-- # With include parameter- cmd = grep_to_cmdrun('error', 'src', '*.js')- assert 'rg -li error' in cmd- assert "--glob '*.js'" in cmd- assert 'Below are the execution results' in cmd---def test_grep_to_cmdrun_quotes(temp_dir, runtime_cls, run_as_openhands):- """Test patterns with different types of quotes."""- runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)- try:- # Double quotes in pattern- cmd = grep_to_cmdrun(r'const message = "Hello"', '/workspace')- assert 'rg -li' in cmd-- # Verify command works by executing it on a test file- setup_cmd = 'echo \'const message = "Hello";\' > /workspace/test_quotes.js'- obs = _run_cmd_action(runtime, setup_cmd)- assert obs.exit_code == 0-- obs = _run_cmd_action(runtime, cmd)- assert obs.exit_code == 0- assert '/workspace/test_quotes.js' in obs.content-- # Single quotes in pattern- cmd = grep_to_cmdrun("function\\('test'\\)", '/workspace')- assert 'rg -li' in cmd-- setup_cmd = 'echo "function(\'test\') {}" > /workspace/test_quotes2.js'- obs = _run_cmd_action(runtime, setup_cmd)- assert obs.exit_code == 0-- obs = _run_cmd_action(runtime, cmd)- assert obs.exit_code == 0- assert '/workspace/test_quotes2.js' in obs.content- finally:- _close_test_runtime(runtime)---def test_grep_to_cmdrun_special_chars(runtime_cls, run_as_openhands, temp_dir):- """Test patterns with special shell characters."""- runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)- try:- # Create test directory and files with special pattern content- setup_cmd = """- mkdir -p /workspace/test_special_patterns && \- echo "testing x && y || z pattern" > /workspace/test_special_patterns/logical.txt && \- echo "function() { return x; }" > /workspace/test_special_patterns/function.txt && \- echo "using \\$variable here" > /workspace/test_special_patterns/dollar.txt && \- echo "using \\`backticks\\` here" > /workspace/test_special_patterns/backticks.txt && \- echo "line with \\n newline chars" > /workspace/test_special_patterns/newline.txt && \- echo "matching *.js wildcard" > /workspace/test_special_patterns/wildcard.txt && \- echo "testing x > y redirection" > /workspace/test_special_patterns/redirect.txt && \- echo "testing a | b pipe" > /workspace/test_special_patterns/pipe.txt && \- echo "line with #comment" > /workspace/test_special_patterns/comment.txt && \- echo "CSS \\!important rule" > /workspace/test_special_patterns/bang.txt- """- obs = _run_cmd_action(runtime, setup_cmd)- assert obs.exit_code == 0, 'Failed to set up test files'-- special_patterns = [- r'x && y \|\| z', # Shell logical operators (escaping pipe)- r'function\(\) \{ return x; \}', # Properly escaped braces and parentheses- r'\$variable', # Dollar sign- # r"`backticks`", # Backticks- r'\\n newline', # Escaped characters- r'\*\.js', # Wildcards (escaped)- r'x > y', # Redirection- r'a \| b', # Pipe (escaped)- r'#comment', # Hash- # r"!important", # Bang- ]-- for pattern in special_patterns:- # Generate the grep command using our helper function- cmd = grep_to_cmdrun(pattern, '/workspace/test_special_patterns')- assert 'rg -li' in cmd- assert 'Below are the execution results of the search command:' in cmd-- # Execute the command- obs = _run_cmd_action(runtime, cmd)-- # Verify the command executed successfully- assert 'command not found' not in obs.content- assert 'syntax error' not in obs.content- assert 'unexpected' not in obs.content-- # Check that the pattern was found in the appropriate file- if '&&' in pattern:- assert 'logical.txt' in obs.content- elif 'function' in pattern:- assert 'function.txt' in obs.content- elif '$variable' in pattern:- assert 'dollar.txt' in obs.content- # elif "backticks" in pattern:- # assert "backticks.txt" in obs.content- elif '\\n newline' in pattern:- assert 'newline.txt' in obs.content- elif '*' in pattern:- assert 'wildcard.txt' in obs.content- elif '>' in pattern:- assert 'redirect.txt' in obs.content- elif '|' in pattern:- assert 'pipe.txt' in obs.content- elif '#comment' in pattern:- assert 'comment.txt' in obs.content- # elif "!important" in pattern:- # assert "bang.txt" in obs.content- finally:- _close_test_runtime(runtime)---def test_grep_to_cmdrun_paths_with_spaces(runtime_cls, run_as_openhands, temp_dir):- """Test paths with spaces and special characters."""- runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)- try:- # Create test files with content in paths with spaces- setup_cmd = """- mkdir -p "src/my project" "test files/unit tests" "src/special$chars" "path with spaces and $pecial ch@rs" && \- echo "function searchablePattern() { return true; }" > "src/my project/test.js" && \- echo "function testFunction() { return 42; }" > "test files/unit tests/test.js" && \- echo "function specialFunction() { return null; }" > "src/special$chars/test.js" && \- echo "function weirdFunction() { return []; }" > "path with spaces and $pecial ch@rs/test.js"- """- obs = _run_cmd_action(runtime, setup_cmd)- assert obs.exit_code == 0, 'Failed to set up test files'-- special_paths = [- 'src/my project',- 'test files/unit tests',- ]-- for path in special_paths:- # Generate grep command and execute it- cmd = grep_to_cmdrun('function', path)- assert 'rg -li' in cmd-- obs = _run_cmd_action(runtime, cmd)- assert obs.exit_code == 0, f'Grep command failed for path: {path}'- assert 'function' in obs.content, (- f'Expected pattern not found in output for path: {path}'- )-- # Verify the actual file was found- if path == 'src/my project':- assert 'src/my project/test.js' in obs.content- elif path == 'test files/unit tests':- assert 'test files/unit tests/test.js' in obs.content- finally:- _close_test_runtime(runtime)---def test_glob_to_cmdrun_basic():- """Test basic glob patterns."""- cmd = glob_to_cmdrun('*.js', 'src')- assert "rg --files src -g '*.js'" in cmd- assert 'head -n 100' in cmd- assert 'echo "Below are the execution results of the glob command:' in cmd-- # Default path- cmd = glob_to_cmdrun('*.py')- assert "rg --files . -g '*.py'" in cmd- assert 'head -n 100' in cmd- assert 'echo "Below are the execution results of the glob command:' in cmd---def test_glob_to_cmdrun_special_patterns(runtime_cls, run_as_openhands, temp_dir):- """Test glob patterns with special characters."""- runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)- try:- # Create test files matching the patterns we'll test- setup_cmd = r"""- mkdir -p src/components src/utils && \- touch src/file1.js src/file2.js src/file9.js && \- touch src/components/comp.jsx src/components/comp.tsx && \- touch src/$special-file.js && \- touch src/temp1.js src/temp2.js && \- touch src/file.js src/file.ts src/file.jsx && \- touch "src/weird\`file\`.js" && \- touch "src/file with spaces.js"- """- obs = _run_cmd_action(runtime, setup_cmd)- assert obs.exit_code == 0, 'Failed to set up test files'-- special_patterns = [- '**/*.js', # Double glob- '**/{*.jsx,*.tsx}', # Braces- 'file[0-9].js', # Character class- 'temp?.js', # Single character wildcard- 'file.{js,ts,jsx}', # Multiple extensions- 'file with spaces.js', # Spaces- ]-- for pattern in special_patterns:- cmd = glob_to_cmdrun(pattern, 'src')- logger.info(f'Command: {cmd}')- # Execute the command- obs = _run_cmd_action(runtime, cmd)- assert obs.exit_code == 0, f'Glob command failed for pattern: {pattern}'-- # Verify expected files are found- if pattern == '**/*.js':- assert 'file1.js' in obs.content- assert 'file2.js' in obs.content- elif pattern == '**/{*.jsx,*.tsx}':- assert 'comp.jsx' in obs.content- assert 'comp.tsx' in obs.content- elif pattern == 'file[0-9].js':- assert 'file1.js' in obs.content- assert 'file2.js' in obs.content- assert 'file9.js' in obs.content- elif pattern == 'temp?.js':- assert 'temp1.js' in obs.content- assert 'temp2.js' in obs.content- elif pattern == 'file.{js,ts,jsx}':- assert 'file.js' in obs.content- assert 'file.ts' in obs.content- assert 'file.jsx' in obs.content- elif pattern == 'file with spaces.js':- assert 'file with spaces.js' in obs.content- finally:- _close_test_runtime(runtime)---def test_glob_to_cmdrun_paths_with_spaces(runtime_cls, run_as_openhands, temp_dir):- """Test paths with spaces and special characters for glob command."""- runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)- try:- # Create test directories with spaces and special characters- setup_cmd = """- mkdir -p "project files/src" "test results/unit tests" "weird$path/code" "path with spaces and $pecial ch@rs" && \- touch "project files/src/file1.js" "project files/src/file2.js" && \- touch "test results/unit tests/test1.js" "test results/unit tests/test2.js" && \- touch "weird$path/code/weird1.js" "weird$path/code/weird2.js" && \- touch "path with spaces and $pecial ch@rs/special1.js" "path with spaces and $pecial ch@rs/special2.js"- """- obs = _run_cmd_action(runtime, setup_cmd)- assert obs.exit_code == 0, 'Failed to set up test files'-- special_paths = [- 'project files/src',- 'test results/unit tests',- ]-- for path in special_paths:- cmd = glob_to_cmdrun('*.js', path)-- # Execute the command- obs = _run_cmd_action(runtime, cmd)- assert obs.exit_code == 0, f'Glob command failed for path: {path}'-- # Verify expected files are found in each path- if path == 'project files/src':- assert 'file1.js' in obs.content- assert 'file2.js' in obs.content- elif path == 'test results/unit tests':- assert 'test1.js' in obs.content- assert 'test2.js' in obs.content- finally:- _close_test_runtime(runtime)diff --git a/tests/unit/agenthub/browsing_agent/test_browsing_agent_parser.py b/tests/unit/agenthub/browsing_agent/test_browsing_agent_parser.pydeleted file mode 100644index 6392f90c0a..0000000000--- a/tests/unit/agenthub/browsing_agent/test_browsing_agent_parser.py+++ /dev/null@@ -1,83 +0,0 @@-import pytest--from openhands.agenthub.browsing_agent.response_parser import (- BrowseInteractiveAction,- BrowsingResponseParser,-)--- 'action_str, expected',- [- ("click('81'", "click('81')```"),- (- '"We need to search the internet\n```goto("google.com")',- '"We need to search the internet\n```goto("google.com")```',- ),- ("```click('81'", "```click('81')```"),- ("click('81')", "click('81')```"),- (- "send_msg_to_user('The server might not be running or accessible. Please check the server status and try again.')",- "send_msg_to_user('The server might not be running or accessible. Please check the server status and try again.')```",- ),- ],-)-def test_parse_response(action_str: str, expected: str) -> None:- # BrowsingResponseParser.parse_response- parser = BrowsingResponseParser()- response = {'choices': [{'message': {'content': action_str}}]}- result = parser.parse_response(response)- assert result == expected--- 'action_str, expected_browser_actions, expected_thought, expected_msg_content',- [- ("click('81')```", "click('81')", '', ''),- ("```click('81')```", "click('81')", '', ''),- (- "We need to perform a click\n```click('81')",- "click('81')",- 'We need to perform a click',- '',- ),- (- 'Tell the user that the city was built in 1751.\n```send_msg_to_user("Based on the results of my search, the city was built in 1751.")',- 'send_msg_to_user("Based on the results of my search, the city was built in 1751.")',- 'Tell the user that the city was built in 1751.',- 'Based on the results of my search, the city was built in 1751.',- ),- (- 'Tell the user that the city was built in 1751.\n```send_msg_to_user("Based on the results of my search, the city was built in 1751.")```',- 'send_msg_to_user("Based on the results of my search, the city was built in 1751.")',- 'Tell the user that the city was built in 1751.',- 'Based on the results of my search, the city was built in 1751.',- ),- (- "Tell the user that the city was built in 1751.\n```send_msg_to_user('Based on the results of my search, the city was built in 1751.')```",- "send_msg_to_user('Based on the results of my search, the city was built in 1751.')",- 'Tell the user that the city was built in 1751.',- 'Based on the results of my search, the city was built in 1751.',- ),- (- "send_msg_to_user('The server might not be running or accessible. Please check the server status and try again.'))```",- "send_msg_to_user('The server might not be running or accessible. Please check the server status and try again.'))",- '',- 'The server might not be running or accessible. Please check the server status and try again.',- ),- ],-)-def test_parse_action(- action_str: str,- expected_browser_actions: str,- expected_thought: str,- expected_msg_content: str,-) -> None:- # BrowsingResponseParser.parse_action- parser = BrowsingResponseParser()- action = parser.parse_action(action_str)- assert isinstance(action, BrowseInteractiveAction)- assert action.browser_actions == expected_browser_actions- assert action.thought == expected_thought- assert action.browsergym_send_msg_to_user == expected_msg_content- assert action.return_axtree is False # Default value should be Falsediff --git a/tests/unit/agenthub/test_agents.py b/tests/unit/agenthub/test_agents.pydeleted file mode 100644index 09f28e991c..0000000000--- a/tests/unit/agenthub/test_agents.py+++ /dev/null@@ -1,549 +0,0 @@-from typing import Union-from unittest.mock import Mock--import pytest-from litellm import ChatCompletionMessageToolCall--from openhands.agenthub.codeact_agent.codeact_agent import CodeActAgent-from openhands.agenthub.codeact_agent.function_calling import (- response_to_actions as codeact_response_to_actions,-)-from openhands.agenthub.codeact_agent.tools import (- BrowserTool,- IPythonTool,- LLMBasedFileEditTool,- ThinkTool,- create_cmd_run_tool,- create_str_replace_editor_tool,-)-from openhands.agenthub.codeact_agent.tools.browser import (- _BROWSER_DESCRIPTION,- _BROWSER_TOOL_DESCRIPTION,-)-from openhands.agenthub.readonly_agent.function_calling import (- response_to_actions as readonly_response_to_actions,-)-from openhands.agenthub.readonly_agent.readonly_agent import ReadOnlyAgent-from openhands.agenthub.readonly_agent.tools import (- GlobTool,- GrepTool,-)-from openhands.controller.state.state import State-from openhands.core.config import AgentConfig, LLMConfig-from openhands.core.config.openhands_config import OpenHandsConfig-from openhands.core.exceptions import FunctionCallNotExistsError-from openhands.core.message import ImageContent, Message, TextContent-from openhands.events.action import (- CmdRunAction,- MessageAction,-)-from openhands.events.action.message import SystemMessageAction-from openhands.events.event import EventSource-from openhands.events.observation.commands import (- CmdOutputObservation,-)-from openhands.events.tool import ToolCallMetadata-from openhands.llm.llm_registry import LLMRegistry-from openhands.memory.condenser import View---def create_llm_registry():- def _get_registry(llm_config):- config = OpenHandsConfig()- config.set_llm_config(llm_config)- return LLMRegistry(config=config)-- return _get_registry--[email protected](params=['CodeActAgent', 'ReadOnlyAgent'])-def agent_class(request):- if request.param == 'CodeActAgent':- return CodeActAgent- else:- from openhands.agenthub.readonly_agent.readonly_agent import ReadOnlyAgent-- return ReadOnlyAgent---def agent(agent_class, create_llm_registry) -> Union[CodeActAgent, ReadOnlyAgent]:- llm_config = LLMConfig(model='gpt-4o', api_key='test_key')- config = AgentConfig()- agent = agent_class(config=config, llm_registry=create_llm_registry(llm_config))- agent.llm = Mock()- agent.llm.config = Mock()- agent.llm.config.max_message_chars = 1000- return agent---def test_agent_with_default_config_has_default_tools(create_llm_registry):- llm_config = LLMConfig(model='gpt-4o', api_key='test_key')- config = AgentConfig()- codeact_agent = CodeActAgent(- config=config, llm_registry=create_llm_registry(llm_config)- )- assert len(codeact_agent.tools) > 0- default_tool_names = [tool['function']['name'] for tool in codeact_agent.tools]- assert {- 'browser',- 'execute_bash',- 'execute_ipython_cell',- 'finish',- 'str_replace_editor',- 'think',- }.issubset(default_tool_names)---def mock_state() -> State:- state = Mock(spec=State)- state.history = []- state.extra_data = {}-- return state---def test_reset(agent):- # Add some state- action = MessageAction(content='test')- action._source = EventSource.AGENT- agent.pending_actions.append(action)-- # Create a mock state with initial user message- mock_state = Mock(spec=State)- initial_user_message = MessageAction(content='Initial user message')- initial_user_message._source = EventSource.USER- mock_state.history = [initial_user_message]-- # Reset- agent.reset()-- # Verify state is cleared- assert len(agent.pending_actions) == 0---def test_step_with_pending_actions(agent):- # Add a pending action- pending_action = MessageAction(content='test')- pending_action._source = EventSource.AGENT- agent.pending_actions.append(pending_action)-- # Create a mock state with initial user message- mock_state = Mock(spec=State)- initial_user_message = MessageAction(content='Initial user message')- initial_user_message._source = EventSource.USER- mock_state.history = [initial_user_message]-- # Step should return the pending action- result = agent.step(mock_state)- assert result == pending_action- assert len(agent.pending_actions) == 0---def test_cmd_run_tool():- CmdRunTool = create_cmd_run_tool()- assert CmdRunTool['type'] == 'function'- assert CmdRunTool['function']['name'] == 'execute_bash'- assert 'command' in CmdRunTool['function']['parameters']['properties']- assert 'security_risk' in CmdRunTool['function']['parameters']['properties']- assert CmdRunTool['function']['parameters']['required'] == [- 'command',- 'security_risk',- ]---def test_ipython_tool():- assert IPythonTool['type'] == 'function'- assert IPythonTool['function']['name'] == 'execute_ipython_cell'- assert 'code' in IPythonTool['function']['parameters']['properties']- assert 'security_risk' in IPythonTool['function']['parameters']['properties']- assert IPythonTool['function']['parameters']['required'] == [- 'code',- 'security_risk',- ]---def test_llm_based_file_edit_tool():- assert LLMBasedFileEditTool['type'] == 'function'- assert LLMBasedFileEditTool['function']['name'] == 'edit_file'-- properties = LLMBasedFileEditTool['function']['parameters']['properties']- assert 'path' in properties- assert 'content' in properties- assert 'start' in properties- assert 'end' in properties- assert 'security_risk' in properties-- assert LLMBasedFileEditTool['function']['parameters']['required'] == [- 'path',- 'content',- 'security_risk',- ]---def test_str_replace_editor_tool():- StrReplaceEditorTool = create_str_replace_editor_tool()- assert StrReplaceEditorTool['type'] == 'function'- assert StrReplaceEditorTool['function']['name'] == 'str_replace_editor'-- properties = StrReplaceEditorTool['function']['parameters']['properties']- assert 'command' in properties- assert 'path' in properties- assert 'file_text' in properties- assert 'old_str' in properties- assert 'new_str' in properties- assert 'insert_line' in properties- assert 'security_risk' in properties-- assert StrReplaceEditorTool['function']['parameters']['required'] == [- 'command',- 'path',- 'security_risk',- ]---def test_browser_tool():- assert BrowserTool['type'] == 'function'- assert BrowserTool['function']['name'] == 'browser'- assert 'code' in BrowserTool['function']['parameters']['properties']- assert 'security_risk' in BrowserTool['function']['parameters']['properties']- assert BrowserTool['function']['parameters']['required'] == [- 'code',- 'security_risk',- ]- # Check that the description includes all the functions- description = _BROWSER_TOOL_DESCRIPTION- assert 'goto(' in description- assert 'go_back()' in description- assert 'go_forward()' in description- assert 'noop(' in description- assert 'scroll(' in description- assert 'fill(' in description- assert 'select_option(' in description- assert 'click(' in description- assert 'dblclick(' in description- assert 'hover(' in description- assert 'press(' in description- assert 'focus(' in description- assert 'clear(' in description- assert 'drag_and_drop(' in description- assert 'upload_file(' in description-- # Test BrowserTool definition- assert BrowserTool['type'] == 'function'- assert BrowserTool['function']['name'] == 'browser'- assert BrowserTool['function']['description'] == _BROWSER_DESCRIPTION- assert BrowserTool['function']['parameters']['type'] == 'object'- assert 'code' in BrowserTool['function']['parameters']['properties']- assert BrowserTool['function']['parameters']['required'] == [- 'code',- 'security_risk',- ]- assert (- BrowserTool['function']['parameters']['properties']['code']['type'] == 'string'- )- assert 'description' in BrowserTool['function']['parameters']['properties']['code']---def test_response_to_actions_invalid_tool():- # Test response with invalid tool call- mock_response = Mock()- mock_response.choices = [Mock()]- mock_response.choices[0].message = Mock()- mock_response.choices[0].message.content = 'Invalid tool'- mock_response.choices[0].message.tool_calls = [Mock()]- mock_response.choices[0].message.tool_calls[0].id = 'tool_call_10'- mock_response.choices[0].message.tool_calls[0].function = Mock()- mock_response.choices[0].message.tool_calls[0].function.name = 'invalid_tool'- mock_response.choices[0].message.tool_calls[0].function.arguments = '{}'-- with pytest.raises(FunctionCallNotExistsError):- codeact_response_to_actions(mock_response)- with pytest.raises(FunctionCallNotExistsError):- readonly_response_to_actions(mock_response)---def test_step_with_no_pending_actions(mock_state: State, create_llm_registry):- # Mock the LLM response- mock_response = Mock()- mock_response.id = 'mock_id'- mock_response.total_calls_in_response = 1- mock_response.choices = [Mock()]- mock_response.choices[0].message = Mock()- mock_response.choices[0].message.content = 'Task completed'- mock_response.choices[0].message.tool_calls = []-- mock_config = Mock()- mock_config.model = 'mock_model'-- llm = Mock()- llm.config = mock_config- llm.completion = Mock(return_value=mock_response)- llm.is_function_calling_active = Mock(return_value=True) # Enable function calling- llm.is_caching_prompt_active = Mock(return_value=False)- llm.format_messages_for_llm = Mock(return_value=[]) # Mock message formatting-- # Create agent with mocked LLM- llm_config = LLMConfig(model='gpt-4o', api_key='test_key')- config = AgentConfig()- config.enable_prompt_extensions = False- agent = CodeActAgent(config=config, llm_registry=create_llm_registry(llm_config))- # Replace the LLM with our mock after creation- agent.llm = llm-- # Test step with no pending actions- mock_state.latest_user_message = None- mock_state.latest_user_message_id = None- mock_state.latest_user_message_timestamp = None- mock_state.latest_user_message_cause = None- mock_state.latest_user_message_timeout = None- mock_state.latest_user_message_llm_metrics = None- mock_state.latest_user_message_tool_call_metadata = None-- # Add initial user message to history- initial_user_message = MessageAction(content='Initial user message')- initial_user_message._source = EventSource.USER- mock_state.history = [initial_user_message]-- # Mock the view returned by condenser- mock_view = View(events=mock_state.history)- mock_state.view = mock_view-- action = agent.step(mock_state)- assert isinstance(action, MessageAction)- assert action.content == 'Task completed'--[email protected]('agent_type', ['CodeActAgent', 'ReadOnlyAgent'])-def test_correct_tool_description_loaded_based_on_model_name(- agent_type, create_llm_registry-):- """Tests that the simplified tool descriptions are loaded for specific models."""- o3_mock_config = LLMConfig(model='mock_o3_model', api_key='test_key')- if agent_type == 'CodeActAgent':- from openhands.agenthub.codeact_agent.codeact_agent import CodeActAgent-- agent_class = CodeActAgent- else:- from openhands.agenthub.readonly_agent.readonly_agent import ReadOnlyAgent-- agent_class = ReadOnlyAgent-- agent = agent_class(- config=AgentConfig(),- llm_registry=create_llm_registry(o3_mock_config),- )- for tool in agent.tools:- # Assert all descriptions have less than 1024 characters- assert len(tool['function']['description']) < 1024-- sonnect_mock_config = LLMConfig(model='mock_sonnet_model', api_key='test_key')- agent = agent_class(- config=AgentConfig(),- llm_registry=create_llm_registry(sonnect_mock_config),- )- # Assert existence of the detailed tool descriptions that are longer than 1024 characters- if agent_type == 'CodeActAgent':- # This only holds for CodeActAgent- assert any(len(tool['function']['description']) > 1024 for tool in agent.tools)---def test_mismatched_tool_call_events_and_auto_add_system_message(- agent, mock_state: State-):- """Tests that the agent can convert mismatched tool call events (i.e., an observation with no corresponding action) into messages.-- This also tests that the system message is automatically added to the event stream if SystemMessageAction is not present.- """- tool_call_metadata = Mock(- spec=ToolCallMetadata,- model_response=Mock(- id='model_response_0',- choices=[- Mock(- message=Mock(- role='assistant',- content='',- tool_calls=[- Mock(spec=ChatCompletionMessageToolCall, id='tool_call_0')- ],- )- )- ],- ),- tool_call_id='tool_call_0',- function_name='foo',- )-- action = CmdRunAction('foo')- action._source = EventSource.AGENT- action.tool_call_metadata = tool_call_metadata-- observation = CmdOutputObservation(content='', command_id=0, command='foo')- observation.tool_call_metadata = tool_call_metadata-- # Add initial user message- initial_user_message = MessageAction(content='Initial user message')- initial_user_message._source = EventSource.USER-- # When both events are provided, the agent should get three messages:- # 1. The system message (added automatically for backward compatibility)- # 2. The action message- # 3. The observation message- mock_state.history = [initial_user_message, action, observation]- messages = agent._get_messages(mock_state.history, initial_user_message, set())- assert len(messages) == 4 # System + initial user + action + observation- assert messages[0].role == 'system' # First message should be the system message- assert (- messages[1].role == 'user'- ) # Second message should be the initial user message- assert messages[2].role == 'assistant' # Third message should be the action- assert messages[3].role == 'tool' # Fourth message should be the observation-- # The same should hold if the events are presented out-of-order- mock_state.history = [initial_user_message, observation, action]- messages = agent._get_messages(mock_state.history, initial_user_message, set())- assert len(messages) == 4- assert messages[0].role == 'system' # First message should be the system message- assert (- messages[1].role == 'user'- ) # Second message should be the initial user message-- # If only one of the two events is present, then we should just get the system message- # plus any valid message from the event- mock_state.history = [initial_user_message, action]- messages = agent._get_messages(mock_state.history, initial_user_message, set())- assert (- len(messages) == 2- ) # System + initial user message, action is waiting for its observation- assert messages[0].role == 'system'- assert messages[1].role == 'user'-- mock_state.history = [initial_user_message, observation]- messages = agent._get_messages(mock_state.history, initial_user_message, set())- assert (- len(messages) == 2- ) # System + initial user message, observation has no matching action- assert messages[0].role == 'system'- assert messages[1].role == 'user'---def test_grep_tool():- assert GrepTool['type'] == 'function'- assert GrepTool['function']['name'] == 'grep'-- properties = GrepTool['function']['parameters']['properties']- assert 'pattern' in properties- assert 'path' in properties- assert 'include' in properties-- assert GrepTool['function']['parameters']['required'] == ['pattern']---def test_glob_tool():- assert GlobTool['type'] == 'function'- assert GlobTool['function']['name'] == 'glob'-- properties = GlobTool['function']['parameters']['properties']- assert 'pattern' in properties- assert 'path' in properties-- assert GlobTool['function']['parameters']['required'] == ['pattern']---def test_think_tool():- assert ThinkTool['type'] == 'function'- assert ThinkTool['function']['name'] == 'think'-- properties = ThinkTool['function']['parameters']['properties']- assert 'thought' in properties-- assert ThinkTool['function']['parameters']['required'] == ['thought']---def test_enhance_messages_adds_newlines_between_consecutive_user_messages(- agent: CodeActAgent,-):- """Test that _enhance_messages adds newlines between consecutive user messages."""- # Create consecutive user messages with various content types- messages = [- # First user message with TextContent only- Message(role='user', content=[TextContent(text='First user message')]),- # Second user message with TextContent only - should get newlines added- Message(role='user', content=[TextContent(text='Second user message')]),- # Assistant message- Message(role='assistant', content=[TextContent(text='Assistant response')]),- # Third user message with TextContent only - shouldn't get newlines- Message(role='user', content=[TextContent(text='Third user message')]),- # Fourth user message with ImageContent first, TextContent second - should get newlines- Message(- role='user',- content=[- ImageContent(image_urls=['https://example.com/image.jpg']),- TextContent(text='Fourth user message with image'),- ],- ),- # Fifth user message with only ImageContent - no TextContent to modify- Message(- role='user',- content=[- ImageContent(image_urls=['https://example.com/another-image.jpg'])- ],- ),- ]-- # Call _enhance_messages- enhanced_messages = agent.conversation_memory._apply_user_message_formatting(- messages- )-- # Verify newlines were added correctly- assert enhanced_messages[1].content[0].text.startswith('\n\n')- assert enhanced_messages[1].content[0].text == '\n\nSecond user message'-- # Third message follows assistant, so shouldn't have newlines- assert not enhanced_messages[3].content[0].text.startswith('\n\n')- assert enhanced_messages[3].content[0].text == 'Third user message'-- # Fourth message follows user, so should have newlines in its TextContent- assert enhanced_messages[4].content[1].text.startswith('\n\n')- assert enhanced_messages[4].content[1].text == '\n\nFourth user message with image'-- # Fifth message only has ImageContent, no TextContent to modify- assert len(enhanced_messages[5].content) == 1- assert isinstance(enhanced_messages[5].content[0], ImageContent)---def test_get_system_message(create_llm_registry):- """Test that the Agent.get_system_message method returns a SystemMessageAction."""- # Create a mock agent- config = AgentConfig()- llm_config = LLMConfig(model='gpt-4o', api_key='test_key')- agent = CodeActAgent(config=config, llm_registry=create_llm_registry(llm_config))-- result = agent.get_system_message()-- # Check that the system message was created correctly- assert isinstance(result, SystemMessageAction)- assert 'You are OpenHands agent' in result.content- assert len(result.tools) > 0- assert any(tool['function']['name'] == 'execute_bash' for tool in result.tools)- assert result._source == EventSource.AGENT---def test_step_raises_error_if_no_initial_user_message(- agent: CodeActAgent, mock_state: State-):- """Tests that step raises ValueError if the initial user message is not found."""- # Ensure history does NOT contain a user MessageAction- assistant_message = MessageAction(content='Assistant message')- assistant_message._source = EventSource.AGENT- mock_state.history = [assistant_message]- # Mock the condenser to return the history as is- agent.condenser = Mock()- agent.condenser.condensed_history.return_value = View(events=mock_state.history)-- with pytest.raises(ValueError, match='Initial user message not found'):- agent.step(mock_state)diff --git a/tests/unit/agenthub/test_function_calling.py b/tests/unit/agenthub/test_function_calling.pydeleted file mode 100644index 3067accf0d..0000000000--- a/tests/unit/agenthub/test_function_calling.py+++ /dev/null@@ -1,274 +0,0 @@-"""Test function calling module."""--import json-from unittest.mock import patch--import pytest-from litellm import ModelResponse--from openhands.agenthub.codeact_agent.function_calling import response_to_actions-from openhands.core.exceptions import FunctionCallValidationError-from openhands.events.action import (- BrowseInteractiveAction,- CmdRunAction,- FileEditAction,- FileReadAction,- IPythonRunCellAction,-)-from openhands.events.event import FileEditSource, FileReadSource---def create_mock_response(function_name: str, arguments: dict) -> ModelResponse:- """Helper function to create a mock response with a tool call."""- return ModelResponse(- id='mock-id',- choices=[- {- 'message': {- 'tool_calls': [- {- 'function': {- 'name': function_name,- 'arguments': json.dumps(arguments),- },- 'id': 'mock-tool-call-id',- 'type': 'function',- }- ],- 'content': None,- 'role': 'assistant',- },- 'index': 0,- 'finish_reason': 'tool_calls',- }- ],- )---def test_execute_bash_valid():- """Test execute_bash with valid arguments."""- response = create_mock_response(- 'execute_bash', {'command': 'ls', 'is_input': 'false', 'security_risk': 'LOW'}- )- actions = response_to_actions(response)- assert len(actions) == 1- assert isinstance(actions[0], CmdRunAction)- assert actions[0].command == 'ls'- assert actions[0].is_input is False-- # Test with timeout parameter- with patch.object(CmdRunAction, 'set_hard_timeout') as mock_set_hard_timeout:- response_with_timeout = create_mock_response(- 'execute_bash',- {- 'command': 'ls',- 'is_input': 'false',- 'timeout': 30,- 'security_risk': 'LOW',- },- )- actions_with_timeout = response_to_actions(response_with_timeout)-- # Verify set_hard_timeout was called with the correct value- mock_set_hard_timeout.assert_called_once_with(30.0)-- assert len(actions_with_timeout) == 1- assert isinstance(actions_with_timeout[0], CmdRunAction)- assert actions_with_timeout[0].command == 'ls'- assert actions_with_timeout[0].is_input is False---def test_execute_bash_missing_command():- """Test execute_bash with missing command argument."""- response = create_mock_response(- 'execute_bash', {'is_input': 'false', 'security_risk': 'LOW'}- )- with pytest.raises(FunctionCallValidationError) as exc_info:- response_to_actions(response)- assert 'Missing required argument "command"' in str(exc_info.value)---def test_execute_ipython_cell_valid():- """Test execute_ipython_cell with valid arguments."""- response = create_mock_response(- 'execute_ipython_cell', {'code': "print('hello')", 'security_risk': 'LOW'}- )- actions = response_to_actions(response)- assert len(actions) == 1- assert isinstance(actions[0], IPythonRunCellAction)- assert actions[0].code == "print('hello')"---def test_execute_ipython_cell_missing_code():- """Test execute_ipython_cell with missing code argument."""- response = create_mock_response('execute_ipython_cell', {'security_risk': 'LOW'})- with pytest.raises(FunctionCallValidationError) as exc_info:- response_to_actions(response)- assert 'Missing required argument "code"' in str(exc_info.value)---def test_edit_file_valid():- """Test edit_file with valid arguments."""- response = create_mock_response(- 'edit_file',- {- 'path': '/path/to/file',- 'content': 'file content',- 'start': 1,- 'end': 10,- 'security_risk': 'LOW',- },- )- actions = response_to_actions(response)- assert len(actions) == 1- assert isinstance(actions[0], FileEditAction)- assert actions[0].path == '/path/to/file'- assert actions[0].content == 'file content'- assert actions[0].start == 1- assert actions[0].end == 10---def test_edit_file_missing_required():- """Test edit_file with missing required arguments."""- # Missing path- response = create_mock_response(- 'edit_file', {'content': 'content', 'security_risk': 'LOW'}- )- with pytest.raises(FunctionCallValidationError) as exc_info:- response_to_actions(response)- assert 'Missing required argument "path"' in str(exc_info.value)-- # Missing content- response = create_mock_response(- 'edit_file', {'path': '/path/to/file', 'security_risk': 'LOW'}- )- with pytest.raises(FunctionCallValidationError) as exc_info:- response_to_actions(response)- assert 'Missing required argument "content"' in str(exc_info.value)---def test_str_replace_editor_valid():- """Test str_replace_editor with valid arguments."""- # Test view command- response = create_mock_response(- 'str_replace_editor',- {'command': 'view', 'path': '/path/to/file', 'security_risk': 'LOW'},- )- actions = response_to_actions(response)- assert len(actions) == 1- assert isinstance(actions[0], FileReadAction)- assert actions[0].path == '/path/to/file'- assert actions[0].impl_source == FileReadSource.OH_ACI-- # Test other commands- response = create_mock_response(- 'str_replace_editor',- {- 'command': 'str_replace',- 'path': '/path/to/file',- 'old_str': 'old',- 'new_str': 'new',- 'security_risk': 'LOW',- },- )- actions = response_to_actions(response)- assert len(actions) == 1- assert isinstance(actions[0], FileEditAction)- assert actions[0].path == '/path/to/file'- assert actions[0].impl_source == FileEditSource.OH_ACI---def test_str_replace_editor_missing_required():- """Test str_replace_editor with missing required arguments."""- # Missing command- response = create_mock_response(- 'str_replace_editor', {'path': '/path/to/file', 'security_risk': 'LOW'}- )- with pytest.raises(FunctionCallValidationError) as exc_info:- response_to_actions(response)- assert 'Missing required argument "command"' in str(exc_info.value)-- # Missing path- response = create_mock_response(- 'str_replace_editor', {'command': 'view', 'security_risk': 'LOW'}- )- with pytest.raises(FunctionCallValidationError) as exc_info:- response_to_actions(response)- assert 'Missing required argument "path"' in str(exc_info.value)---def test_browser_valid():- """Test browser with valid arguments."""- response = create_mock_response(- 'browser', {'code': "click('button-1')", 'security_risk': 'LOW'}- )- actions = response_to_actions(response)- assert len(actions) == 1- assert isinstance(actions[0], BrowseInteractiveAction)- assert actions[0].browser_actions == "click('button-1')"- assert actions[0].return_axtree is False # Default value should be False---def test_browser_missing_code():- """Test browser with missing code argument."""- response = create_mock_response('browser', {'security_risk': 'LOW'})- with pytest.raises(FunctionCallValidationError) as exc_info:- response_to_actions(response)- assert 'Missing required argument "code"' in str(exc_info.value)---def test_invalid_json_arguments():- """Test handling of invalid JSON in arguments."""- response = ModelResponse(- id='mock-id',- choices=[- {- 'message': {- 'tool_calls': [- {- 'function': {- 'name': 'execute_bash',- 'arguments': 'invalid json',- },- 'id': 'mock-tool-call-id',- 'type': 'function',- }- ],- 'content': None,- 'role': 'assistant',- },- 'index': 0,- 'finish_reason': 'tool_calls',- }- ],- )- with pytest.raises(FunctionCallValidationError) as exc_info:- response_to_actions(response)- assert 'Failed to parse tool call arguments' in str(exc_info.value)---def test_unexpected_argument_handling():- """Test that unexpected arguments in function calls are properly handled.-- This test reproduces issue #8369 Example 4 where an unexpected argument- (old_str_prefix) causes a TypeError.- """- response = create_mock_response(- 'str_replace_editor',- {- 'command': 'str_replace',- 'path': '/test/file.py',- 'old_str': 'def test():\n pass',- 'new_str': 'def test():\n return True',- 'old_str_prefix': 'some prefix', # Unexpected argument- 'security_risk': 'LOW',- },- )-- # Test that the function raises a FunctionCallValidationError- with pytest.raises(FunctionCallValidationError) as exc_info:- response_to_actions(response)-- # Verify the error message mentions the unexpected argument- assert 'old_str_prefix' in str(exc_info.value)- assert 'Unexpected argument' in str(exc_info.value)diff --git a/tests/unit/agenthub/test_prompt_caching.py b/tests/unit/agenthub/test_prompt_caching.pydeleted file mode 100644index 2435b1320a..0000000000--- a/tests/unit/agenthub/test_prompt_caching.py+++ /dev/null@@ -1,139 +0,0 @@-import pytest-from litellm import ModelResponse--from openhands.agenthub.codeact_agent.codeact_agent import CodeActAgent-from openhands.core.config import AgentConfig, LLMConfig-from openhands.core.config.openhands_config import OpenHandsConfig-from openhands.events.action import MessageAction-from openhands.llm.llm_registry import LLMRegistry---def llm_config():- return LLMConfig(- model='claude-3-5-sonnet-20241022',- api_key='fake',- caching_prompt=True,- )---def llm_registry():- registry = LLMRegistry(config=OpenHandsConfig())- return registry---def codeact_agent(llm_registry):- config = AgentConfig()- agent = CodeActAgent(config, llm_registry)- return agent---def response_mock(content: str, tool_call_id: str):- class MockModelResponse:- def __init__(self, content, tool_call_id):- self.choices = [- {- 'message': {- 'content': content,- 'tool_calls': [- {- 'function': {- 'id': tool_call_id,- 'name': 'execute_bash',- 'arguments': '{}',- }- }- ],- }- }- ]-- def model_dump(self):- return {'choices': self.choices}-- return ModelResponse(**MockModelResponse(content, tool_call_id).model_dump())---def test_get_messages(codeact_agent: CodeActAgent):- # Add some events to history- history = list()- # Add system message action- system_message_action = codeact_agent.get_system_message()- history.append(system_message_action)-- message_action_1 = MessageAction('Initial user message')- message_action_1._source = 'user'- history.append(message_action_1)- message_action_2 = MessageAction('Sure!')- message_action_2._source = 'agent'- history.append(message_action_2)- message_action_3 = MessageAction('Hello, agent!')- message_action_3._source = 'user'- history.append(message_action_3)- message_action_4 = MessageAction('Hello, user!')- message_action_4._source = 'agent'- history.append(message_action_4)- message_action_5 = MessageAction('Laaaaaaaast!')- message_action_5._source = 'user'- history.append(message_action_5)-- codeact_agent.reset()- messages = codeact_agent._get_messages(history, message_action_1, set())-- assert (- len(messages) == 6- ) # System, initial user + user message, agent message, last user message- assert messages[0].role == 'system' # system message- assert messages[0].content[0].cache_prompt # system message should be cached- assert messages[1].role == 'user'- assert messages[1].content[0].text.endswith('Initial user message')- # we add cache breakpoint to only the last user message- assert not messages[1].content[0].cache_prompt-- assert messages[3].role == 'user'- assert messages[3].content[0].text == ('Hello, agent!')- assert not messages[3].content[0].cache_prompt- assert messages[4].role == 'assistant'- assert messages[4].content[0].text == 'Hello, user!'- assert not messages[4].content[0].cache_prompt- assert messages[5].role == 'user'- assert messages[5].content[0].text.startswith('Laaaaaaaast!')- assert messages[5].content[0].cache_prompt---def test_get_messages_prompt_caching(codeact_agent: CodeActAgent):- history = list()- # Add system message action- system_message_action = codeact_agent.get_system_message()- history.append(system_message_action)-- # Add multiple user and agent messages- initial_user_message = None # Keep track of the first user message- for i in range(15):- message_action_user = MessageAction(f'User message {i}')- message_action_user._source = 'user'- if initial_user_message is None:- initial_user_message = message_action_user # Store the first one- history.append(message_action_user)- message_action_agent = MessageAction(f'Agent message {i}')- message_action_agent._source = 'agent'- history.append(message_action_agent)-- codeact_agent.reset()- messages = codeact_agent._get_messages(history, initial_user_message, set())-- # Check that only the last two user messages have cache_prompt=True- cached_user_messages = [- msg- for msg in messages- if msg.role in ('user', 'system') and msg.content[0].cache_prompt- ]- assert (- len(cached_user_messages) == 2- ) # Including the initial system message + last user message-- # Verify that these are indeed the last user message (from start)- assert cached_user_messages[0].content[0].text.startswith('You are OpenHands agent')- assert cached_user_messages[1].content[0].text.startswith('User message 14')diff --git a/tests/unit/agenthub/test_str_replace_editor_tool.py b/tests/unit/agenthub/test_str_replace_editor_tool.pydeleted file mode 100644index 28beeaeefd..0000000000--- a/tests/unit/agenthub/test_str_replace_editor_tool.py+++ /dev/null@@ -1,225 +0,0 @@-"""Tests for str_replace_editor tool workspace path detection."""--import os-import sys-from unittest.mock import patch--import pytest--# Import the functions directly to avoid dependency issues-sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../..'))--try:- from openhands.agenthub.codeact_agent.tools.str_replace_editor import (- _get_workspace_mount_path_from_env,- create_str_replace_editor_tool,- )-except ImportError:- # If import fails due to dependencies, skip these tests- pytest.skip(- 'Cannot import str_replace_editor due to missing dependencies',- allow_module_level=True,- )---class TestWorkspacePathDetection:- """Test workspace path detection logic."""-- def test_docker_runtime_ignores_sandbox_volumes(self):- """Test that DockerRuntime ignores SANDBOX_VOLUMES and uses /workspace."""- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/host/app:/workspace:rw'}):- result = _get_workspace_mount_path_from_env(runtime_type='docker')- assert result == '/workspace'-- def test_remote_runtime_ignores_sandbox_volumes(self):- """Test that RemoteRuntime ignores SANDBOX_VOLUMES and uses /workspace."""- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/host/app:/workspace:rw'}):- result = _get_workspace_mount_path_from_env(runtime_type='remote')- assert result == '/workspace'-- def test_e2b_runtime_ignores_sandbox_volumes(self):- """Test that E2BRuntime ignores SANDBOX_VOLUMES and uses /workspace."""- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/host/app:/workspace:rw'}):- result = _get_workspace_mount_path_from_env(runtime_type='e2b')- assert result == '/workspace'-- def test_local_runtime_uses_sandbox_volumes(self):- """Test that LocalRuntime uses host path from SANDBOX_VOLUMES."""- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/host/app:/workspace:rw'}):- result = _get_workspace_mount_path_from_env(runtime_type='local')- assert result == '/host/app'-- def test_local_runtime_multiple_mounts(self):- """Test LocalRuntime with multiple mounts, finds /workspace mount."""- with patch.dict(- os.environ,- {- 'SANDBOX_VOLUMES': '/tmp:/tmp:rw,/home/user/project:/workspace:rw,/var:/var:rw'- },- ):- result = _get_workspace_mount_path_from_env(runtime_type='local')- assert result == '/home/user/project'-- def test_cli_runtime_multiple_mounts(self):- """Test CLIRuntime with multiple mounts, finds /workspace mount."""- with patch.dict(- os.environ,- {- 'SANDBOX_VOLUMES': '/tmp:/tmp:rw,/home/user/project:/workspace:rw,/var:/var:rw'- },- ):- result = _get_workspace_mount_path_from_env(runtime_type='cli')- assert result == '/home/user/project'-- def test_local_runtime_no_workspace_mount(self):- """Test LocalRuntime with no /workspace mount falls back to current directory."""- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/tmp:/tmp:rw,/var:/var:rw'}):- result = _get_workspace_mount_path_from_env(runtime_type='local')- assert result == os.getcwd()-- def test_local_runtime_no_sandbox_volumes(self):- """Test LocalRuntime with no SANDBOX_VOLUMES falls back to current directory."""- with patch.dict(os.environ, {}, clear=True):- result = _get_workspace_mount_path_from_env(runtime_type='local')- assert result == os.getcwd()-- def test_local_runtime_empty_sandbox_volumes(self):- """Test LocalRuntime with empty SANDBOX_VOLUMES falls back to current directory."""- with patch.dict(os.environ, {'SANDBOX_VOLUMES': ''}):- result = _get_workspace_mount_path_from_env(runtime_type='local')- assert result == os.getcwd()-- def test_relative_path_conversion(self):- """Test that relative paths in SANDBOX_VOLUMES are converted to absolute."""- with patch.dict(- os.environ, {'SANDBOX_VOLUMES': './relative/path:/workspace:rw'}- ):- result = _get_workspace_mount_path_from_env(runtime_type='local')- # Should be converted to absolute path- assert os.path.isabs(result)- assert result.endswith('relative/path')-- def test_unknown_runtime_type(self):- """Test that unknown runtime types use default container path."""- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/host/app:/workspace:rw'}):- result = _get_workspace_mount_path_from_env(runtime_type='unknown')- assert result == '/workspace'-- def test_none_runtime_type(self):- """Test that None runtime type uses default container path."""- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/host/app:/workspace:rw'}):- result = _get_workspace_mount_path_from_env(runtime_type=None)- assert result == '/workspace'---class TestToolCreation:- """Test tool creation with dynamic workspace paths."""-- def test_tool_creation_docker_runtime(self):- """Test tool creation in DockerRuntime shows /workspace in description."""- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/host/app:/workspace:rw'}):- tool = create_str_replace_editor_tool(runtime_type='docker')- path_description = tool['function']['parameters']['properties']['path'][- 'description'- ]- assert '/workspace/file.py' in path_description- assert '/workspace`.' in path_description- # Should not contain host paths- assert '/host/app' not in path_description-- def test_tool_creation_local_runtime(self):- """Test tool creation in LocalRuntime shows host path in description."""- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/host/app:/workspace:rw'}):- tool = create_str_replace_editor_tool(runtime_type='local')- path_description = tool['function']['parameters']['properties']['path'][- 'description'- ]- assert '/host/app/file.py' in path_description- assert '/host/app`.' in path_description-- def test_tool_creation_cli_runtime(self):- """Test tool creation in CLIRuntime shows host path in description."""- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/host/app:/workspace:rw'}):- tool = create_str_replace_editor_tool(runtime_type='cli')- path_description = tool['function']['parameters']['properties']['path'][- 'description'- ]- assert '/host/app/file.py' in path_description- assert '/host/app`.' in path_description-- def test_tool_creation_remote_runtime(self):- """Test tool creation in RemoteRuntime shows /workspace in description."""- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/host/app:/workspace:rw'}):- tool = create_str_replace_editor_tool(runtime_type='remote')- path_description = tool['function']['parameters']['properties']['path'][- 'description'- ]- assert '/workspace/file.py' in path_description- assert '/workspace`.' in path_description- # Should not contain host paths- assert '/host/app' not in path_description-- def test_tool_creation_e2b_runtime(self):- """Test tool creation in E2BRuntime shows /workspace in description."""- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/host/app:/workspace:rw'}):- tool = create_str_replace_editor_tool(runtime_type='e2b')- path_description = tool['function']['parameters']['properties']['path'][- 'description'- ]- assert '/workspace/file.py' in path_description- assert '/workspace`.' in path_description- # Should not contain host paths- assert '/host/app' not in path_description-- def test_tool_creation_explicit_workspace_path(self):- """Test tool creation with explicitly provided workspace path."""- tool = create_str_replace_editor_tool(- workspace_mount_path_in_sandbox='/custom/path'- )- path_description = tool['function']['parameters']['properties']['path'][- 'description'- ]- assert '/custom/path/file.py' in path_description- assert '/custom/path`.' in path_description-- def test_tool_creation_short_description(self):- """Test tool creation with short description still has correct path."""- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/host/app:/workspace:rw'}):- tool = create_str_replace_editor_tool(- use_short_description=True, runtime_type='local'- )- path_description = tool['function']['parameters']['properties']['path'][- 'description'- ]- assert '/host/app/file.py' in path_description- assert '/host/app`.' in path_description---class TestEdgeCases:- """Test edge cases and error conditions."""-- def test_malformed_sandbox_volumes(self):- """Test handling of malformed SANDBOX_VOLUMES."""- # Missing colon separator - falls back to current directory for local/CLI- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/host/app/workspace'}):- result = _get_workspace_mount_path_from_env(runtime_type='local')- assert result == os.getcwd()-- # Only one part - falls back to current directory for local/CLI- with patch.dict(os.environ, {'SANDBOX_VOLUMES': '/host/app:'}):- result = _get_workspace_mount_path_from_env(runtime_type='local')- assert result == os.getcwd()-- def test_workspace_mount_with_different_permissions(self):- """Test /workspace mount with different permission strings."""- test_cases = [- '/host/app:/workspace:ro',- '/host/app:/workspace:rw',- '/host/app:/workspace', # No permissions- '/host/app:/workspace:rw,size=100m', # Extra options- ]-- for sandbox_volumes in test_cases:- with patch.dict(os.environ, {'SANDBOX_VOLUMES': sandbox_volumes}):- result = _get_workspace_mount_path_from_env(runtime_type='local')- assert result == '/host/app', f'Failed for: {sandbox_volumes}'diff --git a/tests/unit/memory/test_conversation_memory.py b/tests/unit/memory/test_conversation_memory.pydeleted file mode 100644index 24e0b0510e..0000000000--- a/tests/unit/memory/test_conversation_memory.py+++ /dev/null@@ -1,1719 +0,0 @@-import os-import shutil-from unittest.mock import MagicMock, Mock--import pytest-from litellm import ChatCompletionMessageToolCall--from openhands.controller.state.state import State-from openhands.core.config.agent_config import AgentConfig-from openhands.core.message import ImageContent, Message, TextContent-from openhands.events.action import (- AgentFinishAction,- CmdRunAction,- MessageAction,-)-from openhands.events.action.message import SystemMessageAction-from openhands.events.event import (- Event,- EventSource,- FileEditSource,- FileReadSource,-)-from openhands.events.observation import CmdOutputObservation-from openhands.events.observation.agent import (- MicroagentKnowledge,- RecallObservation,-)-from openhands.events.observation.browse import BrowserOutputObservation-from openhands.events.observation.commands import (- CmdOutputMetadata,- IPythonRunCellObservation,-)-from openhands.events.observation.delegate import AgentDelegateObservation-from openhands.events.observation.error import ErrorObservation-from openhands.events.observation.files import FileEditObservation, FileReadObservation-from openhands.events.observation.reject import UserRejectObservation-from openhands.events.recall_type import RecallType-from openhands.events.tool import ToolCallMetadata-from openhands.memory.conversation_memory import ConversationMemory-from openhands.utils.prompt import PromptManager, RepositoryInfo, RuntimeInfo---def agent_config():- return AgentConfig(- enable_prompt_extensions=True,- enable_som_visual_browsing=True,- disabled_microagents=['disabled_agent'],- )---def conversation_memory(agent_config):- prompt_manager = MagicMock(spec=PromptManager)- prompt_manager.get_system_message.return_value = 'System message'- prompt_manager.build_workspace_context.return_value = (- 'Formatted repository and runtime info'- )-- # Make build_microagent_info return the actual content from the triggered agents- def build_microagent_info(triggered_agents):- if not triggered_agents:- return ''- return '\n'.join(agent.content for agent in triggered_agents)-- prompt_manager.build_microagent_info.side_effect = build_microagent_info- return ConversationMemory(agent_config, prompt_manager)---def prompt_dir(tmp_path):- # Copy contents from "openhands/agenthub/codeact_agent" to the temp directory- shutil.copytree(- 'openhands/agenthub/codeact_agent/prompts', tmp_path, dirs_exist_ok=True- )-- # Return the temporary directory path- return tmp_path---def mock_state():- state = MagicMock(spec=State)- state.history = []- return state---def mock_prompt_manager():- return MagicMock()---def test_process_events_with_message_action(conversation_memory):- """Test that MessageAction is processed correctly."""- # Create a system message action- system_message = SystemMessageAction(content='System message')- system_message._source = EventSource.AGENT-- # Create user and assistant messages- user_message = MessageAction(content='Hello')- user_message._source = EventSource.USER- assistant_message = MessageAction(content='Hi there')- assistant_message._source = EventSource.AGENT-- # Process events- messages = conversation_memory.process_events(- condensed_history=[system_message, user_message, assistant_message],- initial_user_action=user_message,- max_message_chars=None,- vision_is_active=False,- )-- # Check that the messages were processed correctly- assert len(messages) == 3- assert messages[0].role == 'system'- assert messages[0].content[0].text == 'System message'---# Test cases for _ensure_system_message-def test_ensure_system_message_adds_if_missing(conversation_memory):- """Test that _ensure_system_message adds a system message if none exists."""- user_message = MessageAction(content='User message')- user_message._source = EventSource.USER- events = [user_message]- conversation_memory._ensure_system_message(events)- assert len(events) == 2- assert isinstance(events[0], SystemMessageAction)- assert events[0].content == 'System message' # From fixture- assert isinstance(events[1], MessageAction) # Original event is still there---def test_ensure_system_message_does_nothing_if_present(conversation_memory):- """Test that _ensure_system_message does nothing if a system message is already present."""- original_system_message = SystemMessageAction(content='Existing system message')- user_message = MessageAction(content='User message')- user_message._source = EventSource.USER- events = [- original_system_message,- user_message,- ]- original_events = list(events) # Copy before modification- conversation_memory._ensure_system_message(events)- assert events == original_events # List should be unchanged---# Test cases for _ensure_initial_user_message-def initial_user_action():- msg = MessageAction(content='Initial User Message')- msg._source = EventSource.USER- return msg---def test_ensure_initial_user_message_adds_if_only_system(- conversation_memory, initial_user_action-):- """Test adding the initial user message when only the system message exists."""- system_message = SystemMessageAction(content='System')- system_message._source = EventSource.AGENT- events = [system_message]- # Pass empty set for forgotten_event_ids (no events have been condensed)- conversation_memory._ensure_initial_user_message(events, initial_user_action, set())- assert len(events) == 2- assert events[0] == system_message- assert events[1] == initial_user_action---def test_ensure_initial_user_message_correct_already_present(- conversation_memory, initial_user_action-):- """Test that nothing changes if the correct initial user message is at index 1."""- system_message = SystemMessageAction(content='System')- agent_message = MessageAction(content='Assistant')- agent_message._source = EventSource.USER- events = [- system_message,- initial_user_action,- agent_message,- ]- original_events = list(events)- # Pass empty set for forgotten_event_ids (no events have been condensed)- conversation_memory._ensure_initial_user_message(events, initial_user_action, set())- assert events == original_events---def test_ensure_initial_user_message_incorrect_at_index_1(- conversation_memory, initial_user_action-):- """Test inserting the correct initial user message when an incorrect message is at index 1."""- system_message = SystemMessageAction(content='System')- incorrect_second_message = MessageAction(content='Assistant')- incorrect_second_message._source = EventSource.AGENT- events = [system_message, incorrect_second_message]- # Pass empty set for forgotten_event_ids (no events have been condensed)- conversation_memory._ensure_initial_user_message(events, initial_user_action, set())- assert len(events) == 3- assert events[0] == system_message- assert events[1] == initial_user_action # Correct one inserted- assert events[2] == incorrect_second_message # Original second message shifted---def test_ensure_initial_user_message_correct_present_later(- conversation_memory, initial_user_action-):- """Test inserting the correct initial user message at index 1 even if it exists later."""- system_message = SystemMessageAction(content='System')- incorrect_second_message = MessageAction(content='Assistant')- incorrect_second_message._source = EventSource.AGENT- # Correct initial message is present, but later in the list- events = [system_message, incorrect_second_message]- conversation_memory._ensure_system_message(events)- # Pass empty set for forgotten_event_ids (no events have been condensed)- conversation_memory._ensure_initial_user_message(events, initial_user_action, set())- assert len(events) == 3 # Should still insert at index 1, not remove the later one- assert events[0] == system_message- assert events[1] == initial_user_action # Correct one inserted at index 1- assert events[2] == incorrect_second_message # Original second message shifted- # The duplicate initial_user_action originally at index 2 is now at index 3 (implicitly tested by length and content)---def test_ensure_initial_user_message_different_user_msg_at_index_1(- conversation_memory, initial_user_action-):- """Test inserting the correct initial user message when a *different* user message is at index 1."""- system_message = SystemMessageAction(content='System')- different_user_message = MessageAction(content='Different User Message')- different_user_message._source = EventSource.USER- events = [system_message, different_user_message]- # Pass empty set for forgotten_event_ids (no events have been condensed)- conversation_memory._ensure_initial_user_message(events, initial_user_action, set())- assert len(events) == 2- assert events[0] == system_message- assert events[1] == different_user_message # Original second message remains---def test_ensure_initial_user_message_different_user_msg_at_index_1_and_orphaned_obs(- conversation_memory, initial_user_action-):- """Test process_events when an incorrect user message is at index 1 AND- an orphaned observation (with tool_call_metadata but no matching action) exists.- Expect: System msg, CORRECT initial user msg, the incorrect user msg (shifted).- The orphaned observation should be filtered out.- """- system_message = SystemMessageAction(content='System')- different_user_message = MessageAction(content='Different User Message')- different_user_message._source = EventSource.USER-- # Create an orphaned observation (no matching action/tool call request will exist)- # Use a dictionary that mimics ModelResponse structure to satisfy Pydantic- mock_response = {- 'id': 'mock_response_id',- 'choices': [{'message': {'content': None, 'tool_calls': []}}],- 'created': 0,- 'model': '',- 'object': '',- 'usage': {'completion_tokens': 0, 'prompt_tokens': 0, 'total_tokens': 0},- }- orphaned_obs = CmdOutputObservation(- command='orphan_cmd',- content='Orphaned output',- command_id=99,- exit_code=0,- )- orphaned_obs.tool_call_metadata = ToolCallMetadata(- tool_call_id='orphan_call_id',- function_name='execute_bash',- model_response=mock_response,- total_calls_in_response=1,- )-- # Initial events list: system, wrong user message, orphaned observation- events = [system_message, different_user_message, orphaned_obs]-- # Call the main process_events method- messages = conversation_memory.process_events(- condensed_history=events,- initial_user_action=initial_user_action, # Provide the *correct* initial action- max_message_chars=None,- vision_is_active=False,- )-- # Assertions on the final messages list- assert len(messages) == 2- # 1. System message should be first- assert messages[0].role == 'system'- assert messages[0].content[0].text == 'System'-- # 2. The different user message should be left at index 1- assert messages[1].role == 'user'- assert messages[1].content[0].text == different_user_message.content-- # Implicitly assert that the orphaned_obs was filtered out by checking the length (2)---def test_process_events_with_cmd_output_observation(conversation_memory):- obs = CmdOutputObservation(- command='echo hello',- content='Command output',- metadata=CmdOutputMetadata(- exit_code=0,- prefix='[THIS IS PREFIX]',- suffix='[THIS IS SUFFIX]',- ),- )-- initial_user_message = MessageAction(content='Initial user message')- initial_user_message._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_message,- max_message_chars=None,- vision_is_active=False,- )-- assert len(messages) == 3 # System + initial user + result- result = messages[2] # The actual result is now at index 2- assert result.role == 'user'- assert len(result.content) == 1- assert isinstance(result.content[0], TextContent)- assert 'Observed result of command executed by user:' in result.content[0].text- assert '[Command finished with exit code 0]' in result.content[0].text- assert '[THIS IS PREFIX]' in result.content[0].text- assert '[THIS IS SUFFIX]' in result.content[0].text---def test_process_events_with_ipython_run_cell_observation(conversation_memory):- obs = IPythonRunCellObservation(- code='plt.plot()',- content='IPython output\n',- )-- initial_user_message = MessageAction(content='Initial user message')- initial_user_message._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_message,- max_message_chars=None,- vision_is_active=False,- )-- assert len(messages) == 3 # System + initial user + result- result = messages[2] # The actual result is now at index 2- assert result.role == 'user'- assert len(result.content) == 1- assert isinstance(result.content[0], TextContent)- assert 'IPython output' in result.content[0].text- assert (- ' already displayed to user'- in result.content[0].text- )- assert 'ABC123' not in result.content[0].text---def test_process_events_with_agent_delegate_observation(conversation_memory):- obs = AgentDelegateObservation(- content='Content', outputs={'content': 'Delegated agent output'}- )-- initial_user_message = MessageAction(content='Initial user message')- initial_user_message._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_message,- max_message_chars=None,- vision_is_active=False,- )-- assert len(messages) == 3 # System + initial user + result- result = messages[2] # The actual result is now at index 2- assert result.role == 'user'- assert len(result.content) == 1- assert isinstance(result.content[0], TextContent)- assert 'Delegated agent output' in result.content[0].text---def test_process_events_with_error_observation(conversation_memory):- obs = ErrorObservation('Error message')-- initial_user_message = MessageAction(content='Initial user message')- initial_user_message._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_message,- max_message_chars=None,- vision_is_active=False,- )-- assert len(messages) == 3 # System + initial user + result- result = messages[2] # The actual result is now at index 2- assert result.role == 'user'- assert len(result.content) == 1- assert isinstance(result.content[0], TextContent)- assert 'Error message' in result.content[0].text- assert 'Error occurred in processing last action' in result.content[0].text---def test_process_events_with_unknown_observation(conversation_memory):- # Create a mock that inherits from Event but not Action or Observation- obs = Mock(spec=Event)- initial_user_message = MessageAction(content='Initial user message')- initial_user_message._source = EventSource.USER-- with pytest.raises(ValueError, match='Unknown event type'):- conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_message,- max_message_chars=None,- vision_is_active=False,- )---def test_process_events_with_file_edit_observation(conversation_memory):- obs = FileEditObservation(- path='/test/file.txt',- prev_exist=True,- old_content='old content',- new_content='new content',- content='diff content',- impl_source=FileEditSource.LLM_BASED_EDIT,- )-- initial_user_message = MessageAction(content='Initial user message')- initial_user_message._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_message,- max_message_chars=None,- vision_is_active=False,- )-- assert len(messages) == 3 # System + initial user + result- result = messages[2] # The actual result is now at index 2- assert result.role == 'user'- assert len(result.content) == 1- assert isinstance(result.content[0], TextContent)- assert '[Existing file /test/file.txt is edited with' in result.content[0].text---def test_process_events_with_file_read_observation(conversation_memory):- obs = FileReadObservation(- path='/test/file.txt',- content='File content',- impl_source=FileReadSource.DEFAULT,- )-- initial_user_message = MessageAction(content='Initial user message')- initial_user_message._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_message,- max_message_chars=None,- vision_is_active=False,- )-- assert len(messages) == 3 # System + initial user + result- result = messages[2] # The actual result is now at index 2- assert result.role == 'user'- assert len(result.content) == 1- assert isinstance(result.content[0], TextContent)- assert result.content[0].text == '\n\nFile content'---def test_process_events_with_browser_output_observation(conversation_memory):- formatted_content = '[Current URL: http://example.com]\n\n============== BEGIN webpage content ==============\nPage loaded\n============== END webpage content =============='-- obs = BrowserOutputObservation(- url='http://example.com',- trigger_by_action='browse',- screenshot='',- content=formatted_content,- error=False,- )-- initial_user_message = MessageAction(content='Initial user message')- initial_user_message._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_message,- max_message_chars=None,- vision_is_active=False,- )-- assert len(messages) == 3 # System + initial user + result- result = messages[2] # The actual result is now at index 2- assert result.role == 'user'- assert len(result.content) == 1- assert isinstance(result.content[0], TextContent)- assert '[Current URL: http://example.com]' in result.content[0].text---def test_process_events_with_user_reject_observation(conversation_memory):- obs = UserRejectObservation('Action rejected')-- initial_user_message = MessageAction(content='Initial user message')- initial_user_message._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_message,- max_message_chars=None,- vision_is_active=False,- )-- assert len(messages) == 3 # System + initial user + result- result = messages[2] # The actual result is now at index 2- assert result.role == 'user'- assert len(result.content) == 1- assert isinstance(result.content[0], TextContent)- assert 'Action rejected' in result.content[0].text- assert '[Last action has been rejected by the user]' in result.content[0].text---def test_process_events_with_empty_environment_info(conversation_memory):- """Test that empty environment info observations return an empty list of messages without calling build_workspace_context."""- # Create a RecallObservation with empty info-- empty_obs = RecallObservation(- recall_type=RecallType.WORKSPACE_CONTEXT,- repo_name='',- repo_directory='',- repo_instructions='',- runtime_hosts={},- additional_agent_instructions='',- microagent_knowledge=[],- content='Retrieved environment info',- )-- initial_user_message = MessageAction(content='Initial user message')- initial_user_message._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[empty_obs],- initial_user_action=initial_user_message,- max_message_chars=None,- vision_is_active=False,- )-- # Should only contain system message and initial user message- assert len(messages) == 2-- # Verify that build_workspace_context was NOT called since all input values were empty- conversation_memory.prompt_manager.build_workspace_context.assert_not_called()---def test_process_events_with_function_calling_observation(conversation_memory):- mock_response = {- 'id': 'mock_id',- 'total_calls_in_response': 1,- 'choices': [{'message': {'content': 'Task completed'}}],- }- obs = CmdOutputObservation(- command='echo hello',- content='Command output',- command_id=1,- exit_code=0,- )- obs.tool_call_metadata = ToolCallMetadata(- tool_call_id='123',- function_name='execute_bash',- model_response=mock_response,- total_calls_in_response=1,- )- # Define initial user action- initial_user_action = MessageAction(content='Initial user message')- initial_user_action._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_action,- max_message_chars=None,- vision_is_active=False,- )-- # No direct message when using function calling- assert (- len(messages) == 2- ) # should be no messages except system message and initial user message---def test_process_events_with_message_action_with_image(conversation_memory):- action = MessageAction(- content='Message with image',- image_urls=['http://example.com/image.jpg'],- )- action._source = EventSource.AGENT-- # Define initial user action- initial_user_action = MessageAction(content='Initial user message')- initial_user_action._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[action],- initial_user_action=initial_user_action,- max_message_chars=None,- vision_is_active=True,- )-- assert len(messages) == 3- result = messages[2]- assert result.role == 'assistant'- assert len(result.content) == 2- assert isinstance(result.content[0], TextContent)- assert isinstance(result.content[1], ImageContent)- assert result.content[0].text == 'Message with image'- assert result.content[1].image_urls == ['http://example.com/image.jpg']---def test_process_events_with_user_cmd_action(conversation_memory):- action = CmdRunAction(command='ls -l')- action._source = EventSource.USER-- # Define initial user action- initial_user_action = MessageAction(content='Initial user message')- initial_user_action._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[action],- initial_user_action=initial_user_action,- max_message_chars=None,- vision_is_active=False,- )-- assert len(messages) == 3- result = messages[2]- assert result.role == 'user'- assert len(result.content) == 1- assert isinstance(result.content[0], TextContent)- assert 'User executed the command' in result.content[0].text- assert 'ls -l' in result.content[0].text---def test_process_events_with_agent_finish_action_with_tool_metadata(- conversation_memory,-):- mock_response = {- 'id': 'mock_id',- 'total_calls_in_response': 1,- 'choices': [{'message': {'content': 'Task completed'}}],- }-- action = AgentFinishAction(thought='Initial thought')- action._source = EventSource.AGENT- action.tool_call_metadata = ToolCallMetadata(- tool_call_id='123',- function_name='finish',- model_response=mock_response,- total_calls_in_response=1,- )-- # Define initial user action- initial_user_action = MessageAction(content='Initial user message')- initial_user_action._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[action],- initial_user_action=initial_user_action,- max_message_chars=None,- vision_is_active=False,- )-- assert len(messages) == 3- result = messages[2]- assert result.role == 'assistant'- assert len(result.content) == 1- assert isinstance(result.content[0], TextContent)- assert 'Initial thought\nTask completed' in result.content[0].text---def test_apply_prompt_caching(conversation_memory):- messages = [- Message(role='system', content=[TextContent(text='System message')]),- Message(role='user', content=[TextContent(text='User message')]),- Message(role='assistant', content=[TextContent(text='Assistant message')]),- Message(role='user', content=[TextContent(text='Another user message')]),- ]-- conversation_memory.apply_prompt_caching(messages)-- # System message is hard-coded to be cached always- assert messages[0].content[0].cache_prompt is True- assert messages[1].content[0].cache_prompt is False- assert messages[2].content[0].cache_prompt is False- # Only the last user message should have cache_prompt=True- assert messages[3].content[0].cache_prompt is True---def test_process_events_with_environment_microagent_observation(conversation_memory):- """Test processing a RecallObservation with ENVIRONMENT info type."""- obs = RecallObservation(- recall_type=RecallType.WORKSPACE_CONTEXT,- repo_name='test-repo',- repo_directory='/path/to/repo',- repo_instructions='# Test Repository\nThis is a test repository.',- runtime_hosts={'localhost': 8080},- content='Retrieved environment info',- )-- # Define initial user action- initial_user_action = MessageAction(content='Initial user message')- initial_user_action._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_action,- max_message_chars=None,- vision_is_active=False,- )-- assert len(messages) == 3- result = messages[2]- assert result.role == 'user'- assert len(result.content) == 1- assert isinstance(result.content[0], TextContent)- assert result.content[0].text == '\n\nFormatted repository and runtime info'-- # Verify the prompt_manager was called with the correct parameters- conversation_memory.prompt_manager.build_workspace_context.assert_called_once()- call_args = conversation_memory.prompt_manager.build_workspace_context.call_args[1]- assert isinstance(call_args['repository_info'], RepositoryInfo)- assert call_args['repository_info'].repo_name == 'test-repo'- assert call_args['repository_info'].repo_directory == '/path/to/repo'- assert isinstance(call_args['runtime_info'], RuntimeInfo)- assert call_args['runtime_info'].available_hosts == {'localhost': 8080}- assert (- call_args['repo_instructions']- == '# Test Repository\nThis is a test repository.'- )---def test_process_events_with_knowledge_microagent_microagent_observation(- conversation_memory,-):- """Test processing a RecallObservation with KNOWLEDGE type."""- microagent_knowledge = [- MicroagentKnowledge(- name='test_agent',- trigger='test',- content='This is test agent content',- ),- MicroagentKnowledge(- name='another_agent',- trigger='another',- content='This is another agent content',- ),- MicroagentKnowledge(- name='disabled_agent',- trigger='disabled',- content='This is disabled agent content',- ),- ]-- obs = RecallObservation(- recall_type=RecallType.KNOWLEDGE,- microagent_knowledge=microagent_knowledge,- content='Retrieved knowledge from microagents',- )-- # Define initial user action- initial_user_action = MessageAction(content='Initial user message')- initial_user_action._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_action,- max_message_chars=None,- vision_is_active=False,- )-- assert len(messages) == 3 # System + Initial User + Result- result = messages[2] # Result is now at index 2- assert result.role == 'user'- assert len(result.content) == 1- assert isinstance(result.content[0], TextContent)- # Verify that disabled_agent is filtered out and enabled agents are included- assert 'This is test agent content' in result.content[0].text- assert 'This is another agent content' in result.content[0].text- assert 'This is disabled agent content' not in result.content[0].text-- # Verify the prompt_manager was called with the correct parameters- conversation_memory.prompt_manager.build_microagent_info.assert_called_once()- call_args = conversation_memory.prompt_manager.build_microagent_info.call_args[1]-- # Check that disabled_agent was filtered out- triggered_agents = call_args['triggered_agents']- assert len(triggered_agents) == 2- agent_names = [agent.name for agent in triggered_agents]- assert 'test_agent' in agent_names- assert 'another_agent' in agent_names- assert 'disabled_agent' not in agent_names---def test_process_events_with_microagent_observation_extensions_disabled(- agent_config, conversation_memory-):- """Test processing a RecallObservation when prompt extensions are disabled."""- # Modify the agent config to disable prompt extensions- agent_config.enable_prompt_extensions = False-- obs = RecallObservation(- recall_type=RecallType.WORKSPACE_CONTEXT,- repo_name='test-repo',- repo_directory='/path/to/repo',- content='Retrieved environment info',- )-- # Define initial user action- initial_user_action = MessageAction(content='Initial user message')- initial_user_action._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_action,- max_message_chars=None,- vision_is_active=False,- )-- # When prompt extensions are disabled, the RecallObservation should be ignored- assert len(messages) == 2 # System + Initial User-- # Verify the prompt_manager was not called- conversation_memory.prompt_manager.build_workspace_context.assert_not_called()- conversation_memory.prompt_manager.build_microagent_info.assert_not_called()---def test_process_events_with_empty_microagent_knowledge(conversation_memory):- """Test processing a RecallObservation with empty microagent knowledge."""- obs = RecallObservation(- recall_type=RecallType.KNOWLEDGE,- microagent_knowledge=[],- content='Retrieved knowledge from microagents',- )-- # Define initial user action- initial_user_action = MessageAction(content='Initial user message')- initial_user_action._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_action,- max_message_chars=None,- vision_is_active=False,- )-- # The implementation returns an empty string and it doesn't creates a message- assert len(messages) == 2 # System + Initial User-- # When there are no triggered agents, build_microagent_info is not called- conversation_memory.prompt_manager.build_microagent_info.assert_not_called()---def test_conversation_memory_processes_microagent_observation(prompt_dir):- """Test that ConversationMemory processes RecallObservations correctly."""- # Create a microagent_info.j2 template file- template_path = os.path.join(prompt_dir, 'microagent_info.j2')- if not os.path.exists(template_path):- with open(template_path, 'w') as f:- f.write("""{% for agent_info in triggered_agents %}-<EXTRA_INFO>-The following information has been included based on a keyword match for "{{ agent_info.trigger_word }}".-It may or may not be relevant to the user's request.-- # Verify the template was correctly rendered-{{ agent_info.content }}-</EXTRA_INFO>-{% endfor %}-""")-- # Create a mock agent config- agent_config = MagicMock(spec=AgentConfig)- agent_config.enable_prompt_extensions = True- agent_config.disabled_microagents = []-- # Create a PromptManager- prompt_manager = PromptManager(prompt_dir=prompt_dir)-- # Initialize ConversationMemory- conversation_memory = ConversationMemory(- config=agent_config, prompt_manager=prompt_manager- )-- # Create a RecallObservation with microagent knowledge- microagent_observation = RecallObservation(- recall_type=RecallType.KNOWLEDGE,- microagent_knowledge=[- MicroagentKnowledge(- name='test_agent',- trigger='test_trigger',- content='This is triggered content for testing.',- )- ],- content='Retrieved knowledge from microagents',- )-- # Process the observation- messages = conversation_memory._process_observation(- obs=microagent_observation, tool_call_id_to_message={}, max_message_chars=None- )-- # Verify the message was created correctly- assert len(messages) == 1- message = messages[0]- assert message.role == 'user'- assert len(message.content) == 1- assert isinstance(message.content[0], TextContent)-- expected_text = """<EXTRA_INFO>-The following information has been included based on a keyword match for "test_trigger".-It may or may not be relevant to the user's request.--This is triggered content for testing.-</EXTRA_INFO>"""-- assert message.content[0].text.strip() == expected_text.strip()-- # Clean up- os.remove(os.path.join(prompt_dir, 'microagent_info.j2'))---def test_conversation_memory_processes_environment_microagent_observation(prompt_dir):- """Test that ConversationMemory processes environment info RecallObservations correctly."""- # Create an additional_info.j2 template file- template_path = os.path.join(prompt_dir, 'additional_info.j2')- if not os.path.exists(template_path):- with open(template_path, 'w') as f:- f.write("""-{% if repository_info %}-<REPOSITORY_INFO>-At the user's request, repository {{ repository_info.repo_name }} has been cloned to directory {{ repository_info.repo_directory }}.-</REPOSITORY_INFO>-{% endif %}--{% if repository_instructions %}-<REPOSITORY_INSTRUCTIONS>-{{ repository_instructions }}-</REPOSITORY_INSTRUCTIONS>-{% endif %}--{% if runtime_info and runtime_info.available_hosts %}-<RUNTIME_INFORMATION>-The user has access to the following hosts for accessing a web application,-each of which has a corresponding port:-{% for host, port in runtime_info.available_hosts.items() %}-* {{ host }} (port {{ port }})-{% endfor %}-</RUNTIME_INFORMATION>-{% endif %}-""")-- # Create a mock agent config- agent_config = MagicMock(spec=AgentConfig)- agent_config.enable_prompt_extensions = True-- # Create a PromptManager- prompt_manager = PromptManager(prompt_dir=prompt_dir)-- # Initialize ConversationMemory- conversation_memory = ConversationMemory(- config=agent_config, prompt_manager=prompt_manager- )-- # Create a RecallObservation with environment info- microagent_observation = RecallObservation(- recall_type=RecallType.WORKSPACE_CONTEXT,- repo_name='owner/repo',- repo_directory='/workspace/repo',- repo_instructions='This repository contains important code.',- runtime_hosts={'example.com': 8080},- content='Retrieved environment info',- )-- # Process the observation- messages = conversation_memory._process_observation(- obs=microagent_observation, tool_call_id_to_message={}, max_message_chars=None- )-- # Verify the message was created correctly- assert len(messages) == 1- message = messages[0]- assert message.role == 'user'- assert len(message.content) == 1- assert isinstance(message.content[0], TextContent)-- # Check that the message contains the repository info- assert '<REPOSITORY_INFO>' in message.content[0].text- assert 'owner/repo' in message.content[0].text- assert '/workspace/repo' in message.content[0].text-- # Check that the message contains the repository instructions- assert '<REPOSITORY_INSTRUCTIONS>' in message.content[0].text- assert 'This repository contains important code.' in message.content[0].text-- # Check that the message contains the runtime info- assert '<RUNTIME_INFORMATION>' in message.content[0].text- assert 'example.com (port 8080)' in message.content[0].text---def test_process_events_with_microagent_observation_deduplication(conversation_memory):- """Test that RecallObservations are properly deduplicated based on agent name.-- The deduplication logic should keep the FIRST occurrence of each microagent- and filter out later occurrences to avoid redundant information.- """- # Create a sequence of RecallObservations with overlapping agents- obs1 = RecallObservation(- recall_type=RecallType.KNOWLEDGE,- microagent_knowledge=[- MicroagentKnowledge(- name='python_agent',- trigger='python',- content='Python best practices v1',- ),- MicroagentKnowledge(- name='git_agent',- trigger='git',- content='Git best practices v1',- ),- MicroagentKnowledge(- name='image_agent',- trigger='image',- content='Image best practices v1',- ),- ],- content='First retrieval',- )-- obs2 = RecallObservation(- recall_type=RecallType.KNOWLEDGE,- microagent_knowledge=[- MicroagentKnowledge(- name='python_agent',- trigger='python',- content='Python best practices v2',- ),- ],- content='Second retrieval',- )-- obs3 = RecallObservation(- recall_type=RecallType.KNOWLEDGE,- microagent_knowledge=[- MicroagentKnowledge(- name='git_agent',- trigger='git',- content='Git best practices v3',- ),- ],- content='Third retrieval',- )-- # Define initial user action- initial_user_action = MessageAction(content='Initial user message')- initial_user_action._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs1, obs2, obs3],- initial_user_action=initial_user_action,- max_message_chars=None,- vision_is_active=False,- )-- # Verify that only the first occurrence of content for each agent is included- assert len(messages) == 3 # System + Initial User + Result- # Result is now at index 2- # First microagent should include all agents since they appear here first- assert 'Image best practices v1' in messages[2].content[0].text- assert 'Git best practices v1' in messages[2].content[0].text- assert 'Python best practices v1' in messages[2].content[0].text---def test_process_events_with_microagent_observation_deduplication_disabled_agents(- conversation_memory,-):- """Test that disabled agents are filtered out and deduplication keeps the first occurrence."""- # Create a sequence of RecallObservations with disabled agents- obs1 = RecallObservation(- recall_type=RecallType.KNOWLEDGE,- microagent_knowledge=[- MicroagentKnowledge(- name='disabled_agent',- trigger='disabled',- content='Disabled agent content',- ),- MicroagentKnowledge(- name='enabled_agent',- trigger='enabled',- content='Enabled agent content v1',- ),- ],- content='First retrieval',- )-- obs2 = RecallObservation(- recall_type=RecallType.KNOWLEDGE,- microagent_knowledge=[- MicroagentKnowledge(- name='enabled_agent',- trigger='enabled',- content='Enabled agent content v2',- ),- ],- content='Second retrieval',- )-- # Define initial user action- initial_user_action = MessageAction(content='Initial user message')- initial_user_action._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs1, obs2],- initial_user_action=initial_user_action,- max_message_chars=None,- vision_is_active=False,- )-- # Verify that disabled agents are filtered out and only the first occurrence of enabled agents is included- assert len(messages) == 3 # System + Initial User + Result- # Result is now at index 2- # First microagent should include enabled_agent but not disabled_agent- assert 'Disabled agent content' not in messages[2].content[0].text- assert 'Enabled agent content v1' in messages[2].content[0].text---def test_process_events_with_microagent_observation_deduplication_empty(- conversation_memory,-):- """Test that empty RecallObservations are handled correctly."""- obs = RecallObservation(- recall_type=RecallType.KNOWLEDGE,- microagent_knowledge=[],- content='Empty retrieval',- )-- # Define initial user action- initial_user_action = MessageAction(content='Initial user message')- initial_user_action._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[obs],- initial_user_action=initial_user_action,- max_message_chars=None,- vision_is_active=False,- )-- # Verify that empty RecallObservations are handled gracefully- assert (- len(messages) == 2 # System + Initial User- ) # an empty microagent is not added to Messages- assert messages[0].role == 'system'- assert messages[1].role == 'user' # Initial user message---def test_has_agent_in_earlier_events(conversation_memory):- """Test the _has_agent_in_earlier_events helper method."""- # Create test RecallObservations- obs1 = RecallObservation(- recall_type=RecallType.KNOWLEDGE,- microagent_knowledge=[- MicroagentKnowledge(- name='agent1',- trigger='trigger1',- content='Content 1',- ),- ],- content='First retrieval',- )-- obs2 = RecallObservation(- recall_type=RecallType.KNOWLEDGE,- microagent_knowledge=[- MicroagentKnowledge(- name='agent2',- trigger='trigger2',- content='Content 2',- ),- ],- content='Second retrieval',- )-- obs3 = RecallObservation(- recall_type=RecallType.WORKSPACE_CONTEXT,- content='Environment info',- )-- # Create a list with mixed event types- events = [obs1, MessageAction(content='User message'), obs2, obs3]-- # Test looking for existing agents- assert conversation_memory._has_agent_in_earlier_events('agent1', 2, events) is True- assert conversation_memory._has_agent_in_earlier_events('agent1', 3, events) is True- assert conversation_memory._has_agent_in_earlier_events('agent1', 4, events) is True-- # Test looking for an agent in a later position (should not find it)- assert (- conversation_memory._has_agent_in_earlier_events('agent2', 0, events) is False- )- assert (- conversation_memory._has_agent_in_earlier_events('agent2', 1, events) is False- )-- # Test looking for an agent in a different microagent type (should not find it)- assert (- conversation_memory._has_agent_in_earlier_events('non_existent', 3, events)- is False- )---class TestFilterUnmatchedToolCalls:- @pytest.fixture- def processor(self):- return ConversationMemory()-- def test_empty_is_unchanged(self):- assert list(ConversationMemory._filter_unmatched_tool_calls([])) == []-- def test_no_tool_calls_is_unchanged(self):- messages = [- Message(role='user', content=[TextContent(text='Hello')]),- Message(role='assistant', content=[TextContent(text='Hi there')]),- Message(role='user', content=[TextContent(text='How are you?')]),- ]- assert (- list(ConversationMemory._filter_unmatched_tool_calls(messages)) == messages- )-- def test_matched_tool_calls_are_unchanged(self):- messages = [- Message(role='user', content=[TextContent(text="What's the weather?")]),- Message(- role='assistant',- content=[],- tool_calls=[- ChatCompletionMessageToolCall(- id='call_1',- type='function',- function={'name': 'get_weather', 'arguments': ''},- )- ],- ),- Message(- role='tool',- tool_call_id='call_1',- content=[TextContent(text='Sunny, 75Β°F')],- ),- Message(role='assistant', content=[TextContent(text="It's sunny today.")]),- ]-- # All tool calls have matching responses, should remain unchanged- assert (- list(ConversationMemory._filter_unmatched_tool_calls(messages)) == messages- )-- def test_tool_call_without_response_is_removed(self):- messages = [- Message(role='user', content=[TextContent(text='Query')]),- Message(- role='tool',- tool_call_id='missing_call',- content=[TextContent(text='Response')],- ),- Message(role='assistant', content=[TextContent(text='Answer')]),- ]-- expected_after_filter = [- Message(role='user', content=[TextContent(text='Query')]),- Message(role='assistant', content=[TextContent(text='Answer')]),- ]-- result = list(ConversationMemory._filter_unmatched_tool_calls(messages))- assert result == expected_after_filter-- def test_tool_response_without_call_is_removed(self):- messages = [- Message(role='user', content=[TextContent(text='Query')]),- Message(- role='assistant',- content=[],- tool_calls=[- ChatCompletionMessageToolCall(- id='unmatched_call',- type='function',- function={'name': 'some_function', 'arguments': ''},- )- ],- ),- Message(role='assistant', content=[TextContent(text='Answer')]),- ]-- expected_after_filter = [- Message(role='user', content=[TextContent(text='Query')]),- Message(role='assistant', content=[TextContent(text='Answer')]),- ]-- result = list(ConversationMemory._filter_unmatched_tool_calls(messages))- assert result == expected_after_filter-- def test_partial_matched_tool_calls_retains_matched(self):- """When there are both matched and unmatched tools calls in a message, retain the message and only matched calls"""- messages = [- Message(role='user', content=[TextContent(text='Get data')]),- Message(- role='assistant',- content=[],- tool_calls=[- ChatCompletionMessageToolCall(- id='matched_call',- type='function',- function={'name': 'function1', 'arguments': ''},- ),- ChatCompletionMessageToolCall(- id='unmatched_call',- type='function',- function={'name': 'function2', 'arguments': ''},- ),- ],- ),- Message(- role='tool',- tool_call_id='matched_call',- content=[TextContent(text='Data')],- ),- Message(role='assistant', content=[TextContent(text='Result')]),- ]-- expected = [- Message(role='user', content=[TextContent(text='Get data')]),- # This message should be modified to only include the matched tool call- Message(- role='assistant',- content=[],- tool_calls=[- ChatCompletionMessageToolCall(- id='matched_call',- type='function',- function={'name': 'function1', 'arguments': ''},- )- ],- ),- Message(- role='tool',- tool_call_id='matched_call',- content=[TextContent(text='Data')],- ),- Message(role='assistant', content=[TextContent(text='Result')]),- ]-- result = list(ConversationMemory._filter_unmatched_tool_calls(messages))-- # Verify result structure- assert len(result) == len(expected)- for i, msg in enumerate(result):- assert msg == expected[i]---def test_system_message_in_events(conversation_memory):- """Test that SystemMessageAction in condensed_history is processed correctly."""- # Create a system message action- system_message = SystemMessageAction(content='System message', tools=['test_tool'])- system_message._source = EventSource.AGENT-- # Process events with the system message in condensed_history- # Define initial user action- initial_user_action = MessageAction(content='Initial user message')- initial_user_action._source = EventSource.USER- messages = conversation_memory.process_events(- condensed_history=[system_message],- initial_user_action=initial_user_action,- max_message_chars=None,- vision_is_active=False,- )-- # Check that the system message was processed correctly- assert len(messages) == 2 # System + Initial User- assert messages[0].role == 'system'- assert messages[0].content[0].text == 'System message'- assert messages[1].role == 'user' # Initial user message---# Helper function to create mock tool call metadata-def _create_mock_tool_call_metadata(- tool_call_id: str, function_name: str, response_id: str = 'mock_response_id'-) -> ToolCallMetadata:- # Use a dictionary that mimics ModelResponse structure to satisfy Pydantic- mock_response = {- 'id': response_id,- 'choices': [- {- 'message': {- 'role': 'assistant',- 'content': None, # Content is None for tool calls- 'tool_calls': [- {- 'id': tool_call_id,- 'type': 'function',- 'function': {- 'name': function_name,- 'arguments': '{}',- }, # Args don't matter for this test- }- ],- }- }- ],- 'created': 0,- 'model': 'mock_model',- 'object': 'chat.completion',- 'usage': {'completion_tokens': 0, 'prompt_tokens': 0, 'total_tokens': 0},- }- return ToolCallMetadata(- tool_call_id=tool_call_id,- function_name=function_name,- model_response=mock_response,- total_calls_in_response=1,- )---def test_process_events_partial_history(conversation_memory):- """Tests process_events with full and partial histories to verify- _ensure_system_message, _ensure_initial_user_message, and tool call matching logic.- """- # --- Define Common Events ---- system_message = SystemMessageAction(content='System message')- system_message._source = EventSource.AGENT-- user_message = MessageAction(- content='Initial user query'- ) # This is the crucial initial_user_action- user_message._source = EventSource.USER-- recall_obs = RecallObservation(- recall_type=RecallType.WORKSPACE_CONTEXT,- repo_name='test-repo',- repo_directory='/path/to/repo',- content='Retrieved environment info',- )- recall_obs._source = EventSource.AGENT-- cmd_action = CmdRunAction(command='ls', thought='Running ls')- cmd_action._source = EventSource.AGENT- cmd_action.tool_call_metadata = _create_mock_tool_call_metadata(- tool_call_id='call_ls_1', function_name='execute_bash', response_id='resp_ls_1'- )-- cmd_obs = CmdOutputObservation(- command_id=1, command='ls', content='file1.txt\nfile2.py', exit_code=0- )- cmd_obs._source = EventSource.AGENT- cmd_obs.tool_call_metadata = _create_mock_tool_call_metadata(- tool_call_id='call_ls_1', function_name='execute_bash', response_id='resp_ls_1'- )-- # --- Scenario 1: Full History ---- full_history: list[Event] = [- system_message,- user_message, # Correct initial user message at index 1- recall_obs,- cmd_action,- cmd_obs,- ]- messages_full = conversation_memory.process_events(- condensed_history=list(full_history), # Pass a copy- initial_user_action=user_message, # Provide the initial action- max_message_chars=None,- vision_is_active=False,- )-- # Expected: System, User, Recall (formatted), Assistant (tool call), Tool Response- assert len(messages_full) == 5- assert messages_full[0].role == 'system'- assert messages_full[0].content[0].text == 'System message'- assert messages_full[1].role == 'user'- assert messages_full[1].content[0].text == 'Initial user query'- assert messages_full[2].role == 'user' # Recall obs becomes user message- assert (- 'Formatted repository and runtime info' in messages_full[2].content[0].text- ) # From fixture mock- assert messages_full[3].role == 'assistant'- assert messages_full[3].tool_calls is not None- assert len(messages_full[3].tool_calls) == 1- assert messages_full[3].tool_calls[0].id == 'call_ls_1'- assert messages_full[4].role == 'tool'- assert messages_full[4].tool_call_id == 'call_ls_1'- assert 'file1.txt' in messages_full[4].content[0].text-- # --- Scenario 2: Partial History (Action + Observation) ---- # Simulates processing only the last action/observation pair- partial_history_action_obs: list[Event] = [- cmd_action,- cmd_obs,- ]- messages_partial_action_obs = conversation_memory.process_events(- condensed_history=list(partial_history_action_obs), # Pass a copy- initial_user_action=user_message, # Provide the initial action- max_message_chars=None,- vision_is_active=False,- )-- # Expected: System (added), Initial User (added), Assistant (tool call), Tool Response- assert len(messages_partial_action_obs) == 4- assert (- messages_partial_action_obs[0].role == 'system'- ) # Added by _ensure_system_message- assert messages_partial_action_obs[0].content[0].text == 'System message'- assert (- messages_partial_action_obs[1].role == 'user'- ) # Added by _ensure_initial_user_message- assert messages_partial_action_obs[1].content[0].text == 'Initial user query'- assert messages_partial_action_obs[2].role == 'assistant'- assert messages_partial_action_obs[2].tool_calls is not None- assert len(messages_partial_action_obs[2].tool_calls) == 1- assert messages_partial_action_obs[2].tool_calls[0].id == 'call_ls_1'- assert messages_partial_action_obs[3].role == 'tool'- assert messages_partial_action_obs[3].tool_call_id == 'call_ls_1'- assert 'file1.txt' in messages_partial_action_obs[3].content[0].text-- # --- Scenario 3: Partial History (Observation Only) ---- # Simulates processing only the last observation- partial_history_obs_only: list[Event] = [- cmd_obs,- ]- messages_partial_obs_only = conversation_memory.process_events(- condensed_history=list(partial_history_obs_only), # Pass a copy- initial_user_action=user_message, # Provide the initial action- max_message_chars=None,- vision_is_active=False,- )-- # Expected: System (added), Initial User (added).- # The CmdOutputObservation has tool_call_metadata, but there's no corresponding- # assistant message (from CmdRunAction) with the matching tool_call.id in the input history.- # Therefore, _filter_unmatched_tool_calls should remove the tool response message.- assert len(messages_partial_obs_only) == 2- assert (- messages_partial_obs_only[0].role == 'system'- ) # Added by _ensure_system_message- assert messages_partial_obs_only[0].content[0].text == 'System message'- assert (- messages_partial_obs_only[1].role == 'user'- ) # Added by _ensure_initial_user_message- assert messages_partial_obs_only[1].content[0].text == 'Initial user query'---def test_process_ipython_observation_with_vision_enabled(- agent_config, mock_prompt_manager-):- """Test that _process_observation correctly handles IPythonRunCellObservation with image_urls when vision is enabled."""- # Create a ConversationMemory instance- memory = ConversationMemory(agent_config, mock_prompt_manager)-- # Create an observation with image URLs- obs = IPythonRunCellObservation(- content='Test output',- code="print('test')",- image_urls=['data:image/png;base64,abc123'],- )-- # Process the observation with vision enabled- messages = memory._process_observation(- obs=obs,- tool_call_id_to_message={},- max_message_chars=None,- vision_is_active=True,- )-- # Check that the message contains both text and image content- assert len(messages) == 1- message = messages[0]- assert len(message.content) == 2- assert isinstance(message.content[0], TextContent)- assert isinstance(message.content[1], ImageContent)- assert message.content[1].image_urls == ['data:image/png;base64,abc123']---def test_process_ipython_observation_with_vision_disabled(- agent_config, mock_prompt_manager-):- """Test that _process_observation correctly handles IPythonRunCellObservation with image_urls when vision is disabled."""- # Create a ConversationMemory instance- memory = ConversationMemory(agent_config, mock_prompt_manager)-- # Create an observation with image URLs- obs = IPythonRunCellObservation(- content='Test output',- code="print('test')",- image_urls=['data:image/png;base64,abc123'],- )-- # Process the observation with vision disabled- messages = memory._process_observation(- obs=obs,- tool_call_id_to_message={},- max_message_chars=None,- vision_is_active=False,- )-- # Check that the message contains both text and image content- # (ImageContent is always included, filtering happens at Message serialization level)- assert len(messages) == 1- message = messages[0]- assert len(message.content) == 2- assert isinstance(message.content[0], TextContent)- assert isinstance(message.content[1], ImageContent)- # Check that NO explanatory text about filtered images was added when vision is disabled- assert 'invalid or empty image(s) were filtered' not in message.content[0].text---def test_ensure_initial_user_message_not_reinserted_when_condensed(- conversation_memory, initial_user_action-):- """Test that initial user message is NOT re-inserted when it has been condensed.-- This is a critical test for bug #11910: Old instructions should not be re-executed- after conversation condensation. If the initial user message has been condensed- (its ID is in the forgotten_event_ids set), we should NOT re-insert it to prevent- the LLM from seeing old instructions as fresh commands.- """- system_message = SystemMessageAction(content='System')- system_message._source = EventSource.AGENT-- # Simulate that the initial_user_action has been condensed by adding its ID- # to the forgotten_event_ids set- initial_user_action._id = 1 # Assign an ID to the initial user action- forgotten_event_ids = {1} # The initial user action's ID is in the forgotten set-- events = [system_message] # Only system message, no user message-- # Call _ensure_initial_user_message with the condensed event ID- conversation_memory._ensure_initial_user_message(- events, initial_user_action, forgotten_event_ids- )-- # The initial user action should NOT be inserted because it was condensed- assert len(events) == 1- assert events[0] == system_message- # Verify the initial user action was NOT added- assert initial_user_action not in events---def test_ensure_initial_user_message_reinserted_when_not_condensed(- conversation_memory, initial_user_action-):- """Test that initial user message IS re-inserted when it has NOT been condensed.-- This ensures backward compatibility: when no condensation has happened,- the initial user message should still be inserted as before.- """- system_message = SystemMessageAction(content='System')- system_message._source = EventSource.AGENT-- # The initial user action has NOT been condensed- initial_user_action._id = 1- forgotten_event_ids = {5, 10, 15} # Different IDs, not including the initial action-- events = [system_message]-- # Call _ensure_initial_user_message with non-matching forgotten IDs- conversation_memory._ensure_initial_user_message(- events, initial_user_action, forgotten_event_ids- )-- # The initial user action SHOULD be inserted because it was NOT condensed- assert len(events) == 2- assert events[0] == system_message- assert events[1] == initial_user_action---def test_process_events_does_not_reinsert_condensed_initial_message(- conversation_memory,-):- """Test that process_events does not re-insert initial user message when condensed.-- This is an integration test for the full process_events flow, verifying that- when the initial user message has been condensed, it is not re-inserted into- the conversation sent to the LLM.- """- # Create a system message- system_message = SystemMessageAction(content='System message')- system_message._source = EventSource.AGENT- system_message._id = 0-- # Create the initial user message (will be marked as condensed)- initial_user_message = MessageAction(content='Do task A, B, and C')- initial_user_message._source = EventSource.USER- initial_user_message._id = 1-- # Create a condensation summary observation- from openhands.events.observation.agent import AgentCondensationObservation-- condensation_summary = AgentCondensationObservation(- content='Summary: User requested tasks A, B, C. Task A was completed successfully.'- )- condensation_summary._id = 2-- # Create a recent user message (not condensed)- recent_user_message = MessageAction(content='Now continue with task D')- recent_user_message._source = EventSource.USER- recent_user_message._id = 3-- # Simulate condensed history: system + summary + recent message- # The initial user message (id=1) has been condensed/forgotten- condensed_history = [system_message, condensation_summary, recent_user_message]-- # The initial user message's ID is in the forgotten set- forgotten_event_ids = {1}-- messages = conversation_memory.process_events(- condensed_history=condensed_history,- initial_user_action=initial_user_message,- forgotten_event_ids=forgotten_event_ids,- max_message_chars=None,- vision_is_active=False,- )-- # Verify the structure of messages- # Should have: system, condensation summary, recent user message- # Should NOT have the initial user message "Do task A, B, and C"- assert len(messages) == 3- assert messages[0].role == 'system'- assert messages[0].content[0].text == 'System message'-- # The second message should be the condensation summary, NOT the initial user message- assert messages[1].role == 'user'- assert 'Summary: User requested tasks A, B, C' in messages[1].content[0].text-- # The third message should be the recent user message- assert messages[2].role == 'user'- assert 'Now continue with task D' in messages[2].content[0].text-- # Critically, the old instruction should NOT appear- for msg in messages:- for content in msg.content:- if hasattr(content, 'text'):- assert 'Do task A, B, and C' not in content.textdiff --git a/tests/unit/memory/test_empty_image_url_fix_v2.py b/tests/unit/memory/test_empty_image_url_fix_v2.pydeleted file mode 100644index 07a90c122f..0000000000--- a/tests/unit/memory/test_empty_image_url_fix_v2.py+++ /dev/null@@ -1,264 +0,0 @@-"""Test for fixing empty image URL issue in multimodal browsing."""--from openhands.core.config.agent_config import AgentConfig-from openhands.core.message import ImageContent-from openhands.events.observation.browse import BrowserOutputObservation-from openhands.memory.conversation_memory import ConversationMemory-from openhands.utils.prompt import PromptManager---def test_empty_image_url_handling():- """Test that empty image URLs are properly filtered out and notification text is added."""- # Create a browser observation with empty screenshot and set_of_marks- browser_obs = BrowserOutputObservation(- url='https://example.com',- trigger_by_action='browse_interactive',- screenshot='', # Empty screenshot- set_of_marks='', # Empty set_of_marks- content='Some webpage content',- )-- # Create conversation memory with vision enabled- agent_config = AgentConfig(enable_som_visual_browsing=True)- prompt_manager = PromptManager(- prompt_dir='openhands/agenthub/codeact_agent/prompts'- )- conv_memory = ConversationMemory(agent_config, prompt_manager)-- # Process the observation with vision enabled- messages = conv_memory._process_observation(- obs=browser_obs,- tool_call_id_to_message={},- max_message_chars=None,- vision_is_active=True,- enable_som_visual_browsing=True,- current_index=0,- events=[],- )-- # Check that no empty image URLs are included- has_image_content = False- has_notification_text = False- for message in messages:- for content in message.content:- if isinstance(content, ImageContent):- has_image_content = True- # All image URLs should be non-empty and valid- for url in content.image_urls:- assert url != '', 'Empty image URL should be filtered out'- assert url is not None, 'None image URL should be filtered out'- # Should start with data: prefix for base64 images- if url: # Only check if URL is not empty- assert url.startswith('data:'), (- f'Invalid image URL format: {url}'- )- elif hasattr(content, 'text'):- # Check for notification text about missing visual information- if (- 'No visual information' in content.text- or 'has been filtered' in content.text- ):- has_notification_text = True-- # Should not have image content but should have notification text- assert not has_image_content, 'Should not have ImageContent for empty images'- assert has_notification_text, (- 'Should have notification text about missing visual information'- )---def test_valid_image_url_handling():- """Test that valid image URLs are properly handled."""- # Create a browser observation with valid base64 image data- valid_base64_image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='-- browser_obs = BrowserOutputObservation(- url='https://example.com',- trigger_by_action='browse_interactive',- screenshot=valid_base64_image,- set_of_marks=valid_base64_image,- content='Some webpage content',- )-- # Create conversation memory with vision enabled- agent_config = AgentConfig(enable_som_visual_browsing=True)- prompt_manager = PromptManager(- prompt_dir='openhands/agenthub/codeact_agent/prompts'- )- conv_memory = ConversationMemory(agent_config, prompt_manager)-- # Process the observation with vision enabled- messages = conv_memory._process_observation(- obs=browser_obs,- tool_call_id_to_message={},- max_message_chars=None,- vision_is_active=True,- enable_som_visual_browsing=True,- current_index=0,- events=[],- )-- # Check that valid image URLs are included- found_image_content = False- for message in messages:- for content in message.content:- if isinstance(content, ImageContent):- found_image_content = True- # Should have at least one valid image URL- assert len(content.image_urls) > 0, 'Should have at least one image URL'- for url in content.image_urls:- assert url != '', 'Image URL should not be empty'- assert url.startswith('data:image/'), (- f'Invalid image URL format: {url}'- )-- assert found_image_content, 'Should have found ImageContent with valid URLs'---def test_mixed_image_url_handling():- """Test handling of mixed valid and invalid image URLs."""- # Create a browser observation with one empty and one valid image- valid_base64_image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='-- browser_obs = BrowserOutputObservation(- url='https://example.com',- trigger_by_action='browse_interactive',- screenshot='', # Empty screenshot- set_of_marks=valid_base64_image, # Valid set_of_marks- content='Some webpage content',- )-- # Create conversation memory with vision enabled- agent_config = AgentConfig(enable_som_visual_browsing=True)- prompt_manager = PromptManager(- prompt_dir='openhands/agenthub/codeact_agent/prompts'- )- conv_memory = ConversationMemory(agent_config, prompt_manager)-- # Process the observation with vision enabled- messages = conv_memory._process_observation(- obs=browser_obs,- tool_call_id_to_message={},- max_message_chars=None,- vision_is_active=True,- enable_som_visual_browsing=True,- current_index=0,- events=[],- )-- # Check that only valid image URLs are included- found_image_content = False- for message in messages:- for content in message.content:- if isinstance(content, ImageContent):- found_image_content = True- # Should have exactly one valid image URL (set_of_marks)- assert len(content.image_urls) == 1, (- f'Should have exactly one image URL, got {len(content.image_urls)}'- )- url = content.image_urls[0]- assert url == valid_base64_image, (- f'Should use the valid image URL: {url}'- )-- assert found_image_content, 'Should have found ImageContent with valid URL'---def test_ipython_empty_image_url_handling():- """Test that empty image URLs in IPython observations are properly filtered with notification text."""- from openhands.events.observation.commands import IPythonRunCellObservation-- # Create an IPython observation with empty image URLs- ipython_obs = IPythonRunCellObservation(- content='Some output',- code='print("hello")',- image_urls=['', None, ''], # Empty and None image URLs- )-- # Create conversation memory with vision enabled- agent_config = AgentConfig(enable_som_visual_browsing=True)- prompt_manager = PromptManager(- prompt_dir='openhands/agenthub/codeact_agent/prompts'- )- conv_memory = ConversationMemory(agent_config, prompt_manager)-- # Process the observation with vision enabled- messages = conv_memory._process_observation(- obs=ipython_obs,- tool_call_id_to_message={},- max_message_chars=None,- vision_is_active=True,- enable_som_visual_browsing=True,- current_index=0,- events=[],- )-- # Check that no empty image URLs are included and notification text is added- has_image_content = False- has_notification_text = False- for message in messages:- for content in message.content:- if isinstance(content, ImageContent):- has_image_content = True- elif hasattr(content, 'text'):- # Check for notification text about filtered images- if 'invalid or empty and have been filtered' in content.text:- has_notification_text = True-- # Should not have image content but should have notification text- assert not has_image_content, 'Should not have ImageContent for empty images'- assert has_notification_text, 'Should have notification text about filtered images'---def test_ipython_mixed_image_url_handling():- """Test handling of mixed valid and invalid image URLs in IPython observations."""- from openhands.events.observation.commands import IPythonRunCellObservation-- # Create an IPython observation with mixed image URLs- valid_base64_image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='- ipython_obs = IPythonRunCellObservation(- content='Some output',- code='print("hello")',- image_urls=['', valid_base64_image, None], # Mix of empty, valid, and None- )-- # Create conversation memory with vision enabled- agent_config = AgentConfig(enable_som_visual_browsing=True)- prompt_manager = PromptManager(- prompt_dir='openhands/agenthub/codeact_agent/prompts'- )- conv_memory = ConversationMemory(agent_config, prompt_manager)-- # Process the observation with vision enabled- messages = conv_memory._process_observation(- obs=ipython_obs,- tool_call_id_to_message={},- max_message_chars=None,- vision_is_active=True,- enable_som_visual_browsing=True,- current_index=0,- events=[],- )-- # Check that only valid image URLs are included and notification text is added- found_image_content = False- has_notification_text = False- for message in messages:- for content in message.content:- if isinstance(content, ImageContent):- found_image_content = True- # Should have exactly one valid image URL- assert len(content.image_urls) == 1, (- f'Should have exactly one image URL, got {len(content.image_urls)}'- )- url = content.image_urls[0]- assert url == valid_base64_image, (- f'Should use the valid image URL: {url}'- )- elif hasattr(content, 'text'):- # Check for notification text about filtered images- if 'invalid or empty image(s) were filtered' in content.text:- has_notification_text = True-- assert found_image_content, 'Should have found ImageContent with valid URL'- assert has_notification_text, 'Should have notification text about filtered images'diff --git a/tests/unit/memory/test_memory.py b/tests/unit/memory/test_memory.pydeleted file mode 100644index 5d0f7fcc28..0000000000--- a/tests/unit/memory/test_memory.py+++ /dev/null@@ -1,656 +0,0 @@-import asyncio-import os-import shutil-import time-from unittest.mock import AsyncMock, MagicMock, patch--import pytest--from openhands.controller.agent import Agent-from openhands.controller.agent_controller import AgentController-from openhands.core.config import OpenHandsConfig-from openhands.core.main import run_controller-from openhands.core.schema.agent import AgentState-from openhands.events.action.agent import RecallAction-from openhands.events.action.message import MessageAction, SystemMessageAction-from openhands.events.event import EventSource-from openhands.events.observation.agent import (- RecallObservation,- RecallType,-)-from openhands.events.serialization.observation import observation_from_dict-from openhands.events.stream import EventStream-from openhands.llm import LLM-from openhands.llm.llm_registry import LLMRegistry-from openhands.llm.metrics import Metrics-from openhands.memory.memory import Memory-from openhands.runtime.impl.action_execution.action_execution_client import (- ActionExecutionClient,-)-from openhands.server.services.conversation_stats import ConversationStats-from openhands.server.session.agent_session import AgentSession-from openhands.storage.memory import InMemoryFileStore-from openhands.utils.prompt import (- ConversationInstructions,- PromptManager,- RepositoryInfo,- RuntimeInfo,-)---def file_store():- """Create a temporary file store for testing."""- return InMemoryFileStore({})---def mock_llm_registry(file_store):- """Create a mock LLMRegistry for testing."""- return MagicMock(spec=LLMRegistry)---def event_stream(file_store):- """Create a test event stream."""- return EventStream(sid='test_sid', file_store=file_store)---def memory(event_stream):- """Create a test memory instance."""- loop = asyncio.new_event_loop()- asyncio.set_event_loop(loop)- memory = Memory(event_stream, 'test_sid')- yield memory- loop.close()---def prompt_dir(tmp_path):- # Copy contents from "openhands/agenthub/codeact_agent" to the temp directory- shutil.copytree(- 'openhands/agenthub/codeact_agent/prompts', tmp_path, dirs_exist_ok=True- )-- # Return the temporary directory path- return tmp_path---def mock_agent():- # Create a dummy agent for the controller- agent = MagicMock(spec=Agent)- agent.llm = MagicMock(spec=LLM)- agent.llm.metrics = Metrics()- agent.llm.config = OpenHandsConfig().get_llm_config()-- # Add a proper system message mock- system_message = SystemMessageAction(content='Test system message')- system_message._source = EventSource.AGENT- system_message._id = -1 # Set invalid ID to avoid the ID check- agent.get_system_message.return_value = system_message-- agent.config = MagicMock()- agent.config.enable_mcp = False-- return agent---async def test_memory_on_event_exception_handling(memory, event_stream, mock_agent):- """Test that exceptions in Memory.on_event are properly handled via status callback."""- # Create a mock runtime- runtime = MagicMock(spec=ActionExecutionClient)- runtime.event_stream = event_stream-- # Mock Memory method to raise an exception- with (- patch.object(- memory, '_on_workspace_context_recall', side_effect=Exception('Test error')- ),- patch('openhands.core.main.create_agent', return_value=mock_agent),- ):- state = await run_controller(- config=OpenHandsConfig(),- initial_user_action=MessageAction(content='Test message'),- runtime=runtime,- sid='test',- fake_user_response_fn=lambda _: 'repeat',- memory=memory,- )-- # Verify that the controller's last error was set- assert state.iteration_flag.current_value == 0- assert state.agent_state == AgentState.ERROR- assert state.last_error == 'Error: Exception'---async def test_memory_on_workspace_context_recall_exception_handling(- memory, event_stream, mock_agent-):- """Test that exceptions in Memory._on_workspace_context_recall are properly handled via status callback."""- # Create a mock runtime- runtime = MagicMock(spec=ActionExecutionClient)- runtime.event_stream = event_stream-- # Mock Memory._on_workspace_context_recall to raise an exception- with (- patch.object(- memory,- '_find_microagent_knowledge',- side_effect=Exception('Test error from _find_microagent_knowledge'),- ),- patch('openhands.core.main.create_agent', return_value=mock_agent),- ):- state = await run_controller(- config=OpenHandsConfig(),- initial_user_action=MessageAction(content='Test message'),- runtime=runtime,- sid='test',- fake_user_response_fn=lambda _: 'repeat',- memory=memory,- )-- # Verify that the controller's last error was set- assert state.iteration_flag.current_value == 0- assert state.agent_state == AgentState.ERROR- assert state.last_error == 'Error: Exception'---async def test_memory_with_microagents():- """Test that Memory loads microagents from the global directory and processes microagent actions.-- This test verifies that:- 1. Memory loads microagents from the global GLOBAL_MICROAGENTS_DIR- 2. When a microagent action with a trigger word is processed, a RecallObservation is created- """- # Create a mock event stream- event_stream = MagicMock(spec=EventStream)-- # Initialize Memory to use the global microagents dir- memory = Memory(- event_stream=event_stream,- sid='test-session',- )-- # Verify microagents were loaded - at least one microagent should be loaded- # from the global directory that's in the repo- assert len(memory.knowledge_microagents) > 0-- # Check for the derived name 'flarglebargle'- derived_name = 'flarglebargle'- assert derived_name in memory.knowledge_microagents-- # Create a microagent action with the trigger word- microagent_action = RecallAction(- query='Hello, flarglebargle!', recall_type=RecallType.KNOWLEDGE- )-- # Set the source to USER- microagent_action._source = EventSource.USER # type: ignore[attr-defined]-- # Mock the event_stream.add_event method- added_events = []-- def original_add_event(event, source):- added_events.append((event, source))-- event_stream.add_event = original_add_event-- # Add the microagent action to the event stream- event_stream.add_event(microagent_action, EventSource.USER)-- # Clear the events list to only capture new events- added_events.clear()-- # Process the microagent action- await memory._on_event(microagent_action)-- # Verify a RecallObservation was added to the event stream- assert len(added_events) == 1- observation, source = added_events[0]- assert isinstance(observation, RecallObservation)- assert source == EventSource.ENVIRONMENT- assert observation.recall_type == RecallType.KNOWLEDGE-- # We should have at least one microagent: flarglebargle (triggered by keyword)- # Note: The default-tools microagent might not be loaded in tests- assert len(observation.microagent_knowledge) == 1-- # Find the flarglebargle microagent in the list- flarglebargle_knowledge = None- for knowledge in observation.microagent_knowledge:- if knowledge.name == derived_name:- flarglebargle_knowledge = knowledge- break-- # Check against the derived name- assert flarglebargle_knowledge is not None- assert flarglebargle_knowledge.name == derived_name- assert flarglebargle_knowledge.trigger == 'flarglebargle'- assert 'magic word' in flarglebargle_knowledge.content---def test_memory_repository_info(prompt_dir, file_store):- """Test that Memory adds repository info to RecallObservations."""- # real event stream- event_stream = EventStream(sid='test-session', file_store=file_store)-- # Create a test repo microagent first- repo_microagent_name = 'test_repo_microagent'- repo_microagent_content = """----name: test_repo-type: repo-agent: CodeActAgent------REPOSITORY INSTRUCTIONS: This is a test repository.-"""-- # Create a temporary repo microagent file- os.makedirs(os.path.join(prompt_dir, 'micro'), exist_ok=True)- with open(- os.path.join(prompt_dir, 'micro', f'{repo_microagent_name}.md'), 'w'- ) as f:- f.write(repo_microagent_content)-- # Patch the global microagents directory to use our test directory- test_microagents_dir = os.path.join(prompt_dir, 'micro')- with patch('openhands.memory.memory.GLOBAL_MICROAGENTS_DIR', test_microagents_dir):- # Initialize Memory- memory = Memory(- event_stream=event_stream,- sid='test-session',- )-- # Set repository info- memory.set_repository_info('owner/repo', '/workspace/repo')-- # Create and add the first user message- user_message = MessageAction(content='First user message')- user_message._source = EventSource.USER # type: ignore[attr-defined]- event_stream.add_event(user_message, EventSource.USER)-- # Create and add the microagent action- microagent_action = RecallAction(- query='First user message', recall_type=RecallType.WORKSPACE_CONTEXT- )- microagent_action._source = EventSource.USER # type: ignore[attr-defined]- event_stream.add_event(microagent_action, EventSource.USER)-- # Give it a little time to process- time.sleep(0.3)-- # Get all events from the stream- events = list(event_stream.get_events())-- # Find the RecallObservation event- microagent_obs_events = [- event for event in events if isinstance(event, RecallObservation)- ]-- # We should have at least one RecallObservation- assert len(microagent_obs_events) > 0-- # Get the first RecallObservation- observation = microagent_obs_events[0]- assert observation.recall_type == RecallType.WORKSPACE_CONTEXT- assert observation.repo_name == 'owner/repo'- assert observation.repo_directory == '/workspace/repo'- assert 'This is a test repository' in observation.repo_instructions-- # Clean up- os.remove(os.path.join(prompt_dir, 'micro', f'{repo_microagent_name}.md'))---async def test_memory_with_agent_microagents():- """Test that Memory processes microagent based on trigger words from agent messages."""- # Create a mock event stream- event_stream = MagicMock(spec=EventStream)-- # Initialize Memory to use the global microagents dir- memory = Memory(- event_stream=event_stream,- sid='test-session',- )-- # Verify microagents were loaded - at least one microagent should be loaded- # from the global directory that's in the repo- assert len(memory.knowledge_microagents) > 0-- # Check for the derived name 'flarglebargle'- derived_name = 'flarglebargle'- assert derived_name in memory.knowledge_microagents-- # Create a microagent action with the trigger word- microagent_action = RecallAction(- query='Hello, flarglebargle!', recall_type=RecallType.KNOWLEDGE- )-- # Set the source to AGENT- microagent_action._source = EventSource.AGENT # type: ignore[attr-defined]-- # Mock the event_stream.add_event method- added_events = []-- def original_add_event(event, source):- added_events.append((event, source))-- event_stream.add_event = original_add_event-- # Add the microagent action to the event stream- event_stream.add_event(microagent_action, EventSource.AGENT)-- # Clear the events list to only capture new events- added_events.clear()-- # Process the microagent action- await memory._on_event(microagent_action)-- # Verify a RecallObservation was added to the event stream- assert len(added_events) == 1- observation, source = added_events[0]- assert isinstance(observation, RecallObservation)- assert source == EventSource.ENVIRONMENT- assert observation.recall_type == RecallType.KNOWLEDGE-- # We should have at least one microagent: flarglebargle (triggered by keyword)- # Note: The default-tools microagent might not be loaded in tests- assert len(observation.microagent_knowledge) == 1-- # Find the flarglebargle microagent in the list- flarglebargle_knowledge = None- for knowledge in observation.microagent_knowledge:- if knowledge.name == derived_name:- flarglebargle_knowledge = knowledge- break-- # Check against the derived name- assert flarglebargle_knowledge is not None- assert flarglebargle_knowledge.name == derived_name- assert flarglebargle_knowledge.trigger == 'flarglebargle'- assert 'magic word' in flarglebargle_knowledge.content---async def test_custom_secrets_descriptions():- """Test that custom_secrets_descriptions are properly stored in memory and included in RecallObservation."""- # Create a mock event stream- event_stream = MagicMock(spec=EventStream)-- # Initialize Memory- memory = Memory(- event_stream=event_stream,- sid='test-session',- )-- # Create a mock runtime with custom secrets descriptions- mock_runtime = MagicMock()- mock_runtime.web_hosts = {'test-host.example.com': 8080}- mock_runtime.additional_agent_instructions = 'Test instructions'-- # Define custom secrets descriptions- custom_secrets = {- 'API_KEY': 'API key for external service',- 'DATABASE_URL': 'Connection string for the database',- 'SECRET_TOKEN': 'Authentication token for secure operations',- }-- # Set runtime info with custom secrets- memory.set_runtime_info(mock_runtime, custom_secrets, '/workspace')-- # Set repository info- memory.set_repository_info('test-owner/test-repo', '/workspace/test-repo')-- # Create a workspace context recall action- recall_action = RecallAction(- query='Initial message', recall_type=RecallType.WORKSPACE_CONTEXT- )- recall_action._source = EventSource.USER # type: ignore[attr-defined]-- # Mock the event_stream.add_event method- added_events = []-- def mock_add_event(event, source):- added_events.append((event, source))-- event_stream.add_event = mock_add_event-- # Process the recall action- await memory._on_event(recall_action)-- # Verify a RecallObservation was added to the event stream- assert len(added_events) == 1- observation, source = added_events[0]-- # Verify the observation is a RecallObservation- assert isinstance(observation, RecallObservation)- assert source == EventSource.ENVIRONMENT- assert observation.recall_type == RecallType.WORKSPACE_CONTEXT-- # Verify custom_secrets_descriptions are included in the observation- assert observation.custom_secrets_descriptions == custom_secrets-- # Verify repository info is included- assert observation.repo_name == 'test-owner/test-repo'- assert observation.repo_directory == '/workspace/test-repo'-- # Verify runtime info is included- assert observation.runtime_hosts == {'test-host.example.com': 8080}- assert observation.additional_agent_instructions == 'Test instructions'---def test_custom_secrets_descriptions_serialization(prompt_dir):- """Test that custom_secrets_descriptions are properly serialized in the message for the LLM."""- # Create a PromptManager with the test prompt directory- prompt_manager = PromptManager(prompt_dir)-- # Create a RuntimeInfo with custom_secrets_descriptions- custom_secrets = {- 'API_KEY': 'API key for external service',- 'DATABASE_URL': 'Connection string for the database',- 'SECRET_TOKEN': 'Authentication token for secure operations',- }- runtime_info = RuntimeInfo(- date='2025-05-15',- available_hosts={'test-host.example.com': 8080},- additional_agent_instructions='Test instructions',- custom_secrets_descriptions=custom_secrets,- working_dir='/workspace',- )-- # Create a RepositoryInfo- repository_info = RepositoryInfo(- repo_name='test-owner/test-repo',- repo_directory='/workspace/test-repo',- branch_name='main',- )-- conversation_instructions = ConversationInstructions(- content='additional agent context for the task'- )-- # Build the workspace context message- workspace_context = prompt_manager.build_workspace_context(- repository_info=repository_info,- runtime_info=runtime_info,- repo_instructions='Test repository instructions',- conversation_instructions=conversation_instructions,- )-- # Verify that the workspace context includes the custom_secrets_descriptions- assert '<CUSTOM_SECRETS>' in workspace_context- for secret_name, secret_description in custom_secrets.items():- assert f'**${secret_name}**' in workspace_context- assert secret_description in workspace_context-- assert '<CONVERSATION_INSTRUCTIONS>' in workspace_context- assert 'additional agent context for the task' in workspace_context---def test_serialization_deserialization_with_custom_secrets():- """Test that RecallObservation can be serialized and deserialized with custom_secrets_descriptions."""- # This simulates an older version of the RecallObservation- legacy_observation = {- 'message': 'Added workspace context',- 'observation': 'recall',- 'content': 'Test content',- 'extras': {- 'recall_type': 'workspace_context',- 'repo_name': 'test-owner/test-repo',- 'repo_directory': '/workspace/test-repo',- 'repo_instructions': 'Test repository instructions',- 'runtime_hosts': {'test-host.example.com': 8080},- 'additional_agent_instructions': 'Test instructions',- 'date': '2025-05-15',- 'microagent_knowledge': [], # Intentionally omitting custom_secrets_descriptions- },- }-- legacy_observation = observation_from_dict(legacy_observation)-- # Verify that the observation was created successfully- assert legacy_observation.recall_type == RecallType.WORKSPACE_CONTEXT- assert legacy_observation.repo_name == 'test-owner/test-repo'- assert legacy_observation.repo_directory == '/workspace/test-repo'---def test_memory_multiple_repo_microagents(prompt_dir, file_store):- """Test that Memory loads and concatenates multiple repo microagents correctly."""- # Create real event stream- event_stream = EventStream(sid='test-session', file_store=file_store)-- # Create two test repo microagents- repo_microagent1_name = 'test_repo_microagent1'- repo_microagent1_content = """----REPOSITORY INSTRUCTIONS: This is the first test repository.-"""-- repo_microagent2_name = 'test_repo_microagent2'- repo_microagent2_content = """----name: test_repo2-type: repo-agent: CodeActAgent------REPOSITORY INSTRUCTIONS: This is the second test repository.-"""-- # Create temporary repo microagent files- os.makedirs(os.path.join(prompt_dir, 'micro'), exist_ok=True)- with open(- os.path.join(prompt_dir, 'micro', f'{repo_microagent1_name}.md'), 'w'- ) as f:- f.write(repo_microagent1_content)-- with open(- os.path.join(prompt_dir, 'micro', f'{repo_microagent2_name}.md'), 'w'- ) as f:- f.write(repo_microagent2_content)-- # Patch the global microagents directory to use our test directory- test_microagents_dir = os.path.join(prompt_dir, 'micro')- with patch('openhands.memory.memory.GLOBAL_MICROAGENTS_DIR', test_microagents_dir):- # Initialize Memory- memory = Memory(- event_stream=event_stream,- sid='test-session',- )-- # Set repository info- memory.set_repository_info('owner/repo', '/workspace/repo')-- # Create and add the first user message- user_message = MessageAction(content='First user message')- user_message._source = EventSource.USER # type: ignore[attr-defined]- event_stream.add_event(user_message, EventSource.USER)-- # Create and add the microagent action- microagent_action = RecallAction(- query='First user message', recall_type=RecallType.WORKSPACE_CONTEXT- )- microagent_action._source = EventSource.USER # type: ignore[attr-defined]- event_stream.add_event(microagent_action, EventSource.USER)-- # Give it a little time to process- time.sleep(0.3)-- # Get all events from the stream- events = list(event_stream.get_events())-- # Find the RecallObservation event- microagent_obs_events = [- event for event in events if isinstance(event, RecallObservation)- ]-- # We should have one RecallObservation- assert len(microagent_obs_events) > 0-- # Get the first RecallObservation- observation = microagent_obs_events[0]- assert observation.recall_type == RecallType.WORKSPACE_CONTEXT- assert observation.repo_name == 'owner/repo'- assert observation.repo_directory == '/workspace/repo'- assert 'This is the first test repository' in observation.repo_instructions- assert 'This is the second test repository' in observation.repo_instructions-- # Clean up- os.remove(os.path.join(prompt_dir, 'micro', f'{repo_microagent1_name}.md'))- os.remove(os.path.join(prompt_dir, 'micro', f'{repo_microagent2_name}.md'))---async def test_conversation_instructions_plumbed_to_memory(- mock_agent, event_stream, file_store, mock_llm_registry-):- # Setup- session = AgentSession(- sid='test-session',- file_store=file_store,- llm_registry=mock_llm_registry,- conversation_stats=ConversationStats(file_store, 'test-session', None),- )-- # Create a mock runtime and set it up- mock_runtime = MagicMock(spec=ActionExecutionClient)-- # Mock the runtime creation to set up the runtime attribute- async def mock_create_runtime(*args, **kwargs):- session.runtime = mock_runtime- return True-- session._create_runtime = AsyncMock(side_effect=mock_create_runtime)-- # Create a spy on set_initial_state- class SpyAgentController(AgentController):- set_initial_state_call_count = 0- test_initial_state = None-- def set_initial_state(self, *args, state=None, **kwargs):- self.set_initial_state_call_count += 1- self.test_initial_state = state- super().set_initial_state(*args, state=state, **kwargs)-- # Patch AgentController- with (- patch(- 'openhands.server.session.agent_session.AgentController', SpyAgentController- ),- ):- await session.start(- runtime_name='test-runtime',- config=OpenHandsConfig(),- agent=mock_agent,- max_iterations=10,- conversation_instructions='instructions for conversation',- )-- # Use the memory instance from the session, not the fixture- assert (- session.memory.conversation_instructions.content- == 'instructions for conversation'- )diff --git a/tests/unit/utils/test_circular_imports.py b/tests/unit/utils/test_circular_imports.pydeleted file mode 100644index c2fa040f66..0000000000--- a/tests/unit/utils/test_circular_imports.py+++ /dev/null@@ -1,397 +0,0 @@-import os-import re-import unittest---class TestCircularImports(unittest.TestCase):- """Test to detect circular imports in the codebase."""-- def test_no_circular_imports_in_key_modules(self):- """- Test that there are no circular imports in key modules that were previously problematic.-- This test specifically checks the modules that were involved in a previous circular import issue:- - openhands.utils.prompt- - openhands.agenthub.codeact_agent.tools.bash- - openhands.agenthub.codeact_agent.tools.prompt- - openhands.memory.memory- - openhands.memory.conversation_memory- """- # Get the project root directory- project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))-- # Map module names to file paths- module_paths = {- 'openhands.utils.prompt': os.path.join(- project_root, 'openhands/utils/prompt.py'- ),- 'openhands.agenthub.codeact_agent.tools.bash': os.path.join(- project_root, 'openhands/agenthub/codeact_agent/tools/bash.py'- ),- 'openhands.agenthub.codeact_agent.tools.prompt': os.path.join(- project_root, 'openhands/agenthub/codeact_agent/tools/prompt.py'- ),- 'openhands.memory.memory': os.path.join(- project_root, 'openhands/memory/memory.py'- ),- 'openhands.memory.conversation_memory': os.path.join(- project_root, 'openhands/memory/conversation_memory.py'- ),- }-- # Check for the specific circular import pattern that was problematic- circular_imports = self._find_circular_imports(module_paths)-- # If there are any circular imports, fail the test- if circular_imports:- circular_import_str = '\n'.join(- [- f'{module1} -> {module2} -> {module1}'- for module1, module2 in circular_imports- ]- )- self.fail(f'Circular imports detected:\n{circular_import_str}')-- def _find_circular_imports(- self, module_paths: dict[str, str]- ) -> list[tuple[str, str]]:- """- Find circular imports between modules.-- Args:- module_paths: Dictionary mapping module names to file paths-- Returns:- List of tuples (module1, module2) where module1 imports module2 and module2 imports module1- """- # Dictionary to store imports for each module- module_imports = {}-- # Extract imports for each module- for module_name, file_path in module_paths.items():- if os.path.exists(file_path):- with open(file_path, 'r') as f:- source_code = f.read()-- # Extract import statements- import_lines = [- line.strip()- for line in source_code.split('\n')- if line.strip().startswith(('import ', 'from '))- and not line.strip().startswith('# ')- ]-- # Parse import statements to get imported modules- imported_modules = []- for line in import_lines:- if line.startswith('import '):- # Handle "import module" or "import module as alias"- parts = line[7:].split(',')- for part in parts:- module_part = part.strip().split(' as ')[0].strip()- if module_part.startswith('openhands.'):- imported_modules.append(module_part)- elif line.startswith('from '):- # Handle "from module import name" or "from module import name as alias"- module_part = line[5:].split(' import ')[0].strip()- if module_part.startswith('openhands.'):- imported_modules.append(module_part)-- module_imports[module_name] = imported_modules-- # Check for circular imports- circular_imports = []- for module1, imports1 in module_imports.items():- for module2 in imports1:- if module2 in module_imports and module1 in module_imports[module2]:- # Found a circular import- circular_imports.append((module1, module2))-- return circular_imports-- def test_specific_circular_import_pattern(self):- """- Test for the specific circular import pattern that caused the issue in the stack trace.-- The problematic pattern was:- openhands.utils.prompt imports from openhands.agenthub.codeact_agent.tools.bash- openhands.agenthub.codeact_agent.tools.bash imports from openhands.agenthub.codeact_agent.tools.prompt- openhands.agenthub.codeact_agent.tools.prompt imports from openhands.utils.prompt- """- # Get the project root directory- project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))-- # Check if the problematic pattern exists- prompt_path = os.path.join(project_root, 'openhands/utils/prompt.py')- bash_path = os.path.join(- project_root, 'openhands/agenthub/codeact_agent/tools/bash.py'- )- tools_prompt_path = os.path.join(- project_root, 'openhands/agenthub/codeact_agent/tools/prompt.py'- )-- # Check if all files exist- if not all(- os.path.exists(path) for path in [prompt_path, bash_path, tools_prompt_path]- ):- self.skipTest('One or more required files do not exist')-- # Read the files- with open(prompt_path, 'r') as f:- prompt_code = f.read()-- with open(bash_path, 'r') as f:- bash_code = f.read()-- with open(tools_prompt_path, 'r') as f:- tools_prompt_code = f.read()-- # Check for the problematic imports- prompt_imports_bash = (- re.search(- r'from openhands\.agenthub\.codeact_agent\.tools\.bash import',- prompt_code,- )- is not None- )- bash_imports_tools_prompt = (- re.search(- r'from openhands\.agenthub\.codeact_agent\.tools\.prompt import',- bash_code,- )- is not None- )- tools_prompt_imports_prompt = (- re.search(r'from openhands\.utils\.prompt import', tools_prompt_code)- is not None- )-- # If all three imports exist, we have a circular import- if (- prompt_imports_bash- and bash_imports_tools_prompt- and tools_prompt_imports_prompt- ):- self.fail(- 'Circular import pattern detected:\n'- 'openhands.utils.prompt imports from openhands.agenthub.codeact_agent.tools.bash\n'- 'openhands.agenthub.codeact_agent.tools.bash imports from openhands.agenthub.codeact_agent.tools.prompt\n'- 'openhands.agenthub.codeact_agent.tools.prompt imports from openhands.utils.prompt'- )-- def test_detect_circular_imports_in_server_modules(self):- """- Test for circular imports in the server modules that were involved in the stack trace.-- The problematic modules were:- - openhands.server.shared- - openhands.server.conversation_manager.conversation_manager- - openhands.server.session.agent_session- - openhands.server.session- - openhands.server.session.session- """- # Get the project root directory- project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))-- # Map module names to file paths- module_paths = {- 'openhands.server.shared': os.path.join(- project_root, 'openhands/server/shared.py'- ),- 'openhands.server.conversation_manager.conversation_manager': os.path.join(- project_root,- 'openhands/server/conversation_manager/conversation_manager.py',- ),- 'openhands.server.session.agent_session': os.path.join(- project_root, 'openhands/server/session/agent_session.py'- ),- 'openhands.server.session.__init__': os.path.join(- project_root, 'openhands/server/session/__init__.py'- ),- 'openhands.server.session.session': os.path.join(- project_root, 'openhands/server/session/session.py'- ),- }-- # Check for circular imports- circular_imports = self._find_circular_imports(module_paths)-- # If there are any circular imports, fail the test- if circular_imports:- circular_import_str = '\n'.join(- [- f'{module1} -> {module2} -> {module1}'- for module1, module2 in circular_imports- ]- )- self.fail(- f'Circular imports detected in server modules:\n{circular_import_str}'- )-- def test_detect_circular_imports_in_mcp_modules(self):- """- Test for circular imports in the MCP modules that were involved in the stack trace.-- The problematic modules were:- - openhands.mcp- - openhands.mcp.utils- - openhands.memory.memory- """- # Get the project root directory- project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))-- # Map module names to file paths- module_paths = {- 'openhands.mcp.__init__': os.path.join(- project_root, 'openhands/mcp/__init__.py'- ),- 'openhands.mcp.utils': os.path.join(project_root, 'openhands/mcp/utils.py'),- 'openhands.memory.memory': os.path.join(- project_root, 'openhands/memory/memory.py'- ),- }-- # Check for circular imports- circular_imports = self._find_circular_imports(module_paths)-- # If there are any circular imports, fail the test- if circular_imports:- circular_import_str = '\n'.join(- [- f'{module1} -> {module2} -> {module1}'- for module1, module2 in circular_imports- ]- )- self.fail(- f'Circular imports detected in MCP modules:\n{circular_import_str}'- )-- def test_detect_complex_circular_import_chains(self):- """- Test for complex circular import chains involving multiple modules.-- This test checks for circular dependencies that involve more than two modules,- such as A imports B, B imports C, and C imports A.- """- # Get the project root directory- project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))-- # Define the modules involved in the stack trace- modules = [- 'openhands.utils.prompt',- 'openhands.agenthub.codeact_agent.tools.bash',- 'openhands.agenthub.codeact_agent.tools.prompt',- 'openhands.memory.memory',- 'openhands.memory.conversation_memory',- 'openhands.server.shared',- 'openhands.server.conversation_manager.conversation_manager',- 'openhands.server.session.agent_session',- 'openhands.server.session.__init__',- 'openhands.server.session.session',- 'openhands.mcp.__init__',- 'openhands.mcp.utils',- ]-- # Map module names to file paths- module_paths = {}- for module in modules:- if module.endswith('.__init__'):- # Handle __init__.py files- module_path = module[:-9].replace('.', '/')- file_path = os.path.join(project_root, f'{module_path}/__init__.py')- else:- # Handle regular .py files- module_path = module.replace('.', '/')- file_path = os.path.join(project_root, f'{module_path}.py')-- if os.path.exists(file_path):- module_paths[module] = file_path-- # Build the import graph- import_graph = {}- for module_name, file_path in module_paths.items():- with open(file_path, 'r') as f:- source_code = f.read()-- # Extract import statements- import_lines = [- line.strip()- for line in source_code.split('\n')- if line.strip().startswith(('import ', 'from '))- and not line.strip().startswith('# ')- ]-- # Parse import statements to get imported modules- imported_modules = []- for line in import_lines:- if line.startswith('import '):- # Handle "import module" or "import module as alias"- parts = line[7:].split(',')- for part in parts:- module_part = part.strip().split(' as ')[0].strip()- if module_part.startswith('openhands.'):- imported_modules.append(module_part)- elif line.startswith('from '):- # Handle "from module import name" or "from module import name as alias"- module_part = line[5:].split(' import ')[0].strip()- if module_part.startswith('openhands.'):- imported_modules.append(module_part)-- import_graph[module_name] = [- m for m in imported_modules if m in module_paths- ]-- # Check for circular import chains- circular_chains = self._find_circular_chains(import_graph)-- # If there are any circular chains, fail the test- if circular_chains:- circular_chain_str = '\n'.join(- [' -> '.join(chain) for chain in circular_chains]- )- self.fail(f'Complex circular import chains detected:\n{circular_chain_str}')-- def _find_circular_chains(- self, import_graph: dict[str, list[str]]- ) -> list[list[str]]:- """- Find circular import chains in the import graph.-- Args:- import_graph: Dictionary mapping module names to lists of imported modules-- Returns:- List of circular import chains, where each chain is a list of module names- """- circular_chains = []-- def dfs(module: str, path: list[str], visited: set[str]):- """- Depth-first search to find circular import chains.-- Args:- module: Current module being visited- path: Current path in the DFS- visited: Set of modules visited in the current DFS path- """- if module in visited:- # Found a circular import chain- cycle_start = path.index(module)- circular_chains.append(path[cycle_start:] + [module])- return-- visited.add(module)- path.append(module)-- for imported_module in import_graph.get(module, []):- dfs(imported_module, path.copy(), visited.copy())-- # Start DFS from each module- for module in import_graph:- dfs(module, [], set())-- return circular_chains---if __name__ == '__main__':- unittest.main()diff --git a/tests/unit/utils/test_prompt_manager.py b/tests/unit/utils/test_prompt_manager.pydeleted file mode 100644index 1722c0811c..0000000000--- a/tests/unit/utils/test_prompt_manager.py+++ /dev/null@@ -1,456 +0,0 @@-import os-import shutil--import pytest--from openhands.controller.state.control_flags import IterationControlFlag-from openhands.controller.state.state import State-from openhands.core.message import Message, TextContent-from openhands.events.observation.agent import MicroagentKnowledge-from openhands.microagent import BaseMicroagent-from openhands.utils.prompt import (- ConversationInstructions,- PromptManager,- RepositoryInfo,- RuntimeInfo,-)---def prompt_dir(tmp_path):- # Copy contents from "openhands/agenthub/codeact_agent" to the temp directory- shutil.copytree(- 'openhands/agenthub/codeact_agent/prompts', tmp_path, dirs_exist_ok=True- )-- # Return the temporary directory path- return tmp_path---def test_prompt_manager_template_rendering(prompt_dir):- """Test PromptManager's template rendering functionality."""- # Create temporary template files- with open(os.path.join(prompt_dir, 'system_prompt.j2'), 'w') as f:- f.write("""System prompt: bar""")- with open(os.path.join(prompt_dir, 'user_prompt.j2'), 'w') as f:- f.write('User prompt: foo')- with open(os.path.join(prompt_dir, 'additional_info.j2'), 'w') as f:- f.write("""-{% if repository_info %}-<REPOSITORY_INFO>-At the user's request, repository {{ repository_info.repo_name }} has been cloned to the current working directory {{ repository_info.repo_directory }}.-</REPOSITORY_INFO>-{% endif %}-""")-- # Test without GitHub repo- manager = PromptManager(prompt_dir)- assert manager.get_system_message() == 'System prompt: bar'- assert manager.get_example_user_message() == 'User prompt: foo'-- # Test with GitHub repo- manager = PromptManager(prompt_dir=prompt_dir)- repo_info = RepositoryInfo(- repo_name='owner/repo', repo_directory='/workspace/repo', branch_name='main'- )-- # verify its parts are rendered- system_msg = manager.get_system_message()- assert 'System prompt: bar' in system_msg-- # Test building additional info- additional_info = manager.build_workspace_context(- repository_info=repo_info,- runtime_info=None,- repo_instructions='',- conversation_instructions=None,- )- assert '<REPOSITORY_INFO>' in additional_info- assert (- "At the user's request, repository owner/repo has been cloned to the current working directory /workspace/repo."- in additional_info- )- assert '</REPOSITORY_INFO>' in additional_info- assert manager.get_example_user_message() == 'User prompt: foo'-- # Clean up temporary files- os.remove(os.path.join(prompt_dir, 'system_prompt.j2'))- os.remove(os.path.join(prompt_dir, 'user_prompt.j2'))- os.remove(os.path.join(prompt_dir, 'additional_info.j2'))---def test_prompt_manager_file_not_found(prompt_dir):- """Test PromptManager behavior when a template file is not found."""- # Test with a non-existent template- with pytest.raises(FileNotFoundError):- BaseMicroagent.load(- os.path.join(prompt_dir, 'micro', 'non_existent_microagent.md')- )---def test_build_microagent_info(prompt_dir):- """Test the build_microagent_info method with the microagent_info.j2 template."""- # Prepare a microagent_info.j2 template file if it doesn't exist- template_path = os.path.join(prompt_dir, 'microagent_info.j2')- if not os.path.exists(template_path):- with open(template_path, 'w') as f:- f.write("""{% for agent_info in triggered_agents %}-<EXTRA_INFO>-The following information has been included based on a keyword match for "{{ agent_info.trigger }}".-It may or may not be relevant to the user's request.--{{ agent_info.content }}-</EXTRA_INFO>-{% endfor %}-""")-- # Initialize the PromptManager- manager = PromptManager(prompt_dir=prompt_dir)-- # Test with a single triggered agent- triggered_agents = [- MicroagentKnowledge(- name='test_agent1',- trigger='keyword1',- content='This is information from agent 1',- )- ]- result = manager.build_microagent_info(triggered_agents)- expected = """<EXTRA_INFO>-The following information has been included based on a keyword match for "keyword1".-It may or may not be relevant to the user's request.--This is information from agent 1-</EXTRA_INFO>"""- assert result.strip() == expected.strip()-- # Test with multiple triggered agents- triggered_agents = [- MicroagentKnowledge(- name='test_agent1',- trigger='keyword1',- content='This is information from agent 1',- ),- MicroagentKnowledge(- name='test_agent2',- trigger='keyword2',- content='This is information from agent 2',- ),- ]- result = manager.build_microagent_info(triggered_agents)- expected = """<EXTRA_INFO>-The following information has been included based on a keyword match for "keyword1".-It may or may not be relevant to the user's request.--This is information from agent 1-</EXTRA_INFO>--<EXTRA_INFO>-The following information has been included based on a keyword match for "keyword2".-It may or may not be relevant to the user's request.--This is information from agent 2-</EXTRA_INFO>"""- assert result.strip() == expected.strip()-- # Test with no triggered agents- result = manager.build_microagent_info([])- assert result.strip() == ''---def test_add_turns_left_reminder(prompt_dir):- """Test adding turns left reminder to messages."""- # Initialize the PromptManager- manager = PromptManager(prompt_dir=prompt_dir)-- # Create a State object with specific iteration values- state = State(- iteration_flag=IterationControlFlag(- current_value=3, max_value=10, limit_increase_amount=10- )- )-- # Create a list of messages with a user message- user_message = Message(role='user', content=[TextContent(text='User content')])- assistant_message = Message(- role='assistant', content=[TextContent(text='Assistant content')]- )- messages = [assistant_message, user_message]-- # Add turns left reminder- manager.add_turns_left_reminder(messages, state)-- # Check that the reminder was added to the latest user message- assert len(user_message.content) == 2- assert (- 'ENVIRONMENT REMINDER: You have 7 turns left to complete the task.'- in user_message.content[1].text- )---def test_build_workspace_context_with_repo_and_runtime(prompt_dir):- """Test building additional info with repository and runtime information."""- # Create an additional_info.j2 template file- with open(os.path.join(prompt_dir, 'additional_info.j2'), 'w') as f:- f.write("""-{% if repository_info %}-<REPOSITORY_INFO>-At the user's request, repository {{ repository_info.repo_name }} has been cloned to directory {{ repository_info.repo_directory }}.-</REPOSITORY_INFO>-{% endif %}--{% if repository_instructions %}-<REPOSITORY_INSTRUCTIONS>-{{ repository_instructions }}-</REPOSITORY_INSTRUCTIONS>-{% endif %}--{% if runtime_info and (runtime_info.available_hosts or runtime_info.additional_agent_instructions) -%}-<RUNTIME_INFORMATION>-{% if runtime_info.available_hosts %}-The user has access to the following hosts for accessing a web application,-each of which has a corresponding port:-{% for host, port in runtime_info.available_hosts.items() %}-* {{ host }} (port {{ port }})-{% endfor %}-{% endif %}--{% if runtime_info.additional_agent_instructions %}-{{ runtime_info.additional_agent_instructions }}-{% endif %}--Today's date is {{ runtime_info.date }}-</RUNTIME_INFORMATION>-{% if conversation_instructions.content %}-<CONVERSATION_INSTRUCTIONS>-{{ conversation_instructions.content }}-</CONVERSATION_INSTRUCTIONS>-{% endif %}-{% endif %}-""")-- # Initialize the PromptManager- manager = PromptManager(prompt_dir=prompt_dir)-- # Create repository and runtime information- repo_info = RepositoryInfo(- repo_name='owner/repo', repo_directory='/workspace/repo', branch_name='main'- )- runtime_info = RuntimeInfo(- date='02/12/1232',- available_hosts={'example.com': 8080},- additional_agent_instructions='You know everything about this runtime.',- working_dir='/workspace',- )- repo_instructions = 'This repository contains important code.'-- conversation_instructions = ConversationInstructions(content='additional context')-- # Build additional info- result = manager.build_workspace_context(- repository_info=repo_info,- runtime_info=runtime_info,- repo_instructions=repo_instructions,- conversation_instructions=conversation_instructions,- )-- # Check that all information is included- assert '<REPOSITORY_INFO>' in result- assert 'owner/repo' in result- assert '/workspace/repo' in result- assert '<REPOSITORY_INSTRUCTIONS>' in result- assert 'This repository contains important code.' in result- assert '<RUNTIME_INFORMATION>' in result- assert 'example.com (port 8080)' in result- assert 'You know everything about this runtime.' in result- assert "Today's date is 02/12/1232" in result- assert 'additional context' in result-- # Clean up- os.remove(os.path.join(prompt_dir, 'additional_info.j2'))---def test_prompt_manager_initialization_error():- """Test that PromptManager raises an error if the prompt directory is not set."""- with pytest.raises(ValueError, match='Prompt directory is not set'):- PromptManager(None)---def test_prompt_manager_custom_system_prompt_filename(prompt_dir):- """Test that PromptManager can use a custom system prompt filename."""- # Create a custom system prompt file- with open(os.path.join(prompt_dir, 'custom_system.j2'), 'w') as f:- f.write('Custom system prompt: {{ custom_var }}')-- # Create default system prompt- with open(os.path.join(prompt_dir, 'system_prompt.j2'), 'w') as f:- f.write('Default system prompt')-- # Test with custom system prompt filename- manager = PromptManager(- prompt_dir=prompt_dir, system_prompt_filename='custom_system.j2'- )- system_msg = manager.get_system_message()- assert 'Custom system prompt:' in system_msg-- # Test without custom system prompt filename (should use default)- manager_default = PromptManager(prompt_dir=prompt_dir)- default_msg = manager_default.get_system_message()- assert 'Default system prompt' in default_msg-- # Clean up- os.remove(os.path.join(prompt_dir, 'custom_system.j2'))- os.remove(os.path.join(prompt_dir, 'system_prompt.j2'))---def test_prompt_manager_custom_system_prompt_filename_not_found(prompt_dir):- """Test that PromptManager raises an error if custom system prompt file is not found."""- with pytest.raises(- FileNotFoundError,- match=r'Prompt file .*/non_existent\.j2 not found',- ):- PromptManager(prompt_dir=prompt_dir, system_prompt_filename='non_existent.j2')---def test_jinja2_template_inheritance(prompt_dir):- """Test that PromptManager._load_template works with Jinja2 template inclusion.-- This test demonstrates that we can use {% include %} to import a base system_prompt.j2- into other templates without defining any blocks in the base template, and that- PromptManager._load_template can load these templates correctly.- """- # Create base system prompt template (no blocks defined here)- with open(os.path.join(prompt_dir, 'system_prompt.j2'), 'w') as f:- f.write("""You are OpenHands agent, a helpful AI assistant that can interact with a computer to solve tasks.--<ROLE>-Your primary role is to assist users by executing commands, modifying code, and solving technical problems effectively.-</ROLE>-""")-- # Create interactive system prompt that imports the base template and adds content- with open(os.path.join(prompt_dir, 'system_prompt_interactive.j2'), 'w') as f:- f.write("""{% include "system_prompt.j2" %}--<INTERACTION_RULES>-1. Always respond in a friendly, helpful manner-2. Ask clarifying questions when needed-3. Provide step-by-step explanations-</INTERACTION_RULES>-""")-- # Create long horizon system prompt that imports the base template and adds content- with open(os.path.join(prompt_dir, 'system_prompt_long_horizon.j2'), 'w') as f:- f.write("""{% include "system_prompt.j2" %}--<TASK_MANAGEMENT>-1. Break down complex tasks into smaller steps-2. Track progress through a TODO list-3. Focus on one task at a time-</TASK_MANAGEMENT>-""")-- # Test PromptManager._load_template with base system prompt- base_manager = PromptManager(prompt_dir=prompt_dir)- base_template = base_manager._load_template('system_prompt.j2')- base_msg = base_template.render().strip()- assert 'You are OpenHands agent' in base_msg- assert '<ROLE>' in base_msg- assert '<INTERACTION_RULES>' not in base_msg- assert '<TASK_MANAGEMENT>' not in base_msg-- # Test PromptManager._load_template with interactive system prompt- interactive_manager = PromptManager(- prompt_dir=prompt_dir, system_prompt_filename='system_prompt_interactive.j2'- )- interactive_template = interactive_manager._load_template(- 'system_prompt_interactive.j2'- )- interactive_msg = interactive_template.render().strip()- assert 'You are OpenHands agent' in interactive_msg- assert '<ROLE>' in interactive_msg- assert '<INTERACTION_RULES>' in interactive_msg- assert 'Ask clarifying questions when needed' in interactive_msg- assert '<TASK_MANAGEMENT>' not in interactive_msg-- # Test PromptManager._load_template with long horizon system prompt- long_horizon_manager = PromptManager(- prompt_dir=prompt_dir, system_prompt_filename='system_prompt_long_horizon.j2'- )- long_horizon_template = long_horizon_manager._load_template(- 'system_prompt_long_horizon.j2'- )- long_horizon_msg = long_horizon_template.render().strip()- assert 'You are OpenHands agent' in long_horizon_msg- assert '<ROLE>' in long_horizon_msg- assert '<INTERACTION_RULES>' not in long_horizon_msg- assert '<TASK_MANAGEMENT>' in long_horizon_msg- assert 'Track progress through a TODO list' in long_horizon_msg-- # Clean up- os.remove(os.path.join(prompt_dir, 'system_prompt.j2'))- os.remove(os.path.join(prompt_dir, 'system_prompt_interactive.j2'))- os.remove(os.path.join(prompt_dir, 'system_prompt_long_horizon.j2'))---def test_prompt_manager_cli_mode_context(prompt_dir):- """Test that PromptManager.get_system_message() supports cli_mode context parameter."""- # Create a system prompt template that uses cli_mode conditional- with open(os.path.join(prompt_dir, 'system_prompt.j2'), 'w') as f:- f.write("""You are OpenHands agent.--{% if cli_mode %}-<CLI_MODE>-You are running in CLI mode. Direct file system access is available.-</CLI_MODE>-{% else %}-<SANDBOX_MODE>-You are running inside sandbox. Container-scoped operations are available.-</SANDBOX_MODE>-{% endif %}--<COMMON_INSTRUCTIONS>-Always be helpful and follow user instructions.-</COMMON_INSTRUCTIONS>""")-- manager = PromptManager(prompt_dir)-- # Test with cli_mode=True- cli_message = manager.get_system_message(cli_mode=True)- assert 'You are OpenHands agent' in cli_message- assert '<CLI_MODE>' in cli_message- assert 'CLI mode' in cli_message- assert 'Direct file system access' in cli_message- assert '<SANDBOX_MODE>' not in cli_message- assert 'inside sandbox' not in cli_message- assert '<COMMON_INSTRUCTIONS>' in cli_message-- # Test with cli_mode=False- sandbox_message = manager.get_system_message(cli_mode=False)- assert 'You are OpenHands agent' in sandbox_message- assert '<SANDBOX_MODE>' in sandbox_message- assert 'inside sandbox' in sandbox_message- assert 'Container-scoped operations' in sandbox_message- assert '<CLI_MODE>' not in sandbox_message- assert 'CLI mode' not in sandbox_message- assert '<COMMON_INSTRUCTIONS>' in sandbox_message-- # Test without cli_mode parameter (backward compatibility)- default_message = manager.get_system_message()- assert 'You are OpenHands agent' in default_message- assert '<COMMON_INSTRUCTIONS>' in default_message- # Without cli_mode, the conditional should evaluate to False- assert '<SANDBOX_MODE>' in default_message- assert '<CLI_MODE>' not in default_message-- # Test with additional context parameters- mixed_message = manager.get_system_message(cli_mode=True, custom_var='test_value')- assert '<CLI_MODE>' in mixed_message- assert '<COMMON_INSTRUCTIONS>' in mixed_message-- # Verify messages are different based on cli_mode- assert cli_message != sandbox_message- assert len(cli_message) != len(sandbox_message)-- # Clean up- os.remove(os.path.join(prompt_dir, 'system_prompt.j2'))