Skip to content

πŸ™Œ OpenHands: AI-Driven Development

refactor: remove external dependencies on V0 packages (controller, memory, microagent) (#14106)

Tim O'Farrellfb98faf4acc8
diff --git a/openhands/app_server/user/skills_router.py b/openhands/app_server/user/skills_router.py
index 2e192e7a29..ea3d0f673d 100644
--- a/openhands/app_server/user/skills_router.py
+++ b/openhands/app_server/user/skills_router.py
@@ -1,3 +1,4 @@
+import os
from pathlib import Path
from typing import Annotated
@@ -5,15 +6,14 @@ import yaml
from fastapi import APIRouter, Query
from pydantic import BaseModel
+import openhands
from openhands.app_server.utils.dependencies import get_dependencies
from openhands.core.logger import openhands_logger as logger
-from openhands.memory.memory import GLOBAL_MICROAGENTS_DIR, USER_MICROAGENTS_DIR
router = APIRouter(prefix='/skills', tags=['Skills'], dependencies=get_dependencies())
-# Re-use V0 path constants (single source of truth)
-GLOBAL_SKILLS_DIR = Path(GLOBAL_MICROAGENTS_DIR)
-USER_SKILLS_DIR = Path(USER_MICROAGENTS_DIR)
+GLOBAL_SKILLS_DIR = Path(os.path.dirname(openhands.__file__)) / 'skills'
+USER_SKILLS_DIR = Path.home() / '.openhands' / 'microagents'
class SkillInfo(BaseModel):
diff --git a/openhands/core/setup.py b/openhands/core/setup.py
index 91d6639de9..3acd7e37c5 100644
--- a/openhands/core/setup.py
+++ b/openhands/core/setup.py
@@ -8,30 +8,19 @@
import hashlib
import os
import uuid
-from typing import Callable
from pydantic import SecretStr
-from openhands.controller import AgentController
-from openhands.controller.agent import Agent
-from openhands.controller.state.state import State
from openhands.core.config import (
OpenHandsConfig,
)
-from openhands.core.config.config_utils import DEFAULT_WORKSPACE_MOUNT_PATH_IN_SANDBOX
from openhands.core.logger import openhands_logger as logger
-from openhands.events import EventStream
-from openhands.events.event import Event
from openhands.integrations.provider import (
PROVIDER_TOKEN_TYPE,
ProviderToken,
ProviderType,
)
-from openhands.llm.llm_registry import LLMRegistry
-from openhands.memory.memory import Memory
-from openhands.microagent.microagent import BaseMicroagent
from openhands.runtime.base import Runtime
-from openhands.server.services.conversation_stats import ConversationStats
from openhands.storage.data_models.secrets import Secrets
from openhands.utils.async_utils import GENERAL_TIMEOUT, call_async_from_sync
@@ -125,96 +114,6 @@ def initialize_repository_for_runtime(
return repo_directory
-def create_memory(
- runtime: Runtime,
- event_stream: EventStream,
- sid: str,
- selected_repository: str | None = None,
- repo_directory: str | None = None,
- status_callback: Callable | None = None,
- conversation_instructions: str | None = None,
- working_dir: str = DEFAULT_WORKSPACE_MOUNT_PATH_IN_SANDBOX,
-) -> Memory:
- """Create a memory for the agent to use.
-
- Args:
- runtime: The runtime to use.
- event_stream: The event stream it will subscribe to.
- sid: The session id.
- selected_repository: The repository to clone and start with, if any.
- repo_directory: The repository directory, if any.
- status_callback: Optional callback function to handle status updates.
- conversation_instructions: Optional instructions that are passed to the agent
- """
- memory = Memory(
- event_stream=event_stream,
- sid=sid,
- status_callback=status_callback,
- )
-
- memory.set_conversation_instructions(conversation_instructions)
-
- if runtime:
- # sets available hosts
- memory.set_runtime_info(runtime, {}, working_dir)
-
- # loads microagents from repo/.openhands/microagents
- microagents: list[BaseMicroagent] = runtime.get_microagents_from_selected_repo(
- selected_repository
- )
- memory.load_user_workspace_microagents(microagents)
-
- if selected_repository and repo_directory:
- memory.set_repository_info(selected_repository, repo_directory)
-
- return memory
-
-
-def create_agent(config: OpenHandsConfig, llm_registry: LLMRegistry) -> Agent:
- agent_cls: type[Agent] = Agent.get_cls(config.default_agent)
- agent_config = config.get_agent_config(config.default_agent)
- # Pass the runtime information from the main config to the agent config
- agent_config.runtime = config.runtime
- config.get_llm_config_from_agent(config.default_agent)
- agent = agent_cls(config=agent_config, llm_registry=llm_registry)
- return agent
-
-
-def create_controller(
- agent: Agent,
- runtime: Runtime,
- config: OpenHandsConfig,
- conversation_stats: ConversationStats,
- headless_mode: bool = True,
- replay_events: list[Event] | None = None,
-) -> tuple[AgentController, State | None]:
- event_stream = runtime.event_stream
- initial_state = None
- try:
- logger.debug(
- f'Trying to restore agent state from session {event_stream.sid} if available'
- )
- initial_state = State.restore_from_session(
- event_stream.sid, event_stream.file_store
- )
- except Exception as e:
- logger.debug(f'Cannot restore agent state: {e}')
-
- controller = AgentController(
- agent=agent,
- conversation_stats=conversation_stats,
- iteration_delta=config.max_iterations,
- budget_per_task_delta=config.max_budget_per_task,
- agent_to_llm_config=config.get_agent_to_llm_config_map(),
- event_stream=event_stream,
- initial_state=initial_state,
- headless_mode=headless_mode,
- confirmation_mode=config.security.confirmation_mode,
- replay_events=replay_events,
- )
- return (controller, initial_state)
-
-
def generate_sid(config: OpenHandsConfig, session_name: str | None = None) -> str:
"""Generate a session id based on the session name and the jwt secret.
diff --git a/openhands/mcp/__init__.py b/openhands/mcp/__init__.py
index a7ba3ec3bd..963dcef01d 100644
--- a/openhands/mcp/__init__.py
+++ b/openhands/mcp/__init__.py
@@ -2,7 +2,6 @@ from openhands.mcp.client import MCPClient
from openhands.mcp.error_collector import mcp_error_collector
from openhands.mcp.tool import MCPClientTool
from openhands.mcp.utils import (
- add_mcp_tools_to_agent,
call_tool_mcp,
convert_mcp_clients_to_tools,
create_mcp_clients,
@@ -16,6 +15,5 @@ __all__ = [
'MCPClientTool',
'fetch_mcp_tools_from_config',
'call_tool_mcp',
- 'add_mcp_tools_to_agent',
'mcp_error_collector',
]
diff --git a/openhands/mcp/utils.py b/openhands/mcp/utils.py
index c6326ba1d7..fac4dfb4d3 100644
--- a/openhands/mcp/utils.py
+++ b/openhands/mcp/utils.py
@@ -1,12 +1,6 @@
import asyncio
import json
import shutil
-from typing import TYPE_CHECKING
-
-if TYPE_CHECKING:
- from openhands.controller.agent import Agent
- from openhands.memory.memory import Memory
-
from mcp import McpError
@@ -21,7 +15,6 @@ from openhands.events.observation.mcp import MCPObservation
from openhands.events.observation.observation import Observation
from openhands.mcp.client import MCPClient
from openhands.mcp.error_collector import mcp_error_collector
-from openhands.runtime.base import Runtime
from openhands.utils._redact_compat import (
redact_text_secrets,
redact_url_params,
@@ -269,49 +262,3 @@ async def call_tool_mcp(mcp_clients: list[MCPClient], action: MCPAction) -> Obse
name=action.name,
arguments=action.arguments,
)
-
-
-async def add_mcp_tools_to_agent(
- agent: 'Agent', runtime: Runtime, memory: 'Memory'
-) -> MCPConfig:
- """Add MCP tools to an agent."""
- import sys
-
- # Skip MCP tools on Windows
- if sys.platform == 'win32':
- logger.info('MCP functionality is disabled on Windows, skipping MCP tools')
- agent.set_mcp_tools([])
- return
-
- assert runtime.runtime_initialized, (
- 'Runtime must be initialized before adding MCP tools'
- )
-
- extra_stdio_servers: dict[str, StdioMCPServer] = {}
-
- # Add microagent MCP tools if available
- microagent_mcp_configs = memory.get_microagent_mcp_tools()
- for mcp_cfg in microagent_mcp_configs:
- for name, server in mcp_cfg.mcpServers.items():
- if isinstance(server, StdioMCPServer):
- if name not in extra_stdio_servers:
- extra_stdio_servers[name] = server
- logger.warning(f'Added microagent stdio server: {name}')
- else:
- logger.warning(
- f'Microagent MCP config contains non-stdio server {name}, not yet supported.'
- )
-
- # Add the runtime as another MCP server
- updated_mcp_config = runtime.get_mcp_config(extra_stdio_servers or None)
-
- # Fetch the MCP tools
- mcp_tools = await fetch_mcp_tools_from_config(updated_mcp_config)
-
- tool_names = [tool['function']['name'] for tool in mcp_tools]
- logger.info(f'Loaded {len(mcp_tools)} MCP tools: {tool_names}')
-
- # Set the MCP tools on the agent
- agent.set_mcp_tools(mcp_tools)
-
- return updated_mcp_config
diff --git a/tests/runtime/test_mcp_action.py b/tests/runtime/test_mcp_action.py
index 781b508d8f..49fde95a1f 100644
--- a/tests/runtime/test_mcp_action.py
+++ b/tests/runtime/test_mcp_action.py
@@ -1,22 +1,13 @@
"""Bash-related tests for the DockerRuntime, which connects to the ActionExecutor running in the sandbox."""
-import json
import os
import socket
import time
import docker
import pytest
-from conftest import (
- _load_runtime,
-)
-import openhands
-from openhands.core.config import MCPConfig
-from openhands.core.config.mcp_config import RemoteMCPServer, StdioMCPServer
from openhands.core.logger import openhands_logger as logger
-from openhands.events.action import CmdRunAction, MCPAction
-from openhands.events.observation import CmdOutputObservation, MCPObservation
# ============================================================================================================================
# Bash-specific tests
@@ -104,289 +95,3 @@ def sse_mcp_docker_server():
logger.error(f'Error stopping container {container.short_id}: {e}')
if log_streamer:
log_streamer.close()
-
-
[email protected]('This test is flaky')
-def test_default_activated_tools():
- import importlib.resources
-
- # Use importlib.resources to access the config file properly
- # This works both when running from source and from installed package
- try:
- with importlib.resources.as_file(
- importlib.resources.files('openhands').joinpath(
- 'runtime', 'mcp', 'config.json'
- )
- ) as config_path:
- assert config_path.exists(), f'MCP config file not found at {config_path}'
- with open(config_path, 'r') as f:
- mcp_config = json.load(f)
- except (FileNotFoundError, ImportError):
- # Fallback to the old method for development environments
- project_root = os.path.dirname(openhands.__file__)
- mcp_config_path = os.path.join(project_root, 'runtime', 'mcp', 'config.json')
- assert os.path.exists(mcp_config_path), (
- f'MCP config file not found at {mcp_config_path}'
- )
- with open(mcp_config_path, 'r') as f:
- mcp_config = json.load(f)
-
- assert 'mcpServers' in mcp_config
- assert 'default' in mcp_config['mcpServers']
- assert 'tools' in mcp_config
- # no tools are always activated yet
- assert len(mcp_config['tools']) == 0
-
-
[email protected]('This test is flaky')
-async def test_fetch_mcp_via_stdio(
- temp_dir, runtime_cls, run_as_openhands, dynamic_port
-):
- mcp_stdio_server_config = StdioMCPServer(
- name='fetch', command='uvx', args=['mcp-server-fetch']
- )
- override_mcp_config = MCPConfig(stdio_servers=[mcp_stdio_server_config])
- runtime, config = _load_runtime(
- temp_dir,
- runtime_cls,
- run_as_openhands,
- override_mcp_config=override_mcp_config,
- enable_browser=True,
- )
-
- # Test browser server
- action_cmd = CmdRunAction(
- command=f'python3 -m http.server {dynamic_port} > server.log 2>&1 &'
- )
- logger.info(action_cmd, extra={'msg_type': 'ACTION'})
- obs = runtime.run_action(action_cmd)
- logger.info(obs, extra={'msg_type': 'OBSERVATION'})
-
- assert isinstance(obs, CmdOutputObservation)
- assert obs.exit_code == 0
- assert '[1]' in obs.content
-
- action_cmd = CmdRunAction(command='sleep 3 && cat server.log')
- logger.info(action_cmd, extra={'msg_type': 'ACTION'})
- obs = runtime.run_action(action_cmd)
- logger.info(obs, extra={'msg_type': 'OBSERVATION'})
- assert obs.exit_code == 0
-
- mcp_action = MCPAction(
- name='fetch', arguments={'url': f'http://localhost:{dynamic_port}'}
- )
- obs = await runtime.call_tool_mcp(mcp_action)
- logger.info(obs, extra={'msg_type': 'OBSERVATION'})
- assert isinstance(obs, MCPObservation), (
- 'The observation should be a MCPObservation.'
- )
-
- result_json = json.loads(obs.content)
- assert not result_json['isError']
- assert len(result_json['content']) == 1
- assert result_json['content'][0]['type'] == 'text'
- assert (
- result_json['content'][0]['text']
- == f'Contents of http://localhost:{dynamic_port}/:\n---\n\n* <.downloads/>\n* <server.log>\n\n---'
- )
-
- runtime.close()
-
-
[email protected]('This test is flaky')
-async def test_filesystem_mcp_via_sse(
- temp_dir, runtime_cls, run_as_openhands, sse_mcp_docker_server
-):
- sse_server_info = sse_mcp_docker_server
- sse_url = sse_server_info['url']
- runtime = None
- try:
- override_mcp_config = MCPConfig(
- mcpServers={'fs': RemoteMCPServer(url=sse_url, transport='sse')}
- )
- runtime, config = _load_runtime(
- temp_dir,
- runtime_cls,
- run_as_openhands,
- override_mcp_config=override_mcp_config,
- )
-
- mcp_action = MCPAction(name='list_directory', arguments={'path': '.'})
- obs = await runtime.call_tool_mcp(mcp_action)
- logger.info(obs, extra={'msg_type': 'OBSERVATION'})
- assert isinstance(obs, MCPObservation), (
- 'The observation should be a MCPObservation.'
- )
- assert '[FILE] .dockerenv' in obs.content
-
- finally:
- if runtime:
- runtime.close()
- # Container and log_streamer cleanup is handled by the sse_mcp_docker_server fixture
-
-
[email protected]('This test is flaky')
-async def test_both_stdio_and_sse_mcp(
- temp_dir, runtime_cls, run_as_openhands, sse_mcp_docker_server, dynamic_port
-):
- sse_server_info = sse_mcp_docker_server
- sse_url = sse_server_info['url']
- runtime = None
- try:
- override_mcp_config = MCPConfig(
- mcpServers={
- 'fs': RemoteMCPServer(url=sse_url, transport='sse'),
- 'fetch': StdioMCPServer(command='uvx', args=['mcp-server-fetch']),
- }
- )
- runtime, config = _load_runtime(
- temp_dir,
- runtime_cls,
- run_as_openhands,
- override_mcp_config=override_mcp_config,
- enable_browser=True,
- )
-
- # ======= Test SSE server =======
- mcp_action_sse = MCPAction(name='list_directory', arguments={'path': '.'})
- obs_sse = await runtime.call_tool_mcp(mcp_action_sse)
- logger.info(obs_sse, extra={'msg_type': 'OBSERVATION'})
- assert isinstance(obs_sse, MCPObservation), (
- 'The observation should be a MCPObservation.'
- )
- assert '[FILE] .dockerenv' in obs_sse.content
-
- # ======= Test stdio server =======
- # Test browser server
- action_cmd_http = CmdRunAction(
- command=f'python3 -m http.server {dynamic_port} > server.log 2>&1 &'
- )
- logger.info(action_cmd_http, extra={'msg_type': 'ACTION'})
- obs_http = runtime.run_action(action_cmd_http)
- logger.info(obs_http, extra={'msg_type': 'OBSERVATION'})
-
- assert isinstance(obs_http, CmdOutputObservation)
- assert obs_http.exit_code == 0
- assert '[1]' in obs_http.content
-
- action_cmd_cat = CmdRunAction(command='sleep 3 && cat server.log')
- logger.info(action_cmd_cat, extra={'msg_type': 'ACTION'})
- obs_cat = runtime.run_action(action_cmd_cat)
- logger.info(obs_cat, extra={'msg_type': 'OBSERVATION'})
- assert obs_cat.exit_code == 0
-
- mcp_action_fetch = MCPAction(
- # NOTE: the tool name is `fetch_fetch` because the tool name is `fetch`
- # And FastMCP Proxy will pre-pend the server name (in this case, `fetch`)
- # to the tool name, so the full tool name becomes `fetch_fetch`
- name='fetch',
- arguments={'url': f'http://localhost:{dynamic_port}'},
- )
- obs_fetch = await runtime.call_tool_mcp(mcp_action_fetch)
- logger.info(obs_fetch, extra={'msg_type': 'OBSERVATION'})
- assert isinstance(obs_fetch, MCPObservation), (
- 'The observation should be a MCPObservation.'
- )
-
- result_json = json.loads(obs_fetch.content)
- assert not result_json['isError']
- assert len(result_json['content']) == 1
- assert result_json['content'][0]['type'] == 'text'
- assert (
- result_json['content'][0]['text']
- == f'Contents of http://localhost:{dynamic_port}/:\n---\n\n* <.downloads/>\n* <server.log>\n\n---'
- )
- finally:
- if runtime:
- runtime.close()
- # SSE Docker container cleanup is handled by the sse_mcp_docker_server fixture
-
-
[email protected]('This test is flaky')
-async def test_microagent_and_one_stdio_mcp_in_config(
- temp_dir, runtime_cls, run_as_openhands, dynamic_port
-):
- runtime = None
- try:
- filesystem_config = StdioMCPServer(
- name='filesystem',
- command='npx',
- args=[
- '@modelcontextprotocol/[email protected]',
- '/',
- ],
- )
- override_mcp_config = MCPConfig(stdio_servers=[filesystem_config])
- runtime, config = _load_runtime(
- temp_dir,
- runtime_cls,
- run_as_openhands,
- override_mcp_config=override_mcp_config,
- enable_browser=True,
- )
-
- # NOTE: this simulate the case where the microagent adds a new stdio server to the runtime
- # but that stdio server is not in the initial config
- # Actual invocation of the microagent involves `add_mcp_tools_to_agent`
- # which will call `get_mcp_config` with the stdio server from microagent's config
- fetch_config = StdioMCPServer(
- name='fetch', command='uvx', args=['mcp-server-fetch']
- )
- updated_config = runtime.get_mcp_config([fetch_config])
- logger.info(f'updated_config: {updated_config}')
-
- # ======= Test the stdio server in the config =======
- mcp_action_sse = MCPAction(
- name='filesystem_list_directory', arguments={'path': '/'}
- )
- obs_sse = await runtime.call_tool_mcp(mcp_action_sse)
- logger.info(obs_sse, extra={'msg_type': 'OBSERVATION'})
- assert isinstance(obs_sse, MCPObservation), (
- 'The observation should be a MCPObservation.'
- )
- assert '[FILE] .dockerenv' in obs_sse.content
-
- # ======= Test the stdio server added by the microagent =======
- # Test browser server
- action_cmd_http = CmdRunAction(
- command=f'python3 -m http.server {dynamic_port} > server.log 2>&1 &'
- )
- logger.info(action_cmd_http, extra={'msg_type': 'ACTION'})
- obs_http = runtime.run_action(action_cmd_http)
- logger.info(obs_http, extra={'msg_type': 'OBSERVATION'})
-
- assert isinstance(obs_http, CmdOutputObservation)
- assert obs_http.exit_code == 0
- assert '[1]' in obs_http.content
-
- action_cmd_cat = CmdRunAction(command='sleep 3 && cat server.log')
- logger.info(action_cmd_cat, extra={'msg_type': 'ACTION'})
- obs_cat = runtime.run_action(action_cmd_cat)
- logger.info(obs_cat, extra={'msg_type': 'OBSERVATION'})
- assert obs_cat.exit_code == 0
-
- mcp_action_fetch = MCPAction(
- name='fetch_fetch', arguments={'url': f'http://localhost:{dynamic_port}'}
- )
- obs_fetch = await runtime.call_tool_mcp(mcp_action_fetch)
- logger.info(obs_fetch, extra={'msg_type': 'OBSERVATION'})
- assert isinstance(obs_fetch, MCPObservation), (
- 'The observation should be a MCPObservation.'
- )
-
- result_json = json.loads(obs_fetch.content)
- assert not result_json['isError']
- assert len(result_json['content']) == 1
- assert result_json['content'][0]['type'] == 'text'
- assert (
- result_json['content'][0]['text']
- == f'Contents of http://localhost:{dynamic_port}/:\n---\n\n* <.downloads/>\n* <server.log>\n\n---'
- )
- finally:
- if runtime:
- runtime.close()
- # SSE Docker container cleanup is handled by the sse_mcp_docker_server fixture
diff --git a/tests/runtime/test_microagent.py b/tests/runtime/test_microagent.py
deleted file mode 100644
index 94cb28d11b..0000000000
--- a/tests/runtime/test_microagent.py
+++ /dev/null
@@ -1,437 +0,0 @@
-"""Tests for microagent loading in runtime."""
-
-import os
-import tempfile
-from pathlib import Path
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-from conftest import (
- _close_test_runtime,
- _load_runtime,
-)
-
-from openhands.core.config import MCPConfig
-from openhands.core.config.mcp_config import StdioMCPServer
-from openhands.mcp.utils import add_mcp_tools_to_agent
-from openhands.microagent.microagent import (
- BaseMicroagent,
- KnowledgeMicroagent,
- RepoMicroagent,
- TaskMicroagent,
-)
-from openhands.microagent.types import MicroagentType
-
-
-def _create_test_microagents(test_dir: str):
- """Create test microagent files in the given directory."""
- microagents_dir = Path(test_dir) / '.openhands' / 'microagents'
- microagents_dir.mkdir(parents=True, exist_ok=True)
-
- # Create test knowledge agent
- knowledge_dir = microagents_dir / 'knowledge'
- knowledge_dir.mkdir(exist_ok=True)
- knowledge_agent = """---
-name: test_knowledge_agent
-type: knowledge
-version: 1.0.0
-agent: CodeActAgent
-triggers:
- - test
- - pytest
----
-
-# Test Guidelines
-
-Testing best practices and guidelines.
-"""
- (knowledge_dir / 'knowledge.md').write_text(knowledge_agent)
-
- # Create test repo agent
- repo_agent = """---
-name: test_repo_agent
-type: repo
-version: 1.0.0
-agent: CodeActAgent
----
-
-# Test Repository Agent
-
-Repository-specific test instructions.
-"""
- (microagents_dir / 'repo.md').write_text(repo_agent)
-
- # Create legacy repo instructions
- legacy_instructions = """# Legacy Instructions
-
-These are legacy repository instructions.
-"""
- (Path(test_dir) / '.openhands_instructions').write_text(legacy_instructions)
-
-
-def test_load_microagents_with_trailing_slashes(
- temp_dir, runtime_cls, run_as_openhands
-):
- """Test loading microagents when directory paths have trailing slashes."""
- # Create test files
- _create_test_microagents(temp_dir)
- runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
- try:
- # Load microagents
- loaded_agents = runtime.get_microagents_from_selected_repo(None)
-
- # Verify all agents are loaded
- knowledge_agents = [
- a for a in loaded_agents if isinstance(a, KnowledgeMicroagent)
- ]
- repo_agents = [a for a in loaded_agents if isinstance(a, RepoMicroagent)]
-
- # Check knowledge agents
- assert len(knowledge_agents) == 1
- agent = knowledge_agents[0]
- assert agent.name == 'knowledge/knowledge'
- assert 'test' in agent.triggers
- assert 'pytest' in agent.triggers
-
- # Check repo agents (including legacy)
- assert len(repo_agents) == 2 # repo.md + .openhands_instructions
- repo_names = {a.name for a in repo_agents}
- assert 'repo' in repo_names
- assert 'repo_legacy' in repo_names
-
- finally:
- _close_test_runtime(runtime)
-
-
-def test_load_microagents_with_selected_repo(temp_dir, runtime_cls, run_as_openhands):
- """Test loading microagents from a selected repository."""
- # Create test files in a repository-like structure
- repo_dir = Path(temp_dir) / 'OpenHands'
- repo_dir.mkdir(parents=True)
- _create_test_microagents(str(repo_dir))
-
- runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
- try:
- # Load microagents with selected repository
- loaded_agents = runtime.get_microagents_from_selected_repo(
- 'OpenHands/OpenHands'
- )
-
- # Verify all agents are loaded
- knowledge_agents = [
- a for a in loaded_agents if isinstance(a, KnowledgeMicroagent)
- ]
- repo_agents = [a for a in loaded_agents if isinstance(a, RepoMicroagent)]
-
- # Check knowledge agents
- assert len(knowledge_agents) == 1
- agent = knowledge_agents[0]
- assert agent.name == 'knowledge/knowledge'
- assert 'test' in agent.triggers
- assert 'pytest' in agent.triggers
-
- # Check repo agents (including legacy)
- assert len(repo_agents) == 2 # repo.md + .openhands_instructions
- repo_names = {a.name for a in repo_agents}
- assert 'repo' in repo_names
- assert 'repo_legacy' in repo_names
-
- finally:
- _close_test_runtime(runtime)
-
-
-def test_load_microagents_with_missing_files(temp_dir, runtime_cls, run_as_openhands):
- """Test loading microagents when some files are missing."""
- # Create only repo.md, no other files
- microagents_dir = Path(temp_dir) / '.openhands' / 'microagents'
- microagents_dir.mkdir(parents=True, exist_ok=True)
-
- repo_agent = """---
-name: test_repo_agent
-type: repo
-version: 1.0.0
-agent: CodeActAgent
----
-
-# Test Repository Agent
-
-Repository-specific test instructions.
-"""
- (microagents_dir / 'repo.md').write_text(repo_agent)
-
- runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
- try:
- # Load microagents
- loaded_agents = runtime.get_microagents_from_selected_repo(None)
-
- # Verify only repo agent is loaded
- knowledge_agents = [
- a for a in loaded_agents if isinstance(a, KnowledgeMicroagent)
- ]
- repo_agents = [a for a in loaded_agents if isinstance(a, RepoMicroagent)]
-
- assert len(knowledge_agents) == 0
- assert len(repo_agents) == 1
-
- agent = repo_agents[0]
- assert agent.name == 'repo'
-
- finally:
- _close_test_runtime(runtime)
-
-
-def test_task_microagent_creation():
- """Test that a TaskMicroagent is created correctly."""
- content = """---
-name: test_task
-version: 1.0.0
-author: openhands
-agent: CodeActAgent
-triggers:
-- /test_task
-inputs:
- - name: TEST_VAR
- description: "Test variable"
----
-
-This is a test task microagent with a variable: ${test_var}.
-"""
-
- with tempfile.NamedTemporaryFile(suffix='.md') as f:
- f.write(content.encode())
- f.flush()
-
- agent = BaseMicroagent.load(f.name)
-
- assert isinstance(agent, TaskMicroagent)
- assert agent.type == MicroagentType.TASK
- assert agent.name == 'test_task'
- assert '/test_task' in agent.triggers
- assert "If the user didn't provide any of these variables" in agent.content
-
-
-def test_task_microagent_variable_extraction():
- """Test that variables are correctly extracted from the content."""
- content = """---
-name: test_task
-version: 1.0.0
-author: openhands
-agent: CodeActAgent
-triggers:
-- /test_task
-inputs:
- - name: var1
- description: "Variable 1"
----
-
-This is a test with variables: ${var1}, ${var2}, and ${var3}.
-"""
-
- with tempfile.NamedTemporaryFile(suffix='.md') as f:
- f.write(content.encode())
- f.flush()
-
- agent = BaseMicroagent.load(f.name)
-
- assert isinstance(agent, TaskMicroagent)
- variables = agent.extract_variables(agent.content)
- assert set(variables) == {'var1', 'var2', 'var3'}
- assert agent.requires_user_input()
-
-
-def test_knowledge_microagent_no_prompt():
- """Test that a regular KnowledgeMicroagent doesn't get the prompt."""
- content = """---
-name: test_knowledge
-version: 1.0.0
-author: openhands
-agent: CodeActAgent
-triggers:
-- test_knowledge
----
-
-This is a test knowledge microagent.
-"""
-
- with tempfile.NamedTemporaryFile(suffix='.md') as f:
- f.write(content.encode())
- f.flush()
-
- agent = BaseMicroagent.load(f.name)
-
- assert isinstance(agent, KnowledgeMicroagent)
- assert agent.type == MicroagentType.KNOWLEDGE
- assert "If the user didn't provide any of these variables" not in agent.content
-
-
-def test_task_microagent_trigger_addition():
- """Test that a trigger is added if not present."""
- content = """---
-name: test_task
-version: 1.0.0
-author: openhands
-agent: CodeActAgent
-inputs:
- - name: TEST_VAR
- description: "Test variable"
----
-
-This is a test task microagent.
-"""
-
- with tempfile.NamedTemporaryFile(suffix='.md') as f:
- f.write(content.encode())
- f.flush()
-
- agent = BaseMicroagent.load(f.name)
-
- assert isinstance(agent, TaskMicroagent)
- assert '/test_task' in agent.triggers
-
-
-def test_task_microagent_no_duplicate_trigger():
- """Test that a trigger is not duplicated if already present."""
- content = """---
-name: test_task
-version: 1.0.0
-author: openhands
-agent: CodeActAgent
-triggers:
-- /test_task
-- another_trigger
-inputs:
- - name: TEST_VAR
- description: "Test variable"
----
-
-This is a test task microagent.
-"""
-
- with tempfile.NamedTemporaryFile(suffix='.md') as f:
- f.write(content.encode())
- f.flush()
-
- agent = BaseMicroagent.load(f.name)
-
- assert isinstance(agent, TaskMicroagent)
- assert agent.triggers.count('/test_task') == 1 # No duplicates
- assert len(agent.triggers) == 2
- assert 'another_trigger' in agent.triggers
- assert '/test_task' in agent.triggers
-
-
-def test_task_microagent_match_trigger():
- """Test that a task microagent matches its trigger correctly."""
- content = """---
-name: test_task
-version: 1.0.0
-author: openhands
-agent: CodeActAgent
-triggers:
-- /test_task
-inputs:
- - name: TEST_VAR
- description: "Test variable"
----
-
-This is a test task microagent.
-"""
-
- with tempfile.NamedTemporaryFile(suffix='.md') as f:
- f.write(content.encode())
- f.flush()
-
- agent = BaseMicroagent.load(f.name)
-
- assert isinstance(agent, TaskMicroagent)
- assert agent.match_trigger('/test_task') == '/test_task'
- assert agent.match_trigger(' /test_task ') == '/test_task'
- assert agent.match_trigger('This contains /test_task') == '/test_task'
- assert agent.match_trigger('/other_task') is None
-
-
[email protected](reason='2025-10-13 : This test is flaky')
-def test_default_tools_microagent_exists():
- """Test that the default-tools microagent exists in the global microagents directory."""
- # Get the path to the global microagents directory
- import openhands
-
- project_root = os.path.dirname(openhands.__file__)
- parent_dir = os.path.dirname(project_root)
- microagents_dir = os.path.join(parent_dir, 'microagents')
-
- # Check that the default-tools.md file exists
- default_tools_path = os.path.join(microagents_dir, 'default-tools.md')
- assert os.path.exists(default_tools_path), (
- f'default-tools.md not found at {default_tools_path}'
- )
-
- # Read the file and check its content
- with open(default_tools_path, 'r') as f:
- content = f.read()
-
- # Verify it's a repo microagent (always activated)
- assert 'type: repo' in content, 'default-tools.md should be a repo microagent'
-
- # Verify it has the fetch tool configured
- assert 'name: "fetch"' in content, 'default-tools.md should have a fetch tool'
- assert 'command: "uvx"' in content, 'default-tools.md should use uvx command'
- assert 'args: ["mcp-server-fetch"]' in content, (
- 'default-tools.md should use mcp-server-fetch'
- )
-
-
-async def test_add_mcp_tools_from_microagents():
- """Test that add_mcp_tools_to_agent adds tools from microagents."""
- # Import ActionExecutionClient for mocking
-
- from openhands.runtime.impl.action_execution.action_execution_client import (
- ActionExecutionClient,
- )
-
- # Create mock objects
- mock_agent = MagicMock()
- mock_runtime = MagicMock(spec=ActionExecutionClient)
- mock_memory = MagicMock()
-
- # Configure the mock memory to return a microagent MCP config
- mock_stdio_server = StdioMCPServer(
- name='test-tool', command='test-command', args=['test-arg1', 'test-arg2']
- )
- mock_microagent_mcp_config = MCPConfig(stdio_servers=[mock_stdio_server])
- mock_memory.get_microagent_mcp_tools.return_value = [mock_microagent_mcp_config]
-
- # Configure the mock runtime
- mock_runtime.runtime_initialized = True
- mock_runtime.get_mcp_config.return_value = mock_microagent_mcp_config
-
- # Mock the fetch_mcp_tools_from_config function to return a mock tool
- mock_tool = {
- 'type': 'function',
- 'function': {
- 'name': 'test-tool',
- 'description': 'Test tool description',
- 'parameters': {},
- },
- }
-
- with patch(
- 'openhands.mcp.utils.fetch_mcp_tools_from_config',
- new=AsyncMock(return_value=[mock_tool]),
- ):
- # Call the function with the OpenHandsConfig instead of MCPConfig
- await add_mcp_tools_to_agent(mock_agent, mock_runtime, mock_memory)
-
- # Verify that the memory's get_microagent_mcp_tools was called
- mock_memory.get_microagent_mcp_tools.assert_called_once()
-
- # Verify that the runtime's get_mcp_config was called with the extra stdio servers
- mock_runtime.get_mcp_config.assert_called_once()
- args, kwargs = mock_runtime.get_mcp_config.call_args
- assert len(args) == 1
- assert len(args[0]) == 1
- assert args[0][0].name == 'test-tool'
-
- # Verify that the agent's set_mcp_tools was called with the mock tool
- mock_agent.set_mcp_tools.assert_called_once_with([mock_tool])
diff --git a/tests/unit/integrations/bitbucket/test_bitbucket.py b/tests/unit/integrations/bitbucket/test_bitbucket.py
index 5c3f383495..47391c6925 100644
--- a/tests/unit/integrations/bitbucket/test_bitbucket.py
+++ b/tests/unit/integrations/bitbucket/test_bitbucket.py
@@ -628,9 +628,8 @@ async def test_get_user_handles_user_emails_api_failure():
# Setup.py Bitbucket Token Tests
@patch('openhands.core.setup.call_async_from_sync')
-@patch('openhands.core.setup.EventStream')
def test_initialize_repository_for_runtime_with_bitbucket_token(
- mock_event_stream, mock_call_async_from_sync
+ mock_call_async_from_sync,
):
"""Test that initialize_repository_for_runtime properly handles BITBUCKET_TOKEN."""
from openhands.core.setup import initialize_repository_for_runtime
@@ -676,9 +675,8 @@ def test_initialize_repository_for_runtime_with_bitbucket_token(
@patch('openhands.core.setup.call_async_from_sync')
-@patch('openhands.core.setup.EventStream')
def test_initialize_repository_for_runtime_with_multiple_tokens(
- mock_event_stream, mock_call_async_from_sync
+ mock_call_async_from_sync,
):
"""Test that initialize_repository_for_runtime handles multiple provider tokens including Bitbucket."""
from openhands.core.setup import initialize_repository_for_runtime
@@ -738,9 +736,8 @@ def test_initialize_repository_for_runtime_with_multiple_tokens(
@patch('openhands.core.setup.call_async_from_sync')
-@patch('openhands.core.setup.EventStream')
def test_initialize_repository_for_runtime_without_bitbucket_token(
- mock_event_stream, mock_call_async_from_sync
+ mock_call_async_from_sync,
):
"""Test that initialize_repository_for_runtime works without BITBUCKET_TOKEN."""
from openhands.core.setup import initialize_repository_for_runtime