Skip to content

πŸ™Œ OpenHands: AI-Driven Development

APP-1359 Removed V0 microagent Package (#14053)

Tim O'Farrell18365e0323d9
diff --git a/frontend/src/api/open-hands.types.ts b/frontend/src/api/open-hands.types.ts
index f68b80b5bd..89c3bb889a 100644
--- a/frontend/src/api/open-hands.types.ts
+++ b/frontend/src/api/open-hands.types.ts
@@ -131,13 +131,6 @@ export interface IOption<T> {
value: T;
}
-export interface MicroagentContentResponse {
- content: string;
- path: string;
- git_provider: Provider;
- triggers: string[];
-}
-
export type GetFilesResponse = string[];
export interface GetFileResponse {
diff --git a/openhands/integrations/azure_devops/service/features.py b/openhands/integrations/azure_devops/service/features.py
index 9f74f21a3a..544c2a5c51 100644
--- a/openhands/integrations/azure_devops/service/features.py
+++ b/openhands/integrations/azure_devops/service/features.py
@@ -1,9 +1,7 @@
"""Feature operations for Azure DevOps integration (microagents, suggested tasks, user)."""
-from openhands.core.logger import openhands_logger as logger
from openhands.integrations.azure_devops.service.base import AzureDevOpsMixinBase
from openhands.integrations.service_types import (
- MicroagentContentResponse,
ProviderType,
RequestMethod,
SuggestedTask,
@@ -139,85 +137,3 @@ class AzureDevOpsFeaturesMixin(AzureDevOpsMixinBase):
continue
return tasks
-
- async def _get_cursorrules_url(self, repository: str) -> str:
- """Get the URL for checking .cursorrules file in Azure DevOps."""
- org, project, repo = self._parse_repository(repository)
- # URL-encode components to handle spaces and special characters
- org_enc = self._encode_url_component(org)
- project_enc = self._encode_url_component(project)
- repo_enc = self._encode_url_component(repo)
- return f'{self.base_url}/{org_enc}/{project_enc}/_apis/git/repositories/{repo_enc}/items?path=/.cursorrules&api-version=7.1'
-
- async def _get_microagents_directory_url(
- self, repository: str, microagents_path: str
- ) -> str:
- """Get the URL for checking microagents directory in Azure DevOps.
-
- Note: For org-level microagents (e.g., 'org/.openhands'), Azure DevOps doesn't support
- this concept, so we raise ValueError to let the caller fall back to other providers.
- """
- parts = repository.split('/')
- if len(parts) < 3:
- # Azure DevOps doesn't support org-level configs, only full repo paths
- raise ValueError(
- f'Invalid repository format: {repository}. Expected format: organization/project/repo'
- )
- org, project, repo = parts[0], parts[1], parts[2]
- # URL-encode components to handle spaces and special characters
- org_enc = self._encode_url_component(org)
- project_enc = self._encode_url_component(project)
- repo_enc = self._encode_url_component(repo)
- return f'{self.base_url}/{org_enc}/{project_enc}/_apis/git/repositories/{repo_enc}/items?path=/{microagents_path}&recursionLevel=OneLevel&api-version=7.1'
-
- def _get_microagents_directory_params(self, microagents_path: str) -> dict | None:
- """Get parameters for the microagents directory request. Return None if no parameters needed."""
- return None
-
- def _is_valid_microagent_file(self, item: dict) -> bool:
- """Check if an item represents a valid microagent file in Azure DevOps."""
- return (
- not item.get('isFolder', False)
- and item.get('path', '').endswith('.md')
- and not item.get('path', '').endswith('README.md')
- )
-
- def _get_file_name_from_item(self, item: dict) -> str:
- """Extract file name from directory item in Azure DevOps."""
- path = item.get('path', '')
- return path.split('/')[-1] if path else ''
-
- def _get_file_path_from_item(self, item: dict, microagents_path: str) -> str:
- """Extract file path from directory item in Azure DevOps."""
- return item.get('path', '').lstrip('/')
-
- async def get_microagent_content(
- self, repository: str, file_path: str
- ) -> MicroagentContentResponse:
- """Get content of a specific microagent file.
-
- Args:
- repository: Repository name in Azure DevOps format 'org/project/repo'
- file_path: Path to the microagent file
-
- Returns:
- MicroagentContentResponse with parsed content and triggers
- """
- org, project, repo = self._parse_repository(repository)
- # URL-encode components to handle spaces and special characters
- org_enc = self._encode_url_component(org)
- project_enc = self._encode_url_component(project)
- repo_enc = self._encode_url_component(repo)
- url = f'{self.base_url}/{org_enc}/{project_enc}/_apis/git/repositories/{repo_enc}/items?path={file_path}&api-version=7.1'
-
- try:
- response, _ = await self._make_request(url)
- content = (
- response if isinstance(response, str) else response.get('content', '')
- )
-
- # Parse the content using the base class method
- return self._parse_microagent_content(content, file_path)
- except Exception as e:
- logger.warning(f'Failed to fetch microagent content from {file_path}: {e}')
- raise
diff --git a/openhands/integrations/bitbucket/bitbucket_service.py b/openhands/integrations/bitbucket/bitbucket_service.py
index 8d7eb48e81..f36beb270a 100644
--- a/openhands/integrations/bitbucket/bitbucket_service.py
+++ b/openhands/integrations/bitbucket/bitbucket_service.py
@@ -4,7 +4,6 @@ from pydantic import SecretStr
from openhands.integrations.bitbucket.service import (
BitBucketBranchesMixin,
- BitBucketFeaturesMixin,
BitBucketPRsMixin,
BitBucketReposMixin,
)
@@ -20,7 +19,6 @@ class BitBucketService(
BitBucketReposMixin,
BitBucketBranchesMixin,
BitBucketPRsMixin,
- BitBucketFeaturesMixin,
GitService,
InstallationsService,
):
diff --git a/openhands/integrations/bitbucket/service/__init__.py b/openhands/integrations/bitbucket/service/__init__.py
index 836fb91da9..d8911073ec 100644
--- a/openhands/integrations/bitbucket/service/__init__.py
+++ b/openhands/integrations/bitbucket/service/__init__.py
@@ -1,13 +1,11 @@
from .base import BitBucketMixinBase
from .branches import BitBucketBranchesMixin
-from .features import BitBucketFeaturesMixin
from .prs import BitBucketPRsMixin
from .repos import BitBucketReposMixin
__all__ = [
'BitBucketMixinBase',
'BitBucketBranchesMixin',
- 'BitBucketFeaturesMixin',
'BitBucketPRsMixin',
'BitBucketReposMixin',
]
diff --git a/openhands/integrations/bitbucket/service/base.py b/openhands/integrations/bitbucket/service/base.py
index f7875b306a..81eb0a98ad 100644
--- a/openhands/integrations/bitbucket/service/base.py
+++ b/openhands/integrations/bitbucket/service/base.py
@@ -12,7 +12,6 @@ from openhands.integrations.service_types import (
ProviderType,
Repository,
RequestMethod,
- ResourceNotFoundError,
User,
)
from openhands.utils.http_session import httpx_verify_option
@@ -236,47 +235,3 @@ class BitBucketMixinBase(BaseGitService, HTTPClient):
url = f'{self.BASE_URL}/repositories/{repository}'
data, _ = await self._make_request(url)
return self._parse_repository(data)
-
- async def _get_cursorrules_url(self, repository: str) -> str:
- """Get the URL for checking .cursorrules file."""
- # Get repository details to get the main branch
- repo_details = await self.get_repository_details_from_repo_name(repository)
- if not repo_details.main_branch:
- raise ResourceNotFoundError(
- f'Main branch not found for repository {repository}. '
- f'This repository may be empty or have no default branch configured.'
- )
- return f'{self.BASE_URL}/repositories/{repository}/src/{repo_details.main_branch}/.cursorrules'
-
- async def _get_microagents_directory_url(
- self, repository: str, microagents_path: str
- ) -> str:
- """Get the URL for checking microagents directory."""
- # Get repository details to get the main branch
- repo_details = await self.get_repository_details_from_repo_name(repository)
- if not repo_details.main_branch:
- raise ResourceNotFoundError(
- f'Main branch not found for repository {repository}. '
- f'This repository may be empty or have no default branch configured.'
- )
- return f'{self.BASE_URL}/repositories/{repository}/src/{repo_details.main_branch}/{microagents_path}'
-
- def _get_microagents_directory_params(self, microagents_path: str) -> dict | None:
- """Get parameters for the microagents directory request. Return None if no parameters needed."""
- return None
-
- def _is_valid_microagent_file(self, item: dict) -> bool:
- """Check if an item represents a valid microagent file."""
- return (
- item['type'] == 'commit_file'
- and item['path'].endswith('.md')
- and not item['path'].endswith('README.md')
- )
-
- def _get_file_name_from_item(self, item: dict) -> str:
- """Extract file name from directory item."""
- return item['path'].split('/')[-1]
-
- def _get_file_path_from_item(self, item: dict, microagents_path: str) -> str:
- """Extract file path from directory item."""
- return item['path']
diff --git a/openhands/integrations/bitbucket/service/features.py b/openhands/integrations/bitbucket/service/features.py
deleted file mode 100644
index 8451ad9603..0000000000
--- a/openhands/integrations/bitbucket/service/features.py
+++ /dev/null
@@ -1,45 +0,0 @@
-from openhands.core.logger import openhands_logger as logger
-from openhands.integrations.bitbucket.service.base import BitBucketMixinBase
-from openhands.integrations.service_types import ResourceNotFoundError
-from openhands.microagent.types import MicroagentContentResponse
-
-
-class BitBucketFeaturesMixin(BitBucketMixinBase):
- """
- Mixin for BitBucket feature operations (microagents, cursor rules, etc.)
- """
-
- async def get_microagent_content(
- self, repository: str, file_path: str
- ) -> MicroagentContentResponse:
- """Fetch individual file content from Bitbucket repository.
-
- Args:
- repository: Repository name in format 'workspace/repo_slug'
- file_path: Path to the file within the repository
-
- Returns:
- MicroagentContentResponse with parsed content and triggers
-
- Raises:
- RuntimeError: If file cannot be fetched or doesn't exist
- """
- # Step 1: Get repository details using existing method
- repo_details = await self.get_repository_details_from_repo_name(repository)
-
- if not repo_details.main_branch:
- logger.warning(
- f'No main branch found in repository info for {repository}. '
- f'Repository response: mainbranch field missing'
- )
- raise ResourceNotFoundError(
- f'Main branch not found for repository {repository}. '
- f'This repository may be empty or have no default branch configured.'
- )
-
- # Step 2: Get file content using the main branch
- file_url = f'{self.BASE_URL}/repositories/{repository}/src/{repo_details.main_branch}/{file_path}'
- response, _ = await self._make_request(file_url)
-
- # Parse the content to extract triggers from frontmatter
- return self._parse_microagent_content(response, file_path)
diff --git a/openhands/integrations/bitbucket_data_center/bitbucket_dc_service.py b/openhands/integrations/bitbucket_data_center/bitbucket_dc_service.py
index 890540777d..d8d30b3389 100644
--- a/openhands/integrations/bitbucket_data_center/bitbucket_dc_service.py
+++ b/openhands/integrations/bitbucket_data_center/bitbucket_dc_service.py
@@ -4,7 +4,6 @@ from pydantic import SecretStr
from openhands.integrations.bitbucket_data_center.service import (
BitbucketDCBranchesMixin,
- BitbucketDCFeaturesMixin,
BitbucketDCPRsMixin,
BitbucketDCReposMixin,
BitbucketDCResolverMixin,
@@ -20,7 +19,6 @@ from openhands.utils.import_utils import get_impl
class BitbucketDCService(
BitbucketDCResolverMixin,
BitbucketDCBranchesMixin,
- BitbucketDCFeaturesMixin,
BitbucketDCPRsMixin,
BitbucketDCReposMixin,
GitService,
diff --git a/openhands/integrations/bitbucket_data_center/service/__init__.py b/openhands/integrations/bitbucket_data_center/service/__init__.py
index 63c4e54ae9..793356c1a7 100644
--- a/openhands/integrations/bitbucket_data_center/service/__init__.py
+++ b/openhands/integrations/bitbucket_data_center/service/__init__.py
@@ -1,6 +1,5 @@
from .base import BitbucketDCMixinBase
from .branches import BitbucketDCBranchesMixin
-from .features import BitbucketDCFeaturesMixin
from .prs import BitbucketDCPRsMixin
from .repos import BitbucketDCReposMixin
from .resolver import BitbucketDCResolverMixin
@@ -8,7 +7,6 @@ from .resolver import BitbucketDCResolverMixin
__all__ = [
'BitbucketDCMixinBase',
'BitbucketDCBranchesMixin',
- 'BitbucketDCFeaturesMixin',
'BitbucketDCPRsMixin',
'BitbucketDCReposMixin',
'BitbucketDCResolverMixin',
diff --git a/openhands/integrations/bitbucket_data_center/service/base.py b/openhands/integrations/bitbucket_data_center/service/base.py
index 849b2df076..b90201b37b 100644
--- a/openhands/integrations/bitbucket_data_center/service/base.py
+++ b/openhands/integrations/bitbucket_data_center/service/base.py
@@ -13,7 +13,6 @@ from openhands.integrations.service_types import (
ProviderType,
Repository,
RequestMethod,
- ResourceNotFoundError,
User,
)
from openhands.utils.http_session import httpx_verify_option
@@ -282,58 +281,3 @@ class BitbucketDCMixinBase(BaseGitService, HTTPClient):
url = self._repo_api_base(owner, repo)
data, _ = await self._make_request(url)
return await self._parse_repository(data, fetch_default_branch=True)
-
- async def _get_cursorrules_url(self, repository: str) -> str:
- """Get the URL for checking .cursorrules file."""
- # Get repository details to get the main branch
- repo_details = await self.get_repository_details_from_repo_name(repository)
- if not repo_details.main_branch:
- raise ResourceNotFoundError(
- f'Main branch not found for repository {repository}. '
- f'This repository may be empty or have no default branch configured.'
- )
- owner, repo = self._extract_owner_and_repo(repository)
- return (
- f'{self.BASE_URL}/projects/{owner}/repos/{repo}/browse/.cursorrules'
- f'?at=refs/heads/{repo_details.main_branch}'
- )
-
- async def _get_microagents_directory_url(
- self, repository: str, microagents_path: str
- ) -> str:
- """Get the URL for checking microagents directory."""
- # Get repository details to get the main branch
- repo_details = await self.get_repository_details_from_repo_name(repository)
- if not repo_details.main_branch:
- raise ResourceNotFoundError(
- f'Main branch not found for repository {repository}. '
- f'This repository may be empty or have no default branch configured.'
- )
-
- owner, repo = self._extract_owner_and_repo(repository)
- return (
- f'{self.BASE_URL}/projects/{owner}/repos/{repo}/browse/{microagents_path}'
- f'?at=refs/heads/{repo_details.main_branch}'
- )
-
- def _get_microagents_directory_params(self, microagents_path: str) -> dict | None:
- """Get parameters for the microagents directory request. Return None if no parameters needed."""
- return None
-
- def _is_valid_microagent_file(self, item: dict) -> bool:
- """Check if an item represents a valid microagent file."""
- file_name = item.get('path', {}).get('name', '')
- return (
- item.get('type') == 'FILE'
- and file_name.endswith('.md')
- and file_name != 'README.md'
- )
-
- def _get_file_name_from_item(self, item: dict) -> str:
- """Extract file name from directory item."""
- return item.get('path', {}).get('name', '')
-
- def _get_file_path_from_item(self, item: dict, microagents_path: str) -> str:
- """Extract file path from directory item."""
- file_name = self._get_file_name_from_item(item)
- return f'{microagents_path}/{file_name}'
diff --git a/openhands/integrations/bitbucket_data_center/service/features.py b/openhands/integrations/bitbucket_data_center/service/features.py
deleted file mode 100644
index daa48f8b2f..0000000000
--- a/openhands/integrations/bitbucket_data_center/service/features.py
+++ /dev/null
@@ -1,96 +0,0 @@
-from openhands.core.logger import openhands_logger as logger
-from openhands.integrations.bitbucket_data_center.service.base import (
- BitbucketDCMixinBase,
-)
-from openhands.integrations.service_types import ResourceNotFoundError
-from openhands.microagent.types import MicroagentContentResponse, MicroagentResponse
-
-
-class BitbucketDCFeaturesMixin(BitbucketDCMixinBase):
- """
- Mixin for BitBucket data center feature operations (microagents, cursor rules, etc.)
- """
-
- async def get_microagent_content(
- self, repository: str, file_path: str
- ) -> MicroagentContentResponse:
- """Fetch individual file content from Bitbucket data center repository.
-
- Args:
- repository: Repository name in format 'project/repo_slug'
- file_path: Path to the file within the repository
-
- Returns:
- MicroagentContentResponse with parsed content and triggers
-
- Raises:
- RuntimeError: If file cannot be fetched or doesn't exist
- """
- # Step 1: Get repository details using existing method
- repo_details = await self.get_repository_details_from_repo_name(repository)
-
- if not repo_details.main_branch:
- logger.warning(
- f'No main branch found in repository info for {repository}. '
- f'Repository response: mainbranch field missing'
- )
- raise ResourceNotFoundError(
- f'Main branch not found for repository {repository}. '
- f'This repository may be empty or have no default branch configured.'
- )
-
- # Step 2: Get file content using the main branch
- owner, repo = self._extract_owner_and_repo(repository)
- repo_base = self._repo_api_base(owner, repo)
-
- file_url = f'{repo_base}/browse/{file_path}'
- params = {'at': f'refs/heads/{repo_details.main_branch}'}
- response, _ = await self._make_request(file_url, params=params)
- if isinstance(response, dict):
- lines = response.get('lines')
- if isinstance(lines, list):
- content = '\n'.join(
- line.get('text', '') for line in lines if isinstance(line, dict)
- )
- else:
- content = response.get('content', '')
- else:
- content = str(response)
-
- # Parse the content to extract triggers from frontmatter
- return self._parse_microagent_content(content, file_path)
-
- async def _process_microagents_directory(
- self, repository: str, microagents_path: str
- ) -> list[MicroagentResponse]:
- microagents = []
- try:
- directory_url = await self._get_microagents_directory_url(
- repository, microagents_path
- )
- directory_params = self._get_microagents_directory_params(microagents_path)
- response, _ = await self._make_request(directory_url, directory_params)
-
- # Bitbucket DC browse endpoint nests items under response['children']['values']
- items = response.get('children', {}).get('values', [])
-
- for item in items:
- if self._is_valid_microagent_file(item):
- try:
- file_name = self._get_file_name_from_item(item)
- file_path = self._get_file_path_from_item(
- item, microagents_path
- )
- microagents.append(
- self._create_microagent_response(file_name, file_path)
- )
- except Exception as e:
- logger.warning(f'Error processing microagent {item}: {str(e)}')
- except ResourceNotFoundError:
- logger.info(
- f'No microagents directory found in {repository} at {microagents_path}'
- )
- except Exception as e:
- logger.warning(f'Error fetching microagents directory: {str(e)}')
-
- return microagents
diff --git a/openhands/integrations/forgejo/service/features.py b/openhands/integrations/forgejo/service/features.py
index 986fa363c0..d11496a6e4 100644
--- a/openhands/integrations/forgejo/service/features.py
+++ b/openhands/integrations/forgejo/service/features.py
@@ -1,123 +1,12 @@
from __future__ import annotations
-import base64
-from typing import Any
-
-from openhands.core.logger import openhands_logger as logger
from openhands.integrations.forgejo.service.base import ForgejoMixinBase
-from openhands.integrations.service_types import (
- MicroagentContentResponse,
- MicroagentResponse,
- ProviderType,
- ResourceNotFoundError,
- SuggestedTask,
-)
+from openhands.integrations.service_types import SuggestedTask
class ForgejoFeaturesMixin(ForgejoMixinBase):
"""Microagent and feature helpers for Forgejo."""
- async def _get_cursorrules_url(self, repository: str) -> str:
- owner, repo = self._split_repo(repository)
- return self._build_repo_api_url(owner, repo, 'contents', '.cursorrules')
-
- async def _get_microagents_directory_url(
- self, repository: str, microagents_path: str
- ) -> str:
- owner, repo = self._split_repo(repository)
- normalized_path = microagents_path.strip('/')
- return self._build_repo_api_url(owner, repo, 'contents', normalized_path)
-
- def _get_microagents_directory_params(self, microagents_path: str) -> dict | None:
- return None
-
- def _is_valid_microagent_file(self, item: dict[str, Any] | None) -> bool:
- if not isinstance(item, dict):
- return False
- if item.get('type') != 'file':
- return False
- name = item.get('name', '')
- return isinstance(name, str) and (
- name.endswith('.md') or name.endswith('.cursorrules')
- )
-
- def _get_file_name_from_item(self, item: dict[str, Any] | None) -> str:
- if not isinstance(item, dict):
- return ''
- name = item.get('name')
- return name if isinstance(name, str) else ''
-
- def _get_file_path_from_item(
- self, item: dict[str, Any] | None, microagents_path: str
- ) -> str:
- file_name = self._get_file_name_from_item(item)
- if not microagents_path:
- return file_name
- return f'{microagents_path.strip("/")}/{file_name}'
-
- async def get_microagents(self, repository: str) -> list[MicroagentResponse]: # type: ignore[override]
- microagents_path = self._determine_microagents_path(repository)
- microagents: list[MicroagentResponse] = []
-
- try:
- directory_url = await self._get_microagents_directory_url(
- repository, microagents_path
- )
- items, _ = await self._make_request(directory_url)
- except ResourceNotFoundError:
- items = []
- except Exception as exc:
- # Fail gracefully if the directory cannot be inspected
- self._log_microagent_warning(repository, str(exc))
- items = []
-
- if isinstance(items, list):
- for item in items:
- if self._is_valid_microagent_file(item):
- file_name = self._get_file_name_from_item(item)
- file_path = self._get_file_path_from_item(item, microagents_path)
- microagents.append(
- self._create_microagent_response(file_name, file_path)
- )
-
- cursorrules = await self._check_cursorrules_file(repository)
- if cursorrules:
- microagents.append(cursorrules)
-
- return microagents
-
- async def get_microagent_content(
- self, repository: str, file_path: str
- ) -> MicroagentContentResponse: # type: ignore[override]
- owner, repo = self._split_repo(repository)
- normalized_path = file_path.lstrip('/')
- url = self._build_repo_api_url(owner, repo, 'contents', normalized_path)
-
- response, _ = await self._make_request(url)
- content = response.get('content') or ''
- encoding = (response.get('encoding') or 'base64').lower()
-
- if encoding == 'base64':
- try:
- decoded = base64.b64decode(content).decode('utf-8')
- except Exception:
- decoded = ''
- else:
- decoded = content
-
- try:
- return self._parse_microagent_content(decoded, file_path)
- except Exception:
- return MicroagentContentResponse(
- content=decoded,
- path=file_path,
- triggers=[],
- git_provider=ProviderType.FORGEJO.value,
- )
-
async def get_suggested_tasks(self) -> list[SuggestedTask]: # type: ignore[override]
# Suggested tasks are not yet implemented for Forgejo.
return []
-
- def _log_microagent_warning(self, repository: str, message: str) -> None:
- logger.debug(f'Forgejo microagent scan warning for {repository}: {message}')
diff --git a/openhands/integrations/github/service/features.py b/openhands/integrations/github/service/features.py
index e8ff9b9e41..9cbcb812f7 100644
--- a/openhands/integrations/github/service/features.py
+++ b/openhands/integrations/github/service/features.py
@@ -1,5 +1,3 @@
-import base64
-
from openhands.core.logger import openhands_logger as logger
from openhands.integrations.github.queries import (
suggested_task_issue_graphql_query,
@@ -7,7 +5,6 @@ from openhands.integrations.github.queries import (
)
from openhands.integrations.github.service.base import GitHubMixinBase
from openhands.integrations.service_types import (
- MicroagentContentResponse,
ProviderType,
SuggestedTask,
TaskType,
@@ -118,60 +115,3 @@ class GitHubFeaturesMixin(GitHubMixinBase):
)
return tasks
-
- """
- Methods specifically for microagent management page
- """
-
- async def _get_cursorrules_url(self, repository: str) -> str:
- """Get the URL for checking .cursorrules file."""
- return f'{self.BASE_URL}/repos/{repository}/contents/.cursorrules'
-
- async def _get_microagents_directory_url(
- self, repository: str, microagents_path: str
- ) -> str:
- """Get the URL for checking microagents directory."""
- return f'{self.BASE_URL}/repos/{repository}/contents/{microagents_path}'
-
- def _is_valid_microagent_file(self, item: dict) -> bool:
- """Check if an item represents a valid microagent file."""
- return (
- item['type'] == 'file'
- and item['name'].endswith('.md')
- and item['name'] != 'README.md'
- )
-
- def _get_file_name_from_item(self, item: dict) -> str:
- """Extract file name from directory item."""
- return item['name']
-
- def _get_file_path_from_item(self, item: dict, microagents_path: str) -> str:
- """Extract file path from directory item."""
- return f'{microagents_path}/{item["name"]}'
-
- def _get_microagents_directory_params(self, microagents_path: str) -> dict | None:
- """Get parameters for the microagents directory request. Return None if no parameters needed."""
- return None
-
- async def get_microagent_content(
- self, repository: str, file_path: str
- ) -> MicroagentContentResponse:
- """Fetch individual file content from GitHub repository.
-
- Args:
- repository: Repository name in format 'owner/repo'
- file_path: Path to the file within the repository
-
- Returns:
- MicroagentContentResponse with parsed content and triggers
-
- Raises:
- RuntimeError: If file cannot be fetched or doesn't exist
- """
- file_url = f'{self.BASE_URL}/repos/{repository}/contents/{file_path}'
-
- file_data, _ = await self._make_request(file_url)
- file_content = base64.b64decode(file_data['content']).decode('utf-8')
-
- # Parse the content to extract triggers from frontmatter
- return self._parse_microagent_content(file_content, file_path)
diff --git a/openhands/integrations/gitlab/service/features.py b/openhands/integrations/gitlab/service/features.py
index 6b1b9e05e9..142316f1b5 100644
--- a/openhands/integrations/gitlab/service/features.py
+++ b/openhands/integrations/gitlab/service/features.py
@@ -1,6 +1,5 @@
from openhands.integrations.gitlab.service.base import GitLabMixinBase
from openhands.integrations.service_types import (
- MicroagentContentResponse,
ProviderType,
RequestMethod,
SuggestedTask,
@@ -13,40 +12,6 @@ class GitLabFeaturesMixin(GitLabMixinBase):
Methods used for custom features in UI driven via GitLab integration
"""
- async def _get_cursorrules_url(self, repository: str) -> str:
- """Get the URL for checking .cursorrules file."""
- project_id = self._extract_project_id(repository)
- return (
- f'{self.BASE_URL}/projects/{project_id}/repository/files/.cursorrules/raw'
- )
-
- async def _get_microagents_directory_url(
- self, repository: str, microagents_path: str
- ) -> str:
- """Get the URL for checking microagents directory."""
- project_id = self._extract_project_id(repository)
- return f'{self.BASE_URL}/projects/{project_id}/repository/tree'
-
- def _get_microagents_directory_params(self, microagents_path: str) -> dict:
- """Get parameters for the microagents directory request."""
- return {'path': microagents_path, 'recursive': 'true'}
-
- def _is_valid_microagent_file(self, item: dict) -> bool:
- """Check if an item represents a valid microagent file."""
- return (
- item['type'] == 'blob'
- and item['name'].endswith('.md')
- and item['name'] != 'README.md'
- )
-
- def _get_file_name_from_item(self, item: dict) -> str:
- """Extract file name from directory item."""
- return item['name']
-
- def _get_file_path_from_item(self, item: dict, microagents_path: str) -> str:
- """Extract file path from directory item."""
- return item['path']
-
async def get_suggested_tasks(self) -> list[SuggestedTask]:
"""Get suggested tasks for the authenticated user across all repositories.
@@ -178,30 +143,3 @@ class GitLabFeaturesMixin(GitLabMixinBase):
return tasks
except Exception:
return []
-
- async def get_microagent_content(
- self, repository: str, file_path: str
- ) -> MicroagentContentResponse:
- """Fetch individual file content from GitLab repository.
-
- Args:
- repository: Repository name in format 'owner/repo' or 'domain/owner/repo'
- file_path: Path to the file within the repository
-
- Returns:
- MicroagentContentResponse with parsed content and triggers
-
- Raises:
- RuntimeError: If file cannot be fetched or doesn't exist
- """
- # Extract project_id from repository name
- project_id = self._extract_project_id(repository)
-
- encoded_file_path = file_path.replace('/', '%2F')
- base_url = f'{self.BASE_URL}/projects/{project_id}'
- file_url = f'{base_url}/repository/files/{encoded_file_path}/raw'
-
- response, _ = await self._make_request(file_url)
-
- # Parse the content to extract triggers from frontmatter
- return self._parse_microagent_content(response, file_path)
diff --git a/openhands/integrations/provider.py b/openhands/integrations/provider.py
index 7a8cc2db43..fdf95da3f6 100644
--- a/openhands/integrations/provider.py
+++ b/openhands/integrations/provider.py
@@ -33,17 +33,14 @@ from openhands.integrations.service_types import (
Branch,
GitService,
InstallationsService,
- MicroagentParseError,
PaginatedBranchesResponse,
ProviderTimeoutError,
ProviderType,
Repository,
- ResourceNotFoundError,
SuggestedTask,
TokenResponse,
User,
)
-from openhands.microagent.types import MicroagentContentResponse, MicroagentResponse
from openhands.server.types import AppMode
from openhands.utils.http_session import httpx_verify_option
@@ -599,104 +596,6 @@ class ProviderHandler:
total_count=0,
)
- async def get_microagents(self, repository: str) -> list[MicroagentResponse]:
- """Get microagents from a repository using the appropriate service.
-
- Args:
- repository: Repository name in the format 'owner/repo'
-
- Returns:
- List of microagents found in the repository
-
- Raises:
- AuthenticationError: If authentication fails
- """
- # Try all available providers in order
- errors = []
- for provider in self.provider_tokens:
- try:
- service = self.get_service(provider)
- result = await service.get_microagents(repository)
- # Only return early if we got a non-empty result
- if result:
- return result
- # If we got an empty array, continue checking other providers
- logger.debug(
- f'No microagents found on {provider} for {repository}, trying other providers'
- )
- except Exception as e:
- errors.append(f'{provider.value}: {str(e)}')
- logger.warning(
- f'Error fetching microagents from {provider} for {repository}: {e}'
- )
-
- # If all providers failed or returned empty results, return empty array
- if errors:
- logger.error(
- f'Failed to fetch microagents for {repository} with all available providers. Errors: {"; ".join(errors)}'
- )
- raise AuthenticationError(f'Unable to fetch microagents for {repository}')
-
- # All providers returned empty arrays
- return []
-
- async def get_microagent_content(
- self, repository: str, file_path: str
- ) -> MicroagentContentResponse:
- """Get content of a specific microagent file from a repository.
-
- Args:
- repository: Repository name in the format 'owner/repo'
- file_path: Path to the microagent file within the repository
-
- Returns:
- MicroagentContentResponse with parsed content and triggers
-
- Raises:
- AuthenticationError: If authentication fails
- """
- # Try all available providers in order
- errors = []
- for provider in self.provider_tokens:
- try:
- service = self.get_service(provider)
- result = await service.get_microagent_content(repository, file_path)
- # If we got content, return it immediately
- if result:
- return result
- # If we got empty content, continue checking other providers
- logger.debug(
- f'No content found on {provider} for {repository}/{file_path}, trying other providers'
- )
- except ResourceNotFoundError:
- logger.debug(
- f'File not found on {provider} for {repository}/{file_path}, trying other providers'
- )
- continue
- except MicroagentParseError as e:
- # Parsing errors are specific to the provider, add to errors list
- errors.append(f'{provider.value}: {str(e)}')
- logger.warning(
- f'Error parsing microagent content from {provider} for {repository}: {e}'
- )
- except Exception as e:
- # For other errors (auth, rate limit, etc.), add to errors list
- errors.append(f'{provider.value}: {str(e)}')
- logger.warning(
- f'Error fetching microagent content from {provider} for {repository}: {e}'
- )
-
- # If all providers failed or returned empty results, raise an error
- if errors:
- logger.error(
- f'Failed to fetch microagent content for {repository} with all available providers. Errors: {"; ".join(errors)}'
- )
-
- # All providers returned empty content or file not found
- raise AuthenticationError(
- f'Microagent file {file_path} not found in {repository}'
- )
-
async def get_authenticated_git_url(
self, repo_name: str, is_optional: bool = False
) -> str:
diff --git a/openhands/integrations/service_types.py b/openhands/integrations/service_types.py
index 110f0c687b..3306e5964d 100644
--- a/openhands/integrations/service_types.py
+++ b/openhands/integrations/service_types.py
@@ -1,15 +1,11 @@
from abc import ABC, abstractmethod
from datetime import datetime
from enum import Enum
-from pathlib import Path
from typing import Any, Protocol
from jinja2 import Environment, FileSystemLoader
from pydantic import BaseModel, SecretStr
-from openhands.core.logger import openhands_logger as logger
-from openhands.microagent.microagent import BaseMicroagent
-from openhands.microagent.types import MicroagentContentResponse, MicroagentResponse
from openhands.server.types import AppMode
@@ -33,7 +29,6 @@ class TaskType(str, Enum):
UNRESOLVED_COMMENTS = 'UNRESOLVED_COMMENTS'
OPEN_ISSUE = 'OPEN_ISSUE'
OPEN_PR = 'OPEN_PR'
- CREATE_MICROAGENT = 'CREATE_MICROAGENT'
class OwnerType(str, Enum):
@@ -201,12 +196,6 @@ class ResourceNotFoundError(ValueError):
pass
-class MicroagentParseError(ValueError):
- """Raised when there is an error parsing a microagent file."""
-
- pass
-
-
class RequestMethod(Enum):
POST = 'post'
GET = 'get'
@@ -226,216 +215,6 @@ class BaseGitService(ABC):
method: RequestMethod = RequestMethod.GET,
) -> tuple[Any, dict]: ...
- @abstractmethod
- async def _get_cursorrules_url(self, repository: str) -> str:
- """Get the URL for checking .cursorrules file."""
- ...
-
- @abstractmethod
- async def _get_microagents_directory_url(
- self, repository: str, microagents_path: str
- ) -> str:
- """Get the URL for checking microagents directory."""
- ...
-
- @abstractmethod
- def _get_microagents_directory_params(self, microagents_path: str) -> dict | None:
- """Get parameters for the microagents directory request. Return None if no parameters needed."""
- ...
-
- @abstractmethod
- def _is_valid_microagent_file(self, item: dict) -> bool:
- """Check if an item represents a valid microagent file."""
- ...
-
- @abstractmethod
- def _get_file_name_from_item(self, item: dict) -> str:
- """Extract file name from directory item."""
- ...
-
- @abstractmethod
- def _get_file_path_from_item(self, item: dict, microagents_path: str) -> str:
- """Extract file path from directory item."""
- ...
-
- def _determine_microagents_path(self, repository_name: str) -> str:
- """Determine the microagents directory path based on repository name."""
- actual_repo_name = repository_name.split('/')[-1]
-
- # Check for special repository names that use a different structure
- if actual_repo_name == '.openhands' or actual_repo_name == 'openhands-config':
- # For repository name ".openhands", scan "microagents" folder
- return 'microagents'
- else:
- # Default behavior: look for .openhands/microagents directory
- return '.openhands/microagents'
-
- def _create_microagent_response(
- self, file_name: str, path: str
- ) -> MicroagentResponse:
- """Create a microagent response from basic file information."""
- # Extract name without extension
- name = file_name.replace('.md', '').replace('.cursorrules', 'cursorrules')
-
- return MicroagentResponse(
- name=name,
- path=path,
- created_at=datetime.now(),
- )
-
- def _parse_microagent_content(
- self, content: str, file_path: str
- ) -> MicroagentContentResponse:
- """Parse microagent content and extract triggers using BaseMicroagent.load.
-
- Args:
- content: Raw microagent file content
- file_path: Path to the file (used for microagent loading)
-
- Returns:
- MicroagentContentResponse with parsed content and triggers
-
- Raises:
- MicroagentParseError: If the microagent file cannot be parsed
- """
- try:
- # Use BaseMicroagent.load to properly parse the content
- # Create a temporary path object for the file
- temp_path = Path(file_path)
-
- # Load the microagent using the existing infrastructure
- microagent = BaseMicroagent.load(path=temp_path, file_content=content)
-
- # Extract triggers from the microagent's metadata
- triggers = microagent.metadata.triggers
-
- # Return the MicroagentContentResponse
- return MicroagentContentResponse(
- content=microagent.content,
- path=file_path,
- triggers=triggers,
- git_provider=self.provider,
- )
-
- except Exception as e:
- logger.error(f'Error parsing microagent content for {file_path}: {str(e)}')
- raise MicroagentParseError(
- f'Failed to parse microagent file {file_path}: {str(e)}'
- )
-
- async def _fetch_cursorrules_content(self, repository: str) -> Any | None:
- """Fetch .cursorrules file content from the repository via API.
-
- Args:
- repository: Repository name in format specific to the provider
-
- Returns:
- Raw API response content if .cursorrules file exists, None otherwise
- """
- cursorrules_url = await self._get_cursorrules_url(repository)
- cursorrules_response, _ = await self._make_request(cursorrules_url)
- return cursorrules_response
-
- async def _check_cursorrules_file(
- self, repository: str
- ) -> MicroagentResponse | None:
- """Check for .cursorrules file in the repository and return microagent response if found.
-
- Args:
- repository: Repository name in format specific to the provider
-
- Returns:
- MicroagentResponse for .cursorrules file if found, None otherwise
- """
- try:
- cursorrules_content = await self._fetch_cursorrules_content(repository)
- if cursorrules_content:
- return self._create_microagent_response('.cursorrules', '.cursorrules')
- except ResourceNotFoundError:
- logger.debug(f'No .cursorrules file found in {repository}')
- except Exception as e:
- logger.warning(f'Error checking .cursorrules file in {repository}: {e}')
-
- return None
-
- async def _process_microagents_directory(
- self, repository: str, microagents_path: str
- ) -> list[MicroagentResponse]:
- """Process microagents directory and return list of microagent responses.
-
- Args:
- repository: Repository name in format specific to the provider
- microagents_path: Path to the microagents directory
-
- Returns:
- List of MicroagentResponse objects found in the directory
- """
- microagents = []
-
- try:
- directory_url = await self._get_microagents_directory_url(
- repository, microagents_path
- )
- directory_params = self._get_microagents_directory_params(microagents_path)
- response, _ = await self._make_request(directory_url, directory_params)
-
- # Handle different response structures
- items = response
- if isinstance(response, dict) and 'values' in response:
- # Bitbucket format
- items = response['values']
- elif isinstance(response, dict) and 'nodes' in response:
- # GraphQL format (if used)
- items = response['nodes']
-
- for item in items:
- if self._is_valid_microagent_file(item):
- try:
- file_name = self._get_file_name_from_item(item)
- file_path = self._get_file_path_from_item(
- item, microagents_path
- )
- microagents.append(
- self._create_microagent_response(file_name, file_path)
- )
- except Exception as e:
- logger.warning(
- f'Error processing microagent {item.get("name", "unknown")}: {str(e)}'
- )
- except ResourceNotFoundError:
- logger.info(
- f'No microagents directory found in {repository} at {microagents_path}'
- )
- except Exception as e:
- logger.warning(f'Error fetching microagents directory: {str(e)}')
-
- return microagents
-
- async def get_microagents(self, repository: str) -> list[MicroagentResponse]:
- """Generic implementation of get_microagents that works across all providers.
-
- Args:
- repository: Repository name in format specific to the provider
-
- Returns:
- List of microagents found in the repository (without content for performance)
- """
- microagents_path = self._determine_microagents_path(repository)
- microagents = []
-
- # Step 1: Check for .cursorrules file
- cursorrules_microagent = await self._check_cursorrules_file(repository)
- if cursorrules_microagent:
- microagents.append(cursorrules_microagent)
-
- # Step 2: Check for microagents directory and process .md files
- directory_microagents = await self._process_microagents_directory(
- repository, microagents_path
- )
- microagents.extend(directory_microagents)
-
- return microagents
-
def _truncate_comment(
self, comment_body: str, max_comment_length: int = 500
) -> str:
@@ -525,20 +304,6 @@ class GitService(Protocol):
) -> list[Branch]:
"""Search for branches within a repository"""
- async def get_microagents(self, repository: str) -> list[MicroagentResponse]:
- """Get microagents from a repository"""
- ...
-
- async def get_microagent_content(
- self, repository: str, file_path: str
- ) -> MicroagentContentResponse:
- """Get content of a specific microagent file
-
- Returns:
- MicroagentContentResponse with parsed content and triggers
- """
- ...
-
async def get_pr_details(self, repository: str, pr_number: int) -> dict:
"""Get detailed information about a specific pull request/merge request
diff --git a/openhands/microagent/__init__.py b/openhands/microagent/__init__.py
deleted file mode 100644
index 110da6d38d..0000000000
--- a/openhands/microagent/__init__.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from .microagent import (
- BaseMicroagent,
- KnowledgeMicroagent,
- RepoMicroagent,
- load_microagents_from_dir,
-)
-from .types import MicroagentMetadata, MicroagentType
-
-__all__ = [
- 'BaseMicroagent',
- 'KnowledgeMicroagent',
- 'RepoMicroagent',
- 'MicroagentMetadata',
- 'MicroagentType',
- 'load_microagents_from_dir',
-]
diff --git a/openhands/microagent/microagent.py b/openhands/microagent/microagent.py
deleted file mode 100644
index 65dbc4b191..0000000000
--- a/openhands/microagent/microagent.py
+++ /dev/null
@@ -1,350 +0,0 @@
-import io
-import re
-from itertools import chain
-from pathlib import Path
-from typing import ClassVar, Union
-
-import frontmatter
-from pydantic import BaseModel
-
-from openhands.core.exceptions import (
- MicroagentValidationError,
-)
-from openhands.core.logger import openhands_logger as logger
-from openhands.microagent.types import InputMetadata, MicroagentMetadata, MicroagentType
-
-
-class BaseMicroagent(BaseModel):
- """Base class for all microagents."""
-
- name: str
- content: str
- metadata: MicroagentMetadata
- source: str # path to the file
- type: MicroagentType
-
- PATH_TO_THIRD_PARTY_MICROAGENT_NAME: ClassVar[dict[str, str]] = {
- '.cursorrules': 'cursorrules',
- 'agents.md': 'agents',
- 'agent.md': 'agents',
- }
-
- @classmethod
- def _handle_third_party(
- cls, path: Path, file_content: str
- ) -> Union['RepoMicroagent', None]:
- # Determine the agent name based on file type
- microagent_name = cls.PATH_TO_THIRD_PARTY_MICROAGENT_NAME.get(path.name.lower())
-
- # Create RepoMicroagent if we recognized the file type
- if microagent_name is not None:
- return RepoMicroagent(
- name=microagent_name,
- content=file_content,
- metadata=MicroagentMetadata(name=microagent_name),
- source=str(path),
- type=MicroagentType.REPO_KNOWLEDGE,
- )
-
- return None
-
- @classmethod
- def load(
- cls,
- path: Union[str, Path],
- microagent_dir: Path | None = None,
- file_content: str | None = None,
- ) -> 'BaseMicroagent':
- """Load a microagent from a markdown file with frontmatter.
-
- The agent's name is derived from its path relative to the microagent_dir.
- """
- path = Path(path) if isinstance(path, str) else path
-
- # Calculate derived name from relative path if microagent_dir is provided
- # Otherwise, we will rely on the name from metadata later
- derived_name = None
- if microagent_dir is not None:
- # Special handling for files which are not in microagent_dir
- derived_name = cls.PATH_TO_THIRD_PARTY_MICROAGENT_NAME.get(
- path.name.lower()
- ) or str(path.relative_to(microagent_dir).with_suffix(''))
-
- # Only load directly from path if file_content is not provided
- if file_content is None:
- with open(path) as f:
- file_content = f.read()
-
- # Legacy repo instructions are stored in .openhands_instructions
- if path.name == '.openhands_instructions':
- return RepoMicroagent(
- name='repo_legacy',
- content=file_content,
- metadata=MicroagentMetadata(name='repo_legacy'),
- source=str(path),
- type=MicroagentType.REPO_KNOWLEDGE,
- )
-
- # Handle third-party agent instruction files
- third_party_agent = cls._handle_third_party(path, file_content)
- if third_party_agent is not None:
- return third_party_agent
-
- file_io = io.StringIO(file_content)
- loaded = frontmatter.load(file_io)
- content = loaded.content
-
- # Handle case where there's no frontmatter or empty frontmatter
- metadata_dict = loaded.metadata or {}
-
- # Ensure version is always a string (YAML may parse numeric versions as integers)
- if 'version' in metadata_dict and not isinstance(metadata_dict['version'], str):
- metadata_dict['version'] = str(metadata_dict['version'])
-
- try:
- metadata = MicroagentMetadata(**metadata_dict)
-
- # Validate MCP tools configuration if present
- if metadata.mcp_tools and metadata.mcp_tools.mcpServers:
- from openhands.core.config.mcp_config import StdioMCPServer
-
- has_stdio = any(
- isinstance(s, StdioMCPServer)
- for s in metadata.mcp_tools.mcpServers.values()
- )
- has_non_stdio = any(
- not isinstance(s, StdioMCPServer)
- for s in metadata.mcp_tools.mcpServers.values()
- )
- if has_non_stdio:
- logger.warning(
- f'Microagent {metadata.name} has remote servers. Only stdio servers are currently supported.'
- )
- if not has_stdio:
- raise MicroagentValidationError(
- f'Microagent {metadata.name} has MCP tools configuration but no stdio servers. '
- 'Only stdio servers are currently supported.'
- )
- except Exception as e:
- # Provide more detailed error message for validation errors
- error_msg = f'Error validating microagent metadata in {path.name}: {str(e)}'
- if 'type' in metadata_dict and metadata_dict['type'] not in [
- t.value for t in MicroagentType
- ]:
- valid_types = ', '.join([f'"{t.value}"' for t in MicroagentType])
- error_msg += f'. Invalid "type" value: "{metadata_dict["type"]}". Valid types are: {valid_types}'
- raise MicroagentValidationError(error_msg) from e
-
- # Create appropriate subclass based on type
- subclass_map = {
- MicroagentType.KNOWLEDGE: KnowledgeMicroagent,
- MicroagentType.REPO_KNOWLEDGE: RepoMicroagent,
- MicroagentType.TASK: TaskMicroagent,
- }
-
- # Infer the agent type:
- # 1. If inputs exist -> TASK
- # 2. If triggers exist -> KNOWLEDGE
- # 3. Else (no triggers) -> REPO (always active)
- inferred_type: MicroagentType
- if metadata.inputs:
- inferred_type = MicroagentType.TASK
- # Add a trigger for the agent name if not already present
- trigger = f'/{metadata.name}'
- if not metadata.triggers or trigger not in metadata.triggers:
- if not metadata.triggers:
- metadata.triggers = [trigger]
- else:
- metadata.triggers.append(trigger)
- elif metadata.triggers:
- inferred_type = MicroagentType.KNOWLEDGE
- else:
- # No triggers, default to REPO
- # This handles cases where 'type' might be missing or defaulted by Pydantic
- inferred_type = MicroagentType.REPO_KNOWLEDGE
-
- if inferred_type not in subclass_map:
- # This should theoretically not happen with the logic above
- raise ValueError(f'Could not determine microagent type for: {path}')
-
- # Use derived_name if available (from relative path), otherwise fallback to metadata.name
- agent_name = derived_name if derived_name is not None else metadata.name
-
- agent_class = subclass_map[inferred_type]
- return agent_class(
- name=agent_name,
- content=content,
- metadata=metadata,
- source=str(path),
- type=inferred_type,
- )
-
-
-class KnowledgeMicroagent(BaseMicroagent):
- """Knowledge micro-agents provide specialized expertise that's triggered by keywords in conversations.
-
- They help with:
- - Language best practices
- - Framework guidelines
- - Common patterns
- - Tool usage
- """
-
- def __init__(self, **data):
- super().__init__(**data)
- if self.type not in [MicroagentType.KNOWLEDGE, MicroagentType.TASK]:
- raise ValueError('KnowledgeMicroagent must have type KNOWLEDGE or TASK')
-
- def match_trigger(self, message: str) -> str | None:
- """Match a trigger in the message.
-
- It returns the first trigger that matches the message.
- """
- message = message.lower()
- for trigger in self.triggers:
- if trigger.lower() in message:
- return trigger
-
- return None
-
- @property
- def triggers(self) -> list[str]:
- return self.metadata.triggers
-
-
-class RepoMicroagent(BaseMicroagent):
- """Microagent specialized for repository-specific knowledge and guidelines.
-
- RepoMicroagents are loaded from `.openhands/microagents/repo.md` files within repositories
- and contain private, repository-specific instructions that are automatically loaded when
- working with that repository. They are ideal for:
- - Repository-specific guidelines
- - Team practices and conventions
- - Project-specific workflows
- - Custom documentation references
- """
-
- def __init__(self, **data):
- super().__init__(**data)
- if self.type != MicroagentType.REPO_KNOWLEDGE:
- raise ValueError(
- f'RepoMicroagent initialized with incorrect type: {self.type}'
- )
-
-
-class TaskMicroagent(KnowledgeMicroagent):
- """TaskMicroagent is a special type of KnowledgeMicroagent that requires user input.
-
- These microagents are triggered by a special format: "/{agent_name}"
- and will prompt the user for any required inputs before proceeding.
- """
-
- def __init__(self, **data):
- super().__init__(**data)
- if self.type != MicroagentType.TASK:
- raise ValueError(
- f'TaskMicroagent initialized with incorrect type: {self.type}'
- )
-
- # Append a prompt to ask for missing variables
- self._append_missing_variables_prompt()
-
- def _append_missing_variables_prompt(self) -> None:
- """Append a prompt to ask for missing variables."""
- # Check if the content contains any variables or has inputs defined
- if not self.requires_user_input() and not self.metadata.inputs:
- return
-
- prompt = "\n\nIf the user didn't provide any of these variables, ask the user to provide them first before the agent can proceed with the task."
- self.content += prompt
-
- def extract_variables(self, content: str) -> list[str]:
- """Extract variables from the content.
-
- Variables are in the format ${variable_name}.
- """
- pattern = r'\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}'
- matches = re.findall(pattern, content)
- return matches
-
- def requires_user_input(self) -> bool:
- """Check if this microagent requires user input.
-
- Returns True if the content contains variables in the format ${variable_name}.
- """
- # Check if the content contains any variables
- variables = self.extract_variables(self.content)
- logger.debug(f'This microagent requires user input: {variables}')
- return len(variables) > 0
-
- @property
- def inputs(self) -> list[InputMetadata]:
- """Get the inputs for this microagent."""
- return self.metadata.inputs
-
-
-def load_microagents_from_dir(
- microagent_dir: Union[str, Path],
-) -> tuple[dict[str, RepoMicroagent], dict[str, KnowledgeMicroagent]]:
- """Load all microagents from the given directory.
-
- Note, legacy repo instructions will not be loaded here.
-
- Args:
- microagent_dir: Path to the microagents directory (e.g. .openhands/microagents)
-
- Returns:
- Tuple of (repo_agents, knowledge_agents) dictionaries
- """
- if isinstance(microagent_dir, str):
- microagent_dir = Path(microagent_dir)
-
- repo_agents = {}
- knowledge_agents = {}
-
- # Load all agents from microagents directory
- logger.debug(f'Loading agents from {microagent_dir}')
-
- # Always check for .cursorrules and AGENTS.md files in repo root, regardless of whether microagents_dir exists
- special_files = []
- repo_root = microagent_dir.parent.parent
-
- # Check for .cursorrules
- if (repo_root / '.cursorrules').exists():
- special_files.append(repo_root / '.cursorrules')
-
- # Check for AGENTS.md (case-insensitive)
- for agents_filename in ['AGENTS.md', 'agents.md', 'AGENT.md', 'agent.md']:
- agents_path = repo_root / agents_filename
- if agents_path.exists():
- special_files.append(agents_path)
- break # Only add the first one found to avoid duplicates
-
- # Collect .md files from microagents directory if it exists
- md_files = []
- if microagent_dir.exists():
- md_files = [f for f in microagent_dir.rglob('*.md') if f.name != 'README.md']
-
- # Process all files in one loop
- for file in chain(special_files, md_files):
- try:
- agent = BaseMicroagent.load(file, microagent_dir)
- if isinstance(agent, RepoMicroagent):
- repo_agents[agent.name] = agent
- elif isinstance(agent, KnowledgeMicroagent):
- # Both KnowledgeMicroagent and TaskMicroagent go into knowledge_agents
- knowledge_agents[agent.name] = agent
- except MicroagentValidationError as e:
- # For validation errors, include the original exception
- error_msg = f'Error loading microagent from {file}: {str(e)}'
- raise MicroagentValidationError(error_msg) from e
- except Exception as e:
- # For other errors, wrap in a ValueError with detailed message
- error_msg = f'Error loading microagent from {file}: {str(e)}'
- raise ValueError(error_msg) from e
-
- logger.debug(
- f'Loaded {len(repo_agents) + len(knowledge_agents)} microagents: '
- f'{[*repo_agents.keys(), *knowledge_agents.keys()]}'
- )
- return repo_agents, knowledge_agents
diff --git a/openhands/microagent/prompts/generate_remember_prompt.j2 b/openhands/microagent/prompts/generate_remember_prompt.j2
deleted file mode 100644
index 68c42fd87c..0000000000
--- a/openhands/microagent/prompts/generate_remember_prompt.j2
+++ /dev/null
@@ -1,21 +0,0 @@
-You are tasked with generating a prompt that will be used by another AI to update a special reference file. This file contains important information and learnings that are used to carry out certain tasks. The file can be extended over time to incorporate new knowledge and experiences.
-
-You have been provided with a subset of new events that may require updates to the special file. These events are:
-<events>
-{{ events }}
-</events>
-
-Your task is to analyze these events and determine what updates, if any, should be made to the special file. Then, you need to generate a prompt that will instruct another AI to make these updates correctly and efficiently.
-
-When creating your prompt, follow these guidelines:
-1. Clearly specify which parts of the file need to be updated or if new sections should be added.
-2. Provide context for why these updates are necessary based on the new events.
-3. Be specific about the information that should be added or modified.
-4. Maintain the existing structure and formatting of the file.
-5. Ensure that the updates are consistent with the current content and don't contradict existing information.
-
-Now, based on the new events provided, generate a prompt that will guide the AI in making the appropriate updates to the special file. Your prompt should be clear, specific, and actionable. Include your prompt within <update_prompt> tags.
-
-<update_prompt>
-
-</update_prompt>
diff --git a/openhands/microagent/types.py b/openhands/microagent/types.py
deleted file mode 100644
index 276876172e..0000000000
--- a/openhands/microagent/types.py
+++ /dev/null
@@ -1,59 +0,0 @@
-from datetime import datetime
-from enum import Enum
-
-from pydantic import BaseModel, Field
-
-from openhands.core.config.mcp_config import (
- MCPConfig,
-)
-
-
-class MicroagentType(str, Enum):
- """Type of microagent."""
-
- KNOWLEDGE = 'knowledge' # Optional microagent, triggered by keywords
- REPO_KNOWLEDGE = 'repo' # Always active microagent
- TASK = 'task' # Special type for task microagents that require user input
-
-
-class InputMetadata(BaseModel):
- """Metadata for task microagent inputs."""
-
- name: str
- description: str
-
-
-class MicroagentMetadata(BaseModel):
- """Metadata for all microagents."""
-
- name: str = 'default'
- type: MicroagentType = Field(default=MicroagentType.REPO_KNOWLEDGE)
- version: str = Field(default='1.0.0')
- agent: str = Field(default='CodeActAgent')
- triggers: list[str] = [] # optional, only exists for knowledge microagents
- inputs: list[InputMetadata] = [] # optional, only exists for task microagents
- mcp_tools: MCPConfig | None = (
- None # optional, for microagents that provide additional MCP tools
- )
-
-
-class MicroagentResponse(BaseModel):
- """Response model for microagents endpoint.
-
- Note: This model only includes basic metadata that can be determined
- without parsing microagent content. Use the separate content API
- to get detailed microagent information.
- """
-
- name: str
- path: str
- created_at: datetime
-
-
-class MicroagentContentResponse(BaseModel):
- """Response model for individual microagent content endpoint."""
-
- content: str
- path: str
- triggers: list[str] = []
- git_provider: str | None = None
diff --git a/openhands/runtime/base.py b/openhands/runtime/base.py
index 8043de75ec..00f90aa387 100644
--- a/openhands/runtime/base.py
+++ b/openhands/runtime/base.py
@@ -12,15 +12,12 @@ import json
import os
import random
import shlex
-import shutil
import string
-import tempfile
import time
from abc import abstractmethod
from pathlib import Path
from types import MappingProxyType
from typing import Callable, cast
-from zipfile import ZipFile
import httpx
@@ -53,7 +50,6 @@ from openhands.events.observation import (
AgentThinkObservation,
CmdOutputObservation,
ErrorObservation,
- FileReadObservation,
NullObservation,
Observation,
TaskTrackingObservation,
@@ -65,12 +61,7 @@ from openhands.integrations.provider import (
ProviderHandler,
ProviderType,
)
-from openhands.integrations.service_types import AuthenticationError
from openhands.llm.llm_registry import LLMRegistry
-from openhands.microagent import (
- BaseMicroagent,
- load_microagents_from_dir,
-)
from openhands.runtime.plugins import (
JupyterRequirement,
PluginRequirement,
@@ -675,62 +666,6 @@ fi
self.log('info', 'Git pre-commit hook installed successfully')
- def _load_microagents_from_directory(
- self, microagents_dir: Path, source_description: str
- ) -> list[BaseMicroagent]:
- """Load microagents from a directory.
-
- Args:
- microagents_dir: Path to the directory containing microagents
- source_description: Description of the source for logging purposes
-
- Returns:
- A list of loaded microagents
- """
- loaded_microagents: list[BaseMicroagent] = []
-
- self.log(
- 'info',
- f'Attempting to list files in {source_description} microagents directory: {microagents_dir}',
- )
-
- files = self.list_files(str(microagents_dir))
-
- if not files:
- self.log(
- 'debug',
- f'No files found in {source_description} microagents directory: {microagents_dir}',
- )
- return loaded_microagents
-
- self.log(
- 'info',
- f'Found {len(files)} files in {source_description} microagents directory',
- )
- zip_path = self.copy_from(str(microagents_dir))
- microagent_folder = tempfile.mkdtemp()
-
- try:
- with ZipFile(zip_path, 'r') as zip_file:
- zip_file.extractall(microagent_folder)
-
- zip_path.unlink()
- repo_agents, knowledge_agents = load_microagents_from_dir(microagent_folder)
-
- self.log(
- 'info',
- f'Loaded {len(repo_agents)} repo agents and {len(knowledge_agents)} knowledge agents from {source_description}',
- )
-
- loaded_microagents.extend(repo_agents.values())
- loaded_microagents.extend(knowledge_agents.values())
- except Exception as e:
- self.log('error', f'Failed to load agents from {source_description}: {e}')
- finally:
- shutil.rmtree(microagent_folder)
-
- return loaded_microagents
-
def _is_gitlab_repository(self, repo_name: str) -> bool:
"""Check if a repository is hosted on GitLab.
@@ -778,245 +713,6 @@ fi
# If we can't determine the provider, assume it's not Azure DevOps
return False
- def get_microagents_from_org_or_user(
- self, selected_repository: str
- ) -> list[BaseMicroagent]:
- """Load microagents from the organization or user level repository.
-
- For example, if the repository is github.com/acme-co/api, this will check if
- github.com/acme-co/.openhands exists. If it does, it will clone it and load
- the microagents from the ./microagents/ folder.
-
- For GitLab repositories, it will use openhands-config instead of .openhands
- since GitLab doesn't support repository names starting with non-alphanumeric
- characters.
-
- For Azure DevOps repositories, it will use org/openhands-config/openhands-config
- format to match Azure DevOps's three-part repository structure (org/project/repo).
-
- Args:
- selected_repository: The repository path (e.g., "github.com/acme-co/api")
-
- Returns:
- A list of loaded microagents from the org/user level repository
- """
- loaded_microagents: list[BaseMicroagent] = []
-
- self.log(
- 'debug',
- f'Starting org-level microagent loading for repository: {selected_repository}',
- )
-
- repo_parts = selected_repository.split('/')
-
- if len(repo_parts) < 2:
- self.log(
- 'warning',
- f'Repository path has insufficient parts ({len(repo_parts)} < 2), skipping org-level microagents',
- )
- return loaded_microagents
-
- # Determine repository type
- is_azure_devops = self._is_azure_devops_repository(selected_repository)
- is_gitlab = self._is_gitlab_repository(selected_repository)
-
- # Extract the org/user name
- # Azure DevOps format: org/project/repo (3 parts) - extract org (first part)
- # GitHub/GitLab/Bitbucket format: owner/repo (2 parts) - extract owner (first part)
- if is_azure_devops and len(repo_parts) >= 3:
- org_name = repo_parts[0] # Get org from org/project/repo
- else:
- org_name = repo_parts[-2] # Get owner from owner/repo
-
- self.log(
- 'info',
- f'Extracted org/user name: {org_name}',
- )
- self.log(
- 'debug',
- f'Repository type detection - is_gitlab: {is_gitlab}, is_azure_devops: {is_azure_devops}',
- )
-
- # For GitLab and Azure DevOps, use openhands-config (since .openhands is not a valid repo name)
- # For other providers, use .openhands
- if is_gitlab:
- org_openhands_repo = f'{org_name}/openhands-config'
- elif is_azure_devops:
- # Azure DevOps format: org/project/repo
- # For org-level config, use: org/openhands-config/openhands-config
- org_openhands_repo = f'{org_name}/openhands-config/openhands-config'
- else:
- org_openhands_repo = f'{org_name}/.openhands'
-
- self.log(
- 'info',
- f'Checking for org-level microagents at {org_openhands_repo}',
- )
-
- # Try to clone the org-level repo
- try:
- # Create a temporary directory for the org-level repo
- org_repo_dir = self.workspace_root / f'org_openhands_{org_name}'
- self.log(
- 'debug',
- f'Creating temporary directory for org repo: {org_repo_dir}',
- )
-
- # Get authenticated URL and do a shallow clone (--depth 1) for efficiency
- try:
- remote_url = call_async_from_sync(
- self.provider_handler.get_authenticated_git_url,
- GENERAL_TIMEOUT,
- org_openhands_repo,
- is_optional=True,
- )
- except AuthenticationError as e:
- self.log(
- 'debug',
- f'org-level microagent directory {org_openhands_repo} not found: {str(e)}',
- )
- raise
- except Exception as e:
- self.log(
- 'debug',
- f'Failed to get authenticated URL for {org_openhands_repo}: {str(e)}',
- )
- raise
-
- clone_cmd = (
- f'GIT_TERMINAL_PROMPT=0 git clone --depth 1 {remote_url} {org_repo_dir}'
- )
- self.log(
- 'info',
- 'Executing clone command for org-level repo',
- )
-
- action = CmdRunAction(command=clone_cmd)
- obs = self.run_action(action)
-
- if isinstance(obs, CmdOutputObservation) and obs.exit_code == 0:
- self.log(
- 'info',
- f'Successfully cloned org-level microagents from {org_openhands_repo}',
- )
-
- # Load microagents from the org-level repo
- org_microagents_dir = org_repo_dir / 'microagents'
- self.log(
- 'info',
- f'Looking for microagents in directory: {org_microagents_dir}',
- )
-
- loaded_microagents = self._load_microagents_from_directory(
- org_microagents_dir, 'org-level'
- )
-
- self.log(
- 'info',
- f'Loaded {len(loaded_microagents)} microagents from org-level repository {org_openhands_repo}',
- )
-
- # Clean up the org repo directory
- action = CmdRunAction(f'rm -rf {org_repo_dir}')
- self.run_action(action)
- else:
- clone_error_msg = (
- obs.content
- if isinstance(obs, CmdOutputObservation)
- else 'Unknown error'
- )
- exit_code = (
- obs.exit_code if isinstance(obs, CmdOutputObservation) else 'N/A'
- )
- self.log(
- 'info',
- f'No org-level microagents found at {org_openhands_repo} (exit_code: {exit_code})',
- )
- self.log(
- 'debug',
- f'Clone command output: {clone_error_msg}',
- )
-
- except AuthenticationError as e:
- self.log(
- 'debug',
- f'org-level microagent directory {org_openhands_repo} not found: {str(e)}',
- )
- except Exception as e:
- self.log(
- 'debug',
- f'Error loading org-level microagents from {org_openhands_repo}: {str(e)}',
- )
-
- return loaded_microagents
-
- def get_microagents_from_selected_repo(
- self, selected_repository: str | None
- ) -> list[BaseMicroagent]:
- """Load microagents from the selected repository.
- If selected_repository is None, load microagents from the current workspace.
- This is the main entry point for loading microagents.
-
- This method also checks for user/org level microagents stored in a repository.
- For example, if the repository is github.com/acme-co/api, it will also check for
- github.com/acme-co/.openhands and load microagents from there if it exists.
-
- For GitLab repositories, it will use openhands-config instead of .openhands
- since GitLab doesn't support repository names starting with non-alphanumeric
- characters.
- """
- loaded_microagents: list[BaseMicroagent] = []
- microagents_dir = self.workspace_root / '.openhands' / 'microagents'
- repo_root = None
-
- # Check for user/org level microagents if a repository is selected
- if selected_repository:
- # Load microagents from the org/user level repository
- org_microagents = self.get_microagents_from_org_or_user(selected_repository)
- loaded_microagents.extend(org_microagents)
-
- # Continue with repository-specific microagents
- repo_root = self.workspace_root / selected_repository.split('/')[-1]
- microagents_dir = repo_root / '.openhands' / 'microagents'
-
- self.log(
- 'info',
- f'Selected repo: {selected_repository}, loading microagents from {microagents_dir} (inside runtime)',
- )
-
- # Legacy Repo Instructions
- # Check for legacy .openhands_instructions file
- obs = self.read(
- FileReadAction(path=str(self.workspace_root / '.openhands_instructions'))
- )
- if isinstance(obs, ErrorObservation) and repo_root is not None:
- # If the instructions file is not found in the workspace root, try to load it from the repo root
- self.log(
- 'debug',
- f'.openhands_instructions not present, trying to load from repository microagents_dir={microagents_dir}',
- )
- obs = self.read(
- FileReadAction(path=str(repo_root / '.openhands_instructions'))
- )
-
- if isinstance(obs, FileReadObservation):
- self.log('info', 'openhands_instructions microagent loaded.')
- loaded_microagents.append(
- BaseMicroagent.load(
- path='.openhands_instructions',
- microagent_dir=None,
- file_content=obs.content,
- )
- )
-
- # Load microagents from directory
- repo_microagents = self._load_microagents_from_directory(
- microagents_dir, 'repository'
- )
- loaded_microagents.extend(repo_microagents)
-
- return loaded_microagents
-
def run_action(self, action: Action) -> Observation:
"""Run an action and return the resulting observation.
If the action is not runnable in any runtime, a NullObservation is returned.
diff --git a/tests/unit/microagent/test_microagent_no_header.py b/tests/unit/microagent/test_microagent_no_header.py
deleted file mode 100644
index 584919763a..0000000000
--- a/tests/unit/microagent/test_microagent_no_header.py
+++ /dev/null
@@ -1,94 +0,0 @@
-from pathlib import Path
-
-from openhands.microagent.microagent import BaseMicroagent, RepoMicroagent
-from openhands.microagent.types import MicroagentType
-
-
-def test_load_markdown_without_frontmatter():
- """Test loading a markdown file without frontmatter."""
- content = '# Test Content\nThis is a test markdown file without frontmatter.'
- path = Path('test.md')
-
- # Load the agent from content using keyword argument
- agent = BaseMicroagent.load(path=path, file_content=content)
-
- # Verify it's loaded as a repo agent with default values
- assert isinstance(agent, RepoMicroagent)
- assert agent.name == 'default'
- assert agent.content == content
- assert agent.type == MicroagentType.REPO_KNOWLEDGE
- assert agent.metadata.agent == 'CodeActAgent'
- assert agent.metadata.version == '1.0.0'
-
-
-def test_load_markdown_with_empty_frontmatter():
- """Test loading a markdown file with empty frontmatter."""
- content = (
- '---\n---\n# Test Content\nThis is a test markdown file with empty frontmatter.'
- )
- path = Path('test.md')
-
- # Load the agent from content using keyword argument
- agent = BaseMicroagent.load(path=path, file_content=content)
-
- # Verify it's loaded as a repo agent with default values
- assert isinstance(agent, RepoMicroagent)
- assert agent.name == 'default'
- assert (
- agent.content
- == '# Test Content\nThis is a test markdown file with empty frontmatter.'
- )
- assert agent.type == MicroagentType.REPO_KNOWLEDGE
- assert agent.metadata.agent == 'CodeActAgent'
- assert agent.metadata.version == '1.0.0'
-
-
-def test_load_markdown_with_partial_frontmatter():
- """Test loading a markdown file with partial frontmatter."""
- content = """---
-name: custom_name
----
-# Test Content
-This is a test markdown file with partial frontmatter."""
- path = Path('test.md')
-
- # Load the agent from content using keyword argument
- agent = BaseMicroagent.load(path=path, file_content=content)
-
- # Verify it uses provided name but default values for other fields
- assert isinstance(agent, RepoMicroagent)
- assert agent.name == 'custom_name'
- assert (
- agent.content
- == '# Test Content\nThis is a test markdown file with partial frontmatter.'
- )
- assert agent.type == MicroagentType.REPO_KNOWLEDGE
- assert agent.metadata.agent == 'CodeActAgent'
- assert agent.metadata.version == '1.0.0'
-
-
-def test_load_markdown_with_full_frontmatter():
- """Test loading a markdown file with full frontmatter still works."""
- content = """---
-name: test_agent
-type: repo
-agent: CustomAgent
-version: 2.0.0
----
-# Test Content
-This is a test markdown file with full frontmatter."""
- path = Path('test.md')
-
- # Load the agent from content using keyword argument
- agent = BaseMicroagent.load(path=path, file_content=content)
-
- # Verify all provided values are used
- assert isinstance(agent, RepoMicroagent)
- assert agent.name == 'test_agent'
- assert (
- agent.content
- == '# Test Content\nThis is a test markdown file with full frontmatter.'
- )
- assert agent.type == MicroagentType.REPO_KNOWLEDGE
- assert agent.metadata.agent == 'CustomAgent'
- assert agent.metadata.version == '2.0.0'
diff --git a/tests/unit/microagent/test_microagent_utils.py b/tests/unit/microagent/test_microagent_utils.py
deleted file mode 100644
index 8cde9631b4..0000000000
--- a/tests/unit/microagent/test_microagent_utils.py
+++ /dev/null
@@ -1,547 +0,0 @@
-"""Tests for the microagent system."""
-
-import tempfile
-from pathlib import Path
-
-import pytest
-
-from openhands.microagent import (
- BaseMicroagent,
- KnowledgeMicroagent,
- MicroagentMetadata,
- MicroagentType,
- RepoMicroagent,
- load_microagents_from_dir,
-)
-
-CONTENT = '# dummy header\ndummy content\n## dummy subheader\ndummy subcontent\n'
-
-
-def test_legacy_micro_agent_load(tmp_path):
- """Test loading of legacy microagents."""
- legacy_file = tmp_path / '.openhands_instructions'
- legacy_file.write_text(CONTENT)
-
- # Pass microagent_dir (tmp_path in this case) to load
- micro_agent = BaseMicroagent.load(legacy_file, tmp_path)
- assert isinstance(micro_agent, RepoMicroagent)
- assert micro_agent.name == 'repo_legacy' # Legacy name is hardcoded
- assert micro_agent.content == CONTENT
- assert micro_agent.type == MicroagentType.REPO_KNOWLEDGE
-
-
-def temp_microagents_dir():
- """Create a temporary directory with test microagents."""
- with tempfile.TemporaryDirectory() as temp_dir:
- root = Path(temp_dir)
-
- # Create test knowledge agent (type inferred from triggers)
- knowledge_agent = """---
-# type: knowledge
-version: 1.0.0
-agent: CodeActAgent
-triggers:
- - test
- - pytest
----
-
-# Test Guidelines
-
-Testing best practices and guidelines.
-"""
- (root / 'knowledge.md').write_text(knowledge_agent)
-
- # Create test repo agent (type inferred from lack of triggers)
- repo_agent = """---
-# type: repo
-version: 1.0.0
-agent: CodeActAgent
----
-
-# Test Repository Agent
-
-Repository-specific test instructions.
-"""
- (root / 'repo.md').write_text(repo_agent)
-
- yield root
-
-
-def test_knowledge_agent():
- """Test knowledge agent functionality."""
- # Note: We still pass type to the constructor here, as it expects it.
- # The loader infers the type before calling the constructor.
- agent = KnowledgeMicroagent(
- name='test',
- content='Test content',
- metadata=MicroagentMetadata(name='test', triggers=['test', 'pytest']),
- source='test.md',
- type=MicroagentType.KNOWLEDGE, # Constructor still needs type
- )
-
- assert agent.match_trigger('running a test') == 'test'
- assert agent.match_trigger('using pytest') == 'test'
- assert agent.match_trigger('no match here') is None
- assert agent.triggers == ['test', 'pytest']
-
-
-def test_load_microagents(temp_microagents_dir):
- """Test loading microagents from directory."""
- repo_agents, knowledge_agents = load_microagents_from_dir(temp_microagents_dir)
-
- # Check knowledge agents (name derived from filename: knowledge.md -> 'knowledge')
- assert len(knowledge_agents) == 1
- agent_k = knowledge_agents['knowledge']
- assert isinstance(agent_k, KnowledgeMicroagent)
- assert agent_k.type == MicroagentType.KNOWLEDGE # Check inferred type
- assert 'test' in agent_k.triggers
-
- # Check repo agents (name derived from filename: repo.md -> 'repo')
- assert len(repo_agents) == 1
- agent_r = repo_agents['repo']
- assert isinstance(agent_r, RepoMicroagent)
- assert agent_r.type == MicroagentType.REPO_KNOWLEDGE # Check inferred type
-
-
-def test_load_microagents_with_nested_dirs(temp_microagents_dir):
- """Test loading microagents from nested directories."""
- # Create nested knowledge agent
- nested_dir = temp_microagents_dir / 'nested' / 'dir'
- nested_dir.mkdir(parents=True)
- nested_agent = """---
-# type: knowledge
-version: 1.0.0
-agent: CodeActAgent
-triggers:
- - nested
----
-
-# Nested Test Guidelines
-
-Testing nested directory loading.
-"""
- (nested_dir / 'nested.md').write_text(nested_agent)
-
- repo_agents, knowledge_agents = load_microagents_from_dir(temp_microagents_dir)
-
- # Check that we can find the nested agent (name derived from path: nested/dir/nested.md -> 'nested/dir/nested')
- assert (
- len(knowledge_agents) == 2
- ) # Original ('knowledge') + nested ('nested/dir/nested')
- agent_n = knowledge_agents['nested/dir/nested']
- assert isinstance(agent_n, KnowledgeMicroagent)
- assert agent_n.type == MicroagentType.KNOWLEDGE # Check inferred type
- assert 'nested' in agent_n.triggers
-
-
-def test_load_microagents_with_trailing_slashes(temp_microagents_dir):
- """Test loading microagents when directory paths have trailing slashes."""
- # Create a directory with trailing slash
- knowledge_dir = temp_microagents_dir / 'test_knowledge/'
- knowledge_dir.mkdir(exist_ok=True)
- knowledge_agent = """---
-# type: knowledge
-version: 1.0.0
-agent: CodeActAgent
-triggers:
- - trailing
----
-
-# Trailing Slash Test
-
-Testing loading with trailing slashes.
-"""
- (knowledge_dir / 'trailing.md').write_text(knowledge_agent)
-
- repo_agents, knowledge_agents = load_microagents_from_dir(
- str(temp_microagents_dir) + '/' # Add trailing slash to test
- )
-
- # Check that we can find the agent despite trailing slashes (name derived from path: test_knowledge/trailing.md -> 'test_knowledge/trailing')
- assert (
- len(knowledge_agents) == 2
- ) # Original ('knowledge') + trailing ('test_knowledge/trailing')
- agent_t = knowledge_agents['test_knowledge/trailing']
- assert isinstance(agent_t, KnowledgeMicroagent)
- assert agent_t.type == MicroagentType.KNOWLEDGE # Check inferred type
- assert 'trailing' in agent_t.triggers
-
-
-def test_invalid_microagent_type(temp_microagents_dir):
- """Test loading a microagent with an invalid type."""
- # Create a microagent with an invalid type
- invalid_agent = """---
-name: invalid_type_agent
-type: invalid_type
-version: 1.0.0
-agent: CodeActAgent
-triggers:
- - test
----
-
-# Invalid Type Test
-
-This microagent has an invalid type.
-"""
- invalid_file = temp_microagents_dir / 'invalid_type.md'
- invalid_file.write_text(invalid_agent)
-
- # Attempt to load the microagent should raise a MicroagentValidationError
- from openhands.core.exceptions import MicroagentValidationError
-
- with pytest.raises(MicroagentValidationError) as excinfo:
- load_microagents_from_dir(temp_microagents_dir)
-
- # Check that the error message contains helpful information
- error_msg = str(excinfo.value)
- assert 'invalid_type.md' in error_msg
- assert 'Invalid "type" value: "invalid_type"' in error_msg
- assert 'Valid types are:' in error_msg
- assert '"knowledge"' in error_msg
- assert '"repo"' in error_msg
- assert '"task"' in error_msg
-
-
-def test_cursorrules_file_load():
- """Test loading .cursorrules file as a RepoMicroagent."""
- cursorrules_content = """Always use Python for new files.
-Follow the existing code style.
-Add proper error handling."""
-
- cursorrules_path = Path('.cursorrules')
-
- # Test loading .cursorrules file directly
- agent = BaseMicroagent.load(cursorrules_path, file_content=cursorrules_content)
-
- # Verify it's loaded as a RepoMicroagent
- assert isinstance(agent, RepoMicroagent)
- assert agent.name == 'cursorrules'
- assert agent.content == cursorrules_content
- assert agent.type == MicroagentType.REPO_KNOWLEDGE
- assert agent.metadata.name == 'cursorrules'
- assert agent.source == str(cursorrules_path)
-
-
-def test_microagent_version_as_integer():
- """Test loading a microagent with version as integer (reproduces the bug)."""
- # Create a microagent with version as an unquoted integer
- # This should be parsed as an integer by YAML but converted to string by our code
- microagent_content = """---
-name: test_agent
-type: knowledge
-version: 2512312
-agent: CodeActAgent
-triggers:
- - test
----
-
-# Test Agent
-
-This is a test agent with integer version.
-"""
-
- test_path = Path('test_agent.md')
-
- # This should not raise an error even though version is an integer in YAML
- agent = BaseMicroagent.load(test_path, file_content=microagent_content)
-
- # Verify the agent was loaded correctly
- assert isinstance(agent, KnowledgeMicroagent)
- assert agent.name == 'test_agent'
- assert agent.metadata.version == '2512312' # Should be converted to string
- assert isinstance(agent.metadata.version, str) # Ensure it's actually a string
- assert agent.type == MicroagentType.KNOWLEDGE
-
-
-def test_microagent_version_as_float():
- """Test loading a microagent with version as float."""
- # Create a microagent with version as an unquoted float
- microagent_content = """---
-name: test_agent_float
-type: knowledge
-version: 1.5
-agent: CodeActAgent
-triggers:
- - test
----
-
-# Test Agent Float
-
-This is a test agent with float version.
-"""
-
- test_path = Path('test_agent_float.md')
-
- # This should not raise an error even though version is a float in YAML
- agent = BaseMicroagent.load(test_path, file_content=microagent_content)
-
- # Verify the agent was loaded correctly
- assert isinstance(agent, KnowledgeMicroagent)
- assert agent.name == 'test_agent_float'
- assert agent.metadata.version == '1.5' # Should be converted to string
- assert isinstance(agent.metadata.version, str) # Ensure it's actually a string
- assert agent.type == MicroagentType.KNOWLEDGE
-
-
-def test_microagent_version_as_string_unchanged():
- """Test loading a microagent with version as string (should remain unchanged)."""
- # Create a microagent with version as a quoted string
- microagent_content = """---
-name: test_agent_string
-type: knowledge
-version: "1.0.0"
-agent: CodeActAgent
-triggers:
- - test
----
-
-# Test Agent String
-
-This is a test agent with string version.
-"""
-
- test_path = Path('test_agent_string.md')
-
- # This should work normally
- agent = BaseMicroagent.load(test_path, file_content=microagent_content)
-
- # Verify the agent was loaded correctly
- assert isinstance(agent, KnowledgeMicroagent)
- assert agent.name == 'test_agent_string'
- assert agent.metadata.version == '1.0.0' # Should remain as string
- assert isinstance(agent.metadata.version, str) # Ensure it's actually a string
- assert agent.type == MicroagentType.KNOWLEDGE
-
-
-def temp_microagents_dir_with_cursorrules():
- """Create a temporary directory with test microagents and .cursorrules file."""
- with tempfile.TemporaryDirectory() as temp_dir:
- root = Path(temp_dir)
-
- # Create .openhands/microagents directory structure
- microagents_dir = root / '.openhands' / 'microagents'
- microagents_dir.mkdir(parents=True, exist_ok=True)
-
- # Create .cursorrules file in repository root
- cursorrules_content = """Always use TypeScript for new files.
-Follow the existing code style."""
- (root / '.cursorrules').write_text(cursorrules_content)
-
- # Create test repo agent
- 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)
-
- yield root
-
-
-def test_load_microagents_with_cursorrules(temp_microagents_dir_with_cursorrules):
- """Test loading microagents when .cursorrules file exists."""
- microagents_dir = (
- temp_microagents_dir_with_cursorrules / '.openhands' / 'microagents'
- )
-
- repo_agents, knowledge_agents = load_microagents_from_dir(microagents_dir)
-
- # Verify that .cursorrules file was loaded as a RepoMicroagent
- assert len(repo_agents) == 2 # repo.md + .cursorrules
- assert 'repo' in repo_agents
- assert 'cursorrules' in repo_agents
-
- # Check .cursorrules agent
- cursorrules_agent = repo_agents['cursorrules']
- assert isinstance(cursorrules_agent, RepoMicroagent)
- assert cursorrules_agent.name == 'cursorrules'
- assert 'Always use TypeScript for new files' in cursorrules_agent.content
- assert cursorrules_agent.type == MicroagentType.REPO_KNOWLEDGE
-
-
-def temp_dir_with_cursorrules_only():
- """Create a temporary directory with only .cursorrules file (no .openhands/microagents directory)."""
- with tempfile.TemporaryDirectory() as temp_dir:
- root = Path(temp_dir)
-
- # Create .cursorrules file in repository root
- cursorrules_content = """Always use Python for new files.
-Follow PEP 8 style guidelines."""
- (root / '.cursorrules').write_text(cursorrules_content)
-
- # Note: We intentionally do NOT create .openhands/microagents directory
- yield root
-
-
-def test_load_cursorrules_without_microagents_dir(temp_dir_with_cursorrules_only):
- """Test loading .cursorrules file when .openhands/microagents directory doesn't exist.
-
- This test reproduces the bug where .cursorrules is only loaded when
- .openhands/microagents directory exists.
- """
- # Try to load from non-existent microagents directory
- microagents_dir = temp_dir_with_cursorrules_only / '.openhands' / 'microagents'
-
- repo_agents, knowledge_agents = load_microagents_from_dir(microagents_dir)
-
- # This should find the .cursorrules file even though microagents_dir doesn't exist
- assert len(repo_agents) == 1 # Only .cursorrules
- assert 'cursorrules' in repo_agents
- assert len(knowledge_agents) == 0
-
- # Check .cursorrules agent
- cursorrules_agent = repo_agents['cursorrules']
- assert isinstance(cursorrules_agent, RepoMicroagent)
- assert cursorrules_agent.name == 'cursorrules'
- assert 'Always use Python for new files' in cursorrules_agent.content
- assert cursorrules_agent.type == MicroagentType.REPO_KNOWLEDGE
-
-
-def test_agents_md_file_load():
- """Test loading AGENTS.md file as a RepoMicroagent."""
- agents_content = """# Project Setup
-
-## Setup commands
-
-- Install deps: `npm install`
-- Start dev server: `npm run dev`
-- Run tests: `npm test`
-
-## Code style
-
-- TypeScript strict mode
-- Single quotes, no semicolons
-- Use functional patterns where possible"""
-
- agents_path = Path('AGENTS.md')
-
- # Test loading AGENTS.md file directly
- agent = BaseMicroagent.load(agents_path, file_content=agents_content)
-
- # Verify it's loaded as a RepoMicroagent
- assert isinstance(agent, RepoMicroagent)
- assert agent.name == 'agents'
- assert agent.content == agents_content
- assert agent.type == MicroagentType.REPO_KNOWLEDGE
- assert agent.metadata.name == 'agents'
- assert agent.source == str(agents_path)
-
-
-def test_agents_md_case_insensitive():
- """Test that AGENTS.md loading is case-insensitive."""
- agents_content = """# Development Guide
-
-Use TypeScript for all new files."""
-
- test_cases = ['AGENTS.md', 'agents.md', 'AGENT.md', 'agent.md']
-
- for filename in test_cases:
- agents_path = Path(filename)
- agent = BaseMicroagent.load(agents_path, file_content=agents_content)
-
- assert isinstance(agent, RepoMicroagent)
- assert agent.name == 'agents'
- assert agent.content == agents_content
- assert agent.type == MicroagentType.REPO_KNOWLEDGE
-
-
-def temp_dir_with_agents_md_only():
- """Create a temporary directory with only AGENTS.md file (no .openhands/microagents directory)."""
- with tempfile.TemporaryDirectory() as temp_dir:
- root = Path(temp_dir)
-
- # Create AGENTS.md file in repository root
- agents_content = """# Development Guide
-
-## Setup commands
-
-- Install deps: `poetry install`
-- Start dev server: `poetry run python app.py`
-- Run tests: `poetry run pytest`
-
-## Code style
-
-- Python 3.12+
-- Follow PEP 8 guidelines
-- Use type hints everywhere"""
- (root / 'AGENTS.md').write_text(agents_content)
-
- # Note: We intentionally do NOT create .openhands/microagents directory
- yield root
-
-
-def test_load_agents_md_without_microagents_dir(temp_dir_with_agents_md_only):
- """Test loading AGENTS.md file when .openhands/microagents directory doesn't exist."""
- # Try to load from non-existent microagents directory
- microagents_dir = temp_dir_with_agents_md_only / '.openhands' / 'microagents'
-
- repo_agents, knowledge_agents = load_microagents_from_dir(microagents_dir)
-
- # This should find the AGENTS.md file even though microagents_dir doesn't exist
- assert len(repo_agents) == 1 # Only AGENTS.md
- assert 'agents' in repo_agents
- assert len(knowledge_agents) == 0
-
- # Check AGENTS.md agent
- agents_agent = repo_agents['agents']
- assert isinstance(agents_agent, RepoMicroagent)
- assert agents_agent.name == 'agents'
- assert 'Install deps: `poetry install`' in agents_agent.content
- assert agents_agent.type == MicroagentType.REPO_KNOWLEDGE
-
-
-def temp_dir_with_both_cursorrules_and_agents():
- """Create a temporary directory with both .cursorrules and AGENTS.md files."""
- with tempfile.TemporaryDirectory() as temp_dir:
- root = Path(temp_dir)
-
- # Create .cursorrules file
- cursorrules_content = """Always use Python for new files.
-Follow PEP 8 style guidelines."""
- (root / '.cursorrules').write_text(cursorrules_content)
-
- # Create AGENTS.md file
- agents_content = """# Development Guide
-
-## Setup commands
-
-- Install deps: `poetry install`
-- Run tests: `poetry run pytest`"""
- (root / 'AGENTS.md').write_text(agents_content)
-
- yield root
-
-
-def test_load_both_cursorrules_and_agents_md(temp_dir_with_both_cursorrules_and_agents):
- """Test loading both .cursorrules and AGENTS.md files when .openhands/microagents doesn't exist."""
- # Try to load from non-existent microagents directory
- microagents_dir = (
- temp_dir_with_both_cursorrules_and_agents / '.openhands' / 'microagents'
- )
-
- repo_agents, knowledge_agents = load_microagents_from_dir(microagents_dir)
-
- # This should find both files
- assert len(repo_agents) == 2 # .cursorrules + AGENTS.md
- assert 'cursorrules' in repo_agents
- assert 'agents' in repo_agents
- assert len(knowledge_agents) == 0
-
- # Check both agents
- cursorrules_agent = repo_agents['cursorrules']
- assert isinstance(cursorrules_agent, RepoMicroagent)
- assert 'Always use Python for new files' in cursorrules_agent.content
-
- agents_agent = repo_agents['agents']
- assert isinstance(agents_agent, RepoMicroagent)
- assert 'Install deps: `poetry install`' in agents_agent.content
diff --git a/tests/unit/runtime/test_runtime_gitlab_microagents.py b/tests/unit/runtime/test_runtime_gitlab_microagents.py
deleted file mode 100644
index 8226fde19b..0000000000
--- a/tests/unit/runtime/test_runtime_gitlab_microagents.py
+++ /dev/null
@@ -1,346 +0,0 @@
-"""Tests for GitLab alternative directory support for microagents."""
-
-import tempfile
-from pathlib import Path
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-from openhands.core.config import OpenHandsConfig, SandboxConfig
-from openhands.events import EventStream
-from openhands.integrations.service_types import ProviderType, Repository
-from openhands.llm.llm_registry import LLMRegistry
-from openhands.microagent.microagent import (
- RepoMicroagent,
-)
-from openhands.runtime.base import Runtime
-from openhands.storage import get_file_store
-
-
-class MockRuntime(Runtime):
- """Mock runtime for testing."""
-
- def __init__(self, workspace_root: Path):
- # Create a minimal config for testing
- config = OpenHandsConfig()
- config.workspace_mount_path_in_sandbox = str(workspace_root)
- config.sandbox = SandboxConfig()
-
- # Create a mock event stream and file store
- file_store = get_file_store('local', str(workspace_root))
- event_stream = MagicMock(spec=EventStream)
- event_stream.file_store = file_store
-
- # Create a mock LLM registry
- llm_registry = LLMRegistry(config)
-
- # Initialize the parent class properly
- super().__init__(
- config=config,
- event_stream=event_stream,
- llm_registry=llm_registry,
- sid='test',
- git_provider_tokens={},
- )
-
- self._workspace_root = workspace_root
- self._logs = []
-
- @property
- def workspace_root(self) -> Path:
- """Return the workspace root path."""
- return self._workspace_root
-
- def log(self, level: str, message: str):
- """Mock log method."""
- self._logs.append((level, message))
-
- def run_action(self, action):
- """Mock run_action method."""
- # For testing, we'll simulate successful cloning
- from openhands.events.observation import CmdOutputObservation
-
- return CmdOutputObservation(content='', exit_code=0)
-
- def read(self, action):
- """Mock read method."""
- from openhands.events.observation import ErrorObservation
-
- return ErrorObservation('File not found')
-
- def _load_microagents_from_directory(self, directory: Path, source: str):
- """Mock microagent loading."""
- if not directory.exists():
- return []
-
- # Create mock microagents based on directory structure
- microagents = []
- for md_file in directory.rglob('*.md'):
- if md_file.name == 'README.md':
- continue
-
- # Create a simple mock microagent
- from openhands.microagent.types import MicroagentMetadata, MicroagentType
-
- agent = RepoMicroagent(
- name=f'mock_{md_file.stem}',
- content=f'Mock content from {md_file}',
- metadata=MicroagentMetadata(name=f'mock_{md_file.stem}'),
- source=str(md_file),
- type=MicroagentType.REPO_KNOWLEDGE,
- )
- microagents.append(agent)
-
- return microagents
-
- # Implement abstract methods with minimal functionality
- def connect(self):
- pass
-
- def run(self, action):
- from openhands.events.observation import CmdOutputObservation
-
- return CmdOutputObservation(content='', exit_code=0)
-
- def run_ipython(self, action):
- from openhands.events.observation import IPythonRunCellObservation
-
- return IPythonRunCellObservation(content='', code='')
-
- def edit(self, action):
- from openhands.events.observation import FileEditObservation
-
- return FileEditObservation(content='', path='')
-
- def browse(self, action):
- from openhands.events.observation import BrowserObservation
-
- return BrowserObservation(content='', url='', screenshot='')
-
- def browse_interactive(self, action):
- from openhands.events.observation import BrowserObservation
-
- return BrowserObservation(content='', url='', screenshot='')
-
- def write(self, action):
- from openhands.events.observation import FileWriteObservation
-
- return FileWriteObservation(content='', path='')
-
- def copy_to(self, host_src, sandbox_dest, recursive=False):
- pass
-
- def copy_from(self, sandbox_src, host_dest, recursive=False):
- pass
-
- def list_files(self, path=None):
- return []
-
- def get_mcp_config(self, extra_stdio_servers=None):
- from openhands.core.config.mcp_config import MCPConfig
-
- return MCPConfig()
-
- def call_tool_mcp(self, action):
- from openhands.events.observation import MCPObservation
-
- return MCPObservation(content='', tool='', result='')
-
-
-def create_test_microagents(base_dir: Path, config_dir_name: str = '.openhands'):
- """Create test microagent files in the specified directory."""
- microagents_dir = base_dir / config_dir_name / 'microagents'
- microagents_dir.mkdir(parents=True, exist_ok=True)
-
- # Create a test microagent
- test_agent = """---
-name: test_agent
-type: repo
-version: 1.0.0
-agent: CodeActAgent
----
-
-# Test Agent
-
-This is a test microagent.
-"""
- (microagents_dir / 'test.md').write_text(test_agent)
- return microagents_dir
-
-
-def temp_workspace():
- """Create a temporary workspace directory."""
- with tempfile.TemporaryDirectory() as temp_dir:
- yield Path(temp_dir)
-
-
-def test_is_gitlab_repository_github(temp_workspace):
- """Test that GitHub repositories are correctly identified as non-GitLab."""
- runtime = MockRuntime(temp_workspace)
-
- # Mock the provider handler to return GitHub
- mock_repo = Repository(
- id='123',
- full_name='owner/repo',
- git_provider=ProviderType.GITHUB,
- is_public=True,
- )
-
- with patch('openhands.runtime.base.ProviderHandler') as mock_handler_class:
- mock_handler = MagicMock()
- mock_handler_class.return_value = mock_handler
-
- with patch('openhands.runtime.base.call_async_from_sync') as mock_async:
- mock_async.return_value = mock_repo
-
- result = runtime._is_gitlab_repository('github.com/owner/repo')
- assert result is False
-
-
-def test_is_gitlab_repository_gitlab(temp_workspace):
- """Test that GitLab repositories are correctly identified."""
- runtime = MockRuntime(temp_workspace)
-
- # Mock the provider handler to return GitLab
- mock_repo = Repository(
- id='456',
- full_name='owner/repo',
- git_provider=ProviderType.GITLAB,
- is_public=True,
- )
-
- with patch('openhands.runtime.base.ProviderHandler') as mock_handler_class:
- mock_handler = MagicMock()
- mock_handler_class.return_value = mock_handler
-
- with patch('openhands.runtime.base.call_async_from_sync') as mock_async:
- mock_async.return_value = mock_repo
-
- result = runtime._is_gitlab_repository('gitlab.com/owner/repo')
- assert result is True
-
-
-def test_is_gitlab_repository_exception(temp_workspace):
- """Test that exceptions in provider detection return False."""
- runtime = MockRuntime(temp_workspace)
-
- with patch('openhands.runtime.base.ProviderHandler') as mock_handler_class:
- mock_handler_class.side_effect = Exception('Provider error')
-
- result = runtime._is_gitlab_repository('unknown.com/owner/repo')
- assert result is False
-
-
-def test_get_microagents_from_org_or_user_github(temp_workspace):
- """Test that GitHub repositories only try .openhands directory."""
- runtime = MockRuntime(temp_workspace)
-
- # Mock the provider detection to return GitHub
- with patch.object(runtime, '_is_gitlab_repository', return_value=False):
- with patch.object(runtime, '_is_azure_devops_repository', return_value=False):
- # Mock the _get_authenticated_git_url to simulate failure (no org repo)
- with patch('openhands.runtime.base.call_async_from_sync') as mock_async:
- mock_async.side_effect = Exception('Repository not found')
-
- result = runtime.get_microagents_from_org_or_user(
- 'github.com/owner/repo'
- )
-
- # Should only try .openhands, not openhands-config
- assert len(result) == 0
- # Check that only one attempt was made (for .openhands)
- assert mock_async.call_count == 1
-
-
-def test_get_microagents_from_org_or_user_gitlab_success_with_config(temp_workspace):
- """Test that GitLab repositories use openhands-config and succeed."""
- runtime = MockRuntime(temp_workspace)
-
- # Create a mock org directory with microagents
- org_dir = temp_workspace / 'org_openhands_owner'
- create_test_microagents(org_dir, '.') # Create microagents directly in org_dir
-
- # Mock the provider detection to return GitLab
- with patch.object(runtime, '_is_gitlab_repository', return_value=True):
- with patch.object(runtime, '_is_azure_devops_repository', return_value=False):
- # Mock successful cloning for openhands-config
- with patch('openhands.runtime.base.call_async_from_sync') as mock_async:
- mock_async.return_value = (
- 'https://gitlab.com/owner/openhands-config.git'
- )
-
- result = runtime.get_microagents_from_org_or_user(
- 'gitlab.com/owner/repo'
- )
-
- # Should succeed with openhands-config
- assert len(result) >= 0 # May be empty if no microagents found
- # Should only try once for openhands-config
- assert mock_async.call_count == 1
-
-
-def test_get_microagents_from_org_or_user_gitlab_failure(temp_workspace):
- """Test that GitLab repositories handle failure gracefully when openhands-config doesn't exist."""
- runtime = MockRuntime(temp_workspace)
-
- # Mock the provider detection to return GitLab
- with patch.object(runtime, '_is_gitlab_repository', return_value=True):
- with patch.object(runtime, '_is_azure_devops_repository', return_value=False):
- # Mock the _get_authenticated_git_url to fail for openhands-config
- with patch('openhands.runtime.base.call_async_from_sync') as mock_async:
- mock_async.side_effect = Exception('openhands-config not found')
-
- result = runtime.get_microagents_from_org_or_user(
- 'gitlab.com/owner/repo'
- )
-
- # Should return empty list when repository doesn't exist
- assert len(result) == 0
- # Should only try once for openhands-config
- assert mock_async.call_count == 1
-
-
-def test_get_microagents_from_selected_repo_gitlab_uses_openhands(temp_workspace):
- """Test that GitLab repositories use .openhands directory for repository-specific microagents."""
- runtime = MockRuntime(temp_workspace)
-
- # Create a repository directory structure
- repo_dir = temp_workspace / 'repo'
- repo_dir.mkdir()
-
- # Create microagents in .openhands directory
- create_test_microagents(repo_dir, '.openhands')
-
- # Mock the provider detection to return GitLab
- with patch.object(runtime, '_is_gitlab_repository', return_value=True):
- # Mock org-level microagents (empty)
- with patch.object(runtime, 'get_microagents_from_org_or_user', return_value=[]):
- result = runtime.get_microagents_from_selected_repo('gitlab.com/owner/repo')
-
- # Should find microagents from .openhands directory
- # The exact assertion depends on the mock implementation
- # At minimum, it should not raise an exception
- assert isinstance(result, list)
-
-
-def test_get_microagents_from_selected_repo_github_only_openhands(temp_workspace):
- """Test that GitHub repositories only check .openhands directory."""
- runtime = MockRuntime(temp_workspace)
-
- # Create a repository directory structure
- repo_dir = temp_workspace / 'repo'
- repo_dir.mkdir()
-
- # Create microagents in both directories
- create_test_microagents(repo_dir, 'openhands-config')
- create_test_microagents(repo_dir, '.openhands')
-
- # Mock the provider detection to return GitHub
- with patch.object(runtime, '_is_gitlab_repository', return_value=False):
- # Mock org-level microagents (empty)
- with patch.object(runtime, 'get_microagents_from_org_or_user', return_value=[]):
- result = runtime.get_microagents_from_selected_repo('github.com/owner/repo')
-
- # Should only check .openhands directory, not openhands-config
- assert isinstance(result, list)