Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat(backend): load skills from agent server (#12434)

Hiep Le743f6256a690
diff --git a/frontend/src/api/conversation-service/v1-conversation-service.types.ts b/frontend/src/api/conversation-service/v1-conversation-service.types.ts
index 8aa5ed105e..35684efcc0 100644
--- a/frontend/src/api/conversation-service/v1-conversation-service.types.ts
+++ b/frontend/src/api/conversation-service/v1-conversation-service.types.ts
@@ -103,7 +103,7 @@ export interface V1AppConversation {
export interface Skill {
name: string;
- type: "repo" | "knowledge";
+ type: "repo" | "knowledge" | "agentskills";
content: string;
triggers: string[];
}
diff --git a/frontend/src/api/open-hands.types.ts b/frontend/src/api/open-hands.types.ts
index 02247c57d9..f177e1f753 100644
--- a/frontend/src/api/open-hands.types.ts
+++ b/frontend/src/api/open-hands.types.ts
@@ -110,7 +110,7 @@ export interface InputMetadata {
export interface Microagent {
name: string;
- type: "repo" | "knowledge";
+ type: "repo" | "knowledge" | "agentskills";
content: string;
triggers: string[];
}
diff --git a/frontend/src/components/features/conversation-panel/skill-item.tsx b/frontend/src/components/features/conversation-panel/skill-item.tsx
index c76bf10be9..2a57e9e8f8 100644
--- a/frontend/src/components/features/conversation-panel/skill-item.tsx
+++ b/frontend/src/components/features/conversation-panel/skill-item.tsx
@@ -11,6 +11,15 @@ interface SkillItemProps {
}
export function SkillItem({ skill, isExpanded, onToggle }: SkillItemProps) {
+ let skillTypeLabel: string;
+ if (skill.type === "repo") {
+ skillTypeLabel = "Repository";
+ } else if (skill.type === "knowledge") {
+ skillTypeLabel = "Knowledge";
+ } else {
+ skillTypeLabel = "AgentSkills";
+ }
+
return (
<div className="rounded-md overflow-hidden">
<button
@@ -25,7 +34,7 @@ export function SkillItem({ skill, isExpanded, onToggle }: SkillItemProps) {
</div>
<div className="flex items-center">
<Typography.Text className="px-2 py-1 text-xs rounded-full bg-gray-800 mr-2">
- {skill.type === "repo" ? "Repository" : "Knowledge"}
+ {skillTypeLabel}
</Typography.Text>
<Typography.Text className="text-gray-300">
{isExpanded ? (
diff --git a/openhands/app_server/app_conversation/app_conversation_models.py b/openhands/app_server/app_conversation/app_conversation_models.py
index de0c8db769..a2dcdd7314 100644
--- a/openhands/app_server/app_conversation/app_conversation_models.py
+++ b/openhands/app_server/app_conversation/app_conversation_models.py
@@ -176,6 +176,6 @@ class SkillResponse(BaseModel):
"""Response model for skills endpoint."""
name: str
- type: Literal['repo', 'knowledge']
+ type: Literal['repo', 'knowledge', 'agentskills']
content: str
triggers: list[str] = []
diff --git a/openhands/app_server/app_conversation/app_conversation_router.py b/openhands/app_server/app_conversation/app_conversation_router.py
index 89f9d2699c..eae1c5e36e 100644
--- a/openhands/app_server/app_conversation/app_conversation_router.py
+++ b/openhands/app_server/app_conversation/app_conversation_router.py
@@ -503,13 +503,6 @@ async def get_conversation_skills(
agent_server_url = replace_localhost_hostname_for_docker(agent_server_url)
- # Create remote workspace
- remote_workspace = AsyncRemoteWorkspace(
- host=agent_server_url,
- api_key=sandbox.session_api_key,
- working_dir=sandbox_spec.working_dir,
- )
-
# Load skills from all sources
logger.info(f'Loading skills for conversation {conversation_id}')
@@ -518,9 +511,9 @@ async def get_conversation_skills(
if isinstance(app_conversation_service, AppConversationServiceBase):
all_skills = await app_conversation_service.load_and_merge_all_skills(
sandbox,
- remote_workspace,
conversation.selected_repository,
sandbox_spec.working_dir,
+ agent_server_url,
)
logger.info(
@@ -531,9 +524,11 @@ async def get_conversation_skills(
# Transform skills to response format
skills_response = []
for skill in all_skills:
- # Determine type based on trigger
- skill_type: Literal['repo', 'knowledge']
- if skill.trigger is None:
+ # Determine type based on AgentSkills format and trigger
+ skill_type: Literal['repo', 'knowledge', 'agentskills']
+ if skill.is_agentskills_format:
+ skill_type = 'agentskills'
+ elif skill.trigger is None:
skill_type = 'repo'
else:
skill_type = 'knowledge'
diff --git a/openhands/app_server/app_conversation/app_conversation_service.py b/openhands/app_server/app_conversation/app_conversation_service.py
index dd98dd44c9..bff19b0fa7 100644
--- a/openhands/app_server/app_conversation/app_conversation_service.py
+++ b/openhands/app_server/app_conversation/app_conversation_service.py
@@ -95,6 +95,7 @@ class AppConversationService(ABC):
task: AppConversationStartTask,
sandbox: SandboxInfo,
workspace: AsyncRemoteWorkspace,
+ agent_server_url: str,
) -> AsyncGenerator[AppConversationStartTask, None]:
"""Run the setup scripts for the project and yield status updates"""
yield task
diff --git a/openhands/app_server/app_conversation/app_conversation_service_base.py b/openhands/app_server/app_conversation/app_conversation_service_base.py
index 87a8a15e3d..1ccff099e6 100644
--- a/openhands/app_server/app_conversation/app_conversation_service_base.py
+++ b/openhands/app_server/app_conversation/app_conversation_service_base.py
@@ -21,18 +21,16 @@ from openhands.app_server.app_conversation.app_conversation_service import (
AppConversationService,
)
from openhands.app_server.app_conversation.skill_loader import (
- load_global_skills,
- load_org_skills,
- load_repo_skills,
- load_sandbox_skills,
- merge_skills,
+ build_org_config,
+ build_sandbox_config,
+ load_skills_from_agent_server,
)
from openhands.app_server.sandbox.sandbox_models import SandboxInfo
from openhands.app_server.user.user_context import UserContext
from openhands.sdk import Agent
from openhands.sdk.context.agent_context import AgentContext
from openhands.sdk.context.condenser import LLMSummarizingCondenser
-from openhands.sdk.context.skills import load_user_skills
+from openhands.sdk.context.skills import Skill
from openhands.sdk.llm import LLM
from openhands.sdk.security.analyzer import SecurityAnalyzerBase
from openhands.sdk.security.confirmation_policy import (
@@ -61,67 +59,74 @@ class AppConversationServiceBase(AppConversationService, ABC):
async def load_and_merge_all_skills(
self,
sandbox: SandboxInfo,
- remote_workspace: AsyncRemoteWorkspace,
selected_repository: str | None,
working_dir: str,
- ) -> list:
- """Load skills from all sources and merge them.
+ agent_server_url: str,
+ ) -> list[Skill]:
+ """Load skills from all sources via the agent-server.
- This method handles all errors gracefully and will return an empty list
- if skill loading fails completely.
+ This method calls the agent-server's /api/skills endpoint to load and
+ merge skills from all sources. The agent-server handles:
+ - Public skills (from OpenHands/skills GitHub repo)
+ - User skills (from ~/.openhands/skills/)
+ - Organization skills (from {org}/.openhands repo)
+ - Project/repo skills (from workspace .openhands/skills/)
+ - Sandbox skills (from exposed URLs)
Args:
- remote_workspace: AsyncRemoteWorkspace for loading repo skills
+ sandbox: SandboxInfo containing exposed URLs and agent-server URL
selected_repository: Repository name or None
working_dir: Working directory path
+ agent_server_url: Agent-server URL (required)
Returns:
List of merged Skill objects from all sources, or empty list on failure
"""
try:
- _logger.debug('Loading skills for V1 conversation')
-
- # Load skills from all sources
- sandbox_skills = load_sandbox_skills(sandbox)
- global_skills = load_global_skills()
- # Load user skills from ~/.openhands/skills/ directory
- # Uses the SDK's load_user_skills() function which handles loading from
- # ~/.openhands/skills/ and ~/.openhands/microagents/ (for backward compatibility)
- try:
- user_skills = load_user_skills()
- _logger.info(
- f'Loaded {len(user_skills)} user skills: {[s.name for s in user_skills]}'
- )
- except Exception as e:
- _logger.warning(f'Failed to load user skills: {str(e)}')
- user_skills = []
-
- # Load organization-level skills
- org_skills = await load_org_skills(
- remote_workspace, selected_repository, working_dir, self.user_context
- )
-
- repo_skills = await load_repo_skills(
- remote_workspace, selected_repository, working_dir
- )
-
- # Merge all skills (later lists override earlier ones)
- # Precedence: sandbox < global < user < org < repo
- all_skills = merge_skills(
- [sandbox_skills, global_skills, user_skills, org_skills, repo_skills]
+ _logger.debug('Loading skills for V1 conversation via agent-server')
+
+ if not agent_server_url:
+ _logger.warning('No agent-server URL available, cannot load skills')
+ return []
+
+ # Build org config (authentication handled by app-server)
+ org_config = await build_org_config(selected_repository, self.user_context)
+
+ # Build sandbox config (exposed URLs)
+ sandbox_config = build_sandbox_config(sandbox)
+
+ # Determine project directory for project skills
+ project_dir = working_dir
+ if selected_repository:
+ repo_name = selected_repository.split('/')[-1]
+ project_dir = f'{working_dir}/{repo_name}'
+
+ # Single API call to agent-server for ALL skills
+ all_skills = await load_skills_from_agent_server(
+ agent_server_url=agent_server_url,
+ session_api_key=sandbox.session_api_key,
+ project_dir=project_dir,
+ org_config=org_config,
+ sandbox_config=sandbox_config,
+ load_public=True,
+ load_user=True,
+ load_project=True,
+ load_org=True,
)
_logger.info(
- f'Loaded {len(all_skills)} total skills: {[s.name for s in all_skills]}'
+ f'Loaded {len(all_skills)} total skills from agent-server: '
+ f'{[s.name for s in all_skills]}'
)
return all_skills
+
except Exception as e:
_logger.warning(f'Failed to load skills: {e}', exc_info=True)
# Return empty list on failure - skills will be loaded again later if needed
return []
- def _create_agent_with_skills(self, agent, skills: list):
+ def _create_agent_with_skills(self, agent, skills: list[Skill]):
"""Create or update agent with skills in its context.
Args:
@@ -132,9 +137,9 @@ class AppConversationServiceBase(AppConversationService, ABC):
Updated agent with skills in context
"""
if agent.agent_context:
- # Merge with existing context
+ # Merge with existing context (new skills override existing ones)
existing_skills = agent.agent_context.skills
- all_skills = merge_skills([skills, existing_skills])
+ all_skills = self._merge_skills([existing_skills, skills])
agent = agent.model_copy(
update={
'agent_context': agent.agent_context.model_copy(
@@ -149,6 +154,25 @@ class AppConversationServiceBase(AppConversationService, ABC):
return agent
+ def _merge_skills(self, skill_lists: list[list[Skill]]) -> list[Skill]:
+ """Merge multiple skill lists, avoiding duplicates by name.
+
+ Later lists take precedence over earlier lists for duplicate names.
+
+ Args:
+ skill_lists: List of skill lists to merge
+
+ Returns:
+ Deduplicated list of skills with later lists overriding earlier ones
+ """
+ skills_by_name: dict[str, Skill] = {}
+
+ for skill_list in skill_lists:
+ for skill in skill_list:
+ skills_by_name[skill.name] = skill
+
+ return list(skills_by_name.values())
+
async def _load_skills_and_update_agent(
self,
sandbox: SandboxInfo,
@@ -169,8 +193,10 @@ class AppConversationServiceBase(AppConversationService, ABC):
Updated agent with skills loaded into context
"""
# Load and merge all skills
+ # Extract agent_server_url from remote_workspace host
+ agent_server_url = remote_workspace.host
all_skills = await self.load_and_merge_all_skills(
- sandbox, remote_workspace, selected_repository, working_dir
+ sandbox, selected_repository, working_dir, agent_server_url
)
# Update agent with skills
@@ -183,6 +209,7 @@ class AppConversationServiceBase(AppConversationService, ABC):
task: AppConversationStartTask,
sandbox: SandboxInfo,
workspace: AsyncRemoteWorkspace,
+ agent_server_url: str,
) -> AsyncGenerator[AppConversationStartTask, None]:
task.status = AppConversationStartTaskStatus.PREPARING_REPOSITORY
yield task
@@ -200,9 +227,9 @@ class AppConversationServiceBase(AppConversationService, ABC):
yield task
await self.load_and_merge_all_skills(
sandbox,
- workspace,
task.request.selected_repository,
workspace.working_dir,
+ agent_server_url,
)
async def _configure_git_user_settings(
diff --git a/openhands/app_server/app_conversation/live_status_app_conversation_service.py b/openhands/app_server/app_conversation/live_status_app_conversation_service.py
index 7102f6aeb6..c3d2d81c58 100644
--- a/openhands/app_server/app_conversation/live_status_app_conversation_service.py
+++ b/openhands/app_server/app_conversation/live_status_app_conversation_service.py
@@ -237,7 +237,7 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
working_dir=sandbox_spec.working_dir,
)
async for updated_task in self.run_setup_scripts(
- task, sandbox, remote_workspace
+ task, sandbox, remote_workspace, agent_server_url
):
yield updated_task
diff --git a/openhands/app_server/app_conversation/skill_loader.py b/openhands/app_server/app_conversation/skill_loader.py
index c1cf5df327..3638c6e681 100644
--- a/openhands/app_server/app_conversation/skill_loader.py
+++ b/openhands/app_server/app_conversation/skill_loader.py
@@ -1,34 +1,37 @@
"""Utilities for loading skills for V1 conversations.
-This module provides functions to load skills from various sources:
-- Global skills from OpenHands/skills/
-- User skills from ~/.openhands/skills/
-- Repository-level skills from the workspace
-
-All skills are used in V1 conversations.
+This module provides functions to load skills from the agent-server,
+which centralizes all skill loading logic. The app-server acts as a
+thin proxy that:
+1. Builds the org_config with authentication information
+2. Builds the sandbox_config with exposed URLs
+3. Calls the agent-server's /api/skills endpoint
+
+All source-specific skill loading is handled by the agent-server.
"""
import logging
-import os
-from pathlib import Path
-import openhands
+import httpx
+from pydantic import BaseModel
+
from openhands.app_server.sandbox.sandbox_models import SandboxInfo
from openhands.app_server.user.user_context import UserContext
from openhands.integrations.provider import ProviderType
from openhands.integrations.service_types import AuthenticationError
from openhands.sdk.context.skills import Skill
-from openhands.sdk.workspace.remote.async_remote_workspace import AsyncRemoteWorkspace
+from openhands.sdk.context.skills.trigger import KeywordTrigger, TaskTrigger
_logger = logging.getLogger(__name__)
-# Path to global skills directory
-GLOBAL_SKILLS_DIR = os.path.join(
- os.path.dirname(os.path.dirname(openhands.__file__)),
- 'skills',
-)
-WORK_HOSTS_SKILL = """The user has access to the following hosts for accessing a web application,
-each of which has a corresponding port:"""
+
+class ExposedUrlConfig(BaseModel):
+ """Configuration for an exposed URL in sandbox config."""
+
+ name: str
+ url: str
+ port: int
+
WORK_HOSTS_SKILL_FOOTER = """
When starting a web server, use the corresponding ports via environment variables:
@@ -45,96 +48,30 @@ app.run(host='0.0.0.0', port=int(os.environ.get('WORKER_1', 12000)))
```"""
-def _find_and_load_global_skill_files(skill_dir: Path) -> list[Skill]:
- """Find and load all .md files from the global skills directory.
-
- Args:
- skill_dir: Path to the global skills directory
-
- Returns:
- List of Skill objects loaded from the files (excluding README.md)
- """
- skills = []
-
- try:
- # Find all .md files in the directory (excluding README.md)
- md_files = [f for f in skill_dir.glob('*.md') if f.name.lower() != 'readme.md']
-
- # Load skills from the found files
- for file_path in md_files:
- try:
- skill = Skill.load(file_path, skill_dir)
- skills.append(skill)
- _logger.debug(f'Loaded global skill: {skill.name} from {file_path}')
- except Exception as e:
- _logger.warning(
- f'Failed to load global skill from {file_path}: {str(e)}'
- )
-
- except Exception as e:
- _logger.debug(f'Failed to find global skill files: {str(e)}')
-
- return skills
-
-
-def load_sandbox_skills(sandbox: SandboxInfo) -> list[Skill]:
- """Load skills specific to the sandbox, including exposed ports / urls."""
- if not sandbox.exposed_urls:
- return []
- urls = [url for url in sandbox.exposed_urls if url.name.startswith('WORKER_')]
- if not urls:
- return []
- content_list = [WORK_HOSTS_SKILL]
- for url in urls:
- content_list.append(f'* {url.url} (port {url.port})')
- content_list.append(WORK_HOSTS_SKILL_FOOTER)
- content = '\n'.join(content_list)
- return [Skill(name='work_hosts', content=content, trigger=None)]
-
-
-def load_global_skills() -> list[Skill]:
- """Load global skills from OpenHands/skills/ directory.
-
- Returns:
- List of Skill objects loaded from global skills directory.
- Returns empty list if directory doesn't exist or on errors.
- """
- skill_dir = Path(GLOBAL_SKILLS_DIR)
-
- # Check if directory exists
- if not skill_dir.exists():
- _logger.debug(f'Global skills directory does not exist: {skill_dir}')
- return []
-
- try:
- _logger.info(f'Loading global skills from {skill_dir}')
-
- # Find and load all .md files from the directory
- skills = _find_and_load_global_skill_files(skill_dir)
+class SandboxConfig(BaseModel):
+ """Sandbox configuration for agent-server API request."""
- _logger.info(f'Loaded {len(skills)} global skills: {[s.name for s in skills]}')
+ exposed_urls: list[ExposedUrlConfig]
- return skills
- except Exception as e:
- _logger.warning(f'Failed to load global skills: {str(e)}')
- return []
+class OrgConfig(BaseModel):
+ """Organization configuration for agent-server API request."""
+ repository: str
+ provider: str
+ org_repo_url: str
+ org_name: str
-def _determine_repo_root(working_dir: str, selected_repository: str | None) -> str:
- """Determine the repository root directory.
- Args:
- working_dir: Base working directory path
- selected_repository: Repository name (e.g., 'owner/repo') or None
+class SkillInfo(BaseModel):
+ """Skill information from agent-server API response."""
- Returns:
- Path to the repository root directory
- """
- if selected_repository:
- repo_name = selected_repository.split('/')[-1]
- return f'{working_dir}/{repo_name}'
- return working_dir
+ name: str
+ content: str
+ triggers: list[str] = []
+ source: str | None = None
+ description: str | None = None
+ is_agentskills_format: bool = False
async def _is_gitlab_repository(repo_name: str, user_context: UserContext) -> bool:
@@ -154,8 +91,6 @@ async def _is_gitlab_repository(repo_name: str, user_context: UserContext) -> bo
)
return repository.git_provider == ProviderType.GITLAB
except Exception:
- # If we can't determine the provider, assume it's not GitLab
- # This is a safe fallback since we'll just use the default .openhands
return False
@@ -178,10 +113,33 @@ async def _is_azure_devops_repository(
)
return repository.git_provider == ProviderType.AZURE_DEVOPS
except Exception:
- # If we can't determine the provider, assume it's not Azure DevOps
return False
+async def _get_provider_type(
+ selected_repository: str, user_context: UserContext
+) -> str:
+ """Determine the Git provider type for a repository.
+
+ Args:
+ selected_repository: Repository name (e.g., 'owner/repo')
+ user_context: UserContext to access provider handler
+
+ Returns:
+ Provider type string: 'github', 'gitlab', 'azure', or 'bitbucket'
+ """
+ is_gitlab = await _is_gitlab_repository(selected_repository, user_context)
+ if is_gitlab:
+ return 'gitlab'
+
+ is_azure = await _is_azure_devops_repository(selected_repository, user_context)
+ if is_azure:
+ return 'azure'
+
+ # Default to github (covers github and bitbucket)
+ return 'github'
+
+
async def _determine_org_repo_path(
selected_repository: str, user_context: UserContext
) -> tuple[str, str]:
@@ -203,27 +161,19 @@ async def _determine_org_repo_path(
"""
repo_parts = selected_repository.split('/')
- # Determine repository type
is_azure_devops = await _is_azure_devops_repository(
selected_repository, user_context
)
is_gitlab = await _is_gitlab_repository(selected_repository, user_context)
- # 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
+ org_name = repo_parts[0]
else:
- org_name = repo_parts[-2] # Get owner from owner/repo
+ org_name = repo_parts[-2]
- # 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'
@@ -231,227 +181,6 @@ async def _determine_org_repo_path(
return org_openhands_repo, org_name
-async def _read_file_from_workspace(
- workspace: AsyncRemoteWorkspace, file_path: str, working_dir: str
-) -> str | None:
- """Read file content from remote workspace.
-
- Args:
- workspace: AsyncRemoteWorkspace to execute commands
- file_path: Path to the file to read
- working_dir: Working directory for command execution
-
- Returns:
- File content as string, or None if file doesn't exist or read fails
- """
- try:
- result = await workspace.execute_command(
- f'cat {file_path}', cwd=working_dir, timeout=10.0
- )
- if result.exit_code == 0 and result.stdout.strip():
- return result.stdout
- return None
- except Exception as e:
- _logger.debug(f'Failed to read file {file_path}: {str(e)}')
- return None
-
-
-async def _load_special_files(
- workspace: AsyncRemoteWorkspace, repo_root: str, working_dir: str
-) -> list[Skill]:
- """Load special skill files from repository root.
-
- Loads: .cursorrules, agents.md, agent.md
-
- Args:
- workspace: AsyncRemoteWorkspace to execute commands
- repo_root: Path to repository root directory
- working_dir: Working directory for command execution
-
- Returns:
- List of Skill objects loaded from special files
- """
- skills = []
- special_files = ['.cursorrules', 'agents.md', 'agent.md']
-
- for filename in special_files:
- file_path = f'{repo_root}/{filename}'
- content = await _read_file_from_workspace(workspace, file_path, working_dir)
-
- if content:
- try:
- # Use simple string path to avoid Path filesystem operations
- skill = Skill.load(path=filename, skill_dir=None, file_content=content)
- skills.append(skill)
- _logger.debug(f'Loaded special file skill: {skill.name}')
- except Exception as e:
- _logger.warning(f'Failed to create skill from {filename}: {str(e)}')
-
- return skills
-
-
-async def _find_and_load_skill_md_files(
- workspace: AsyncRemoteWorkspace, skill_dir: str, working_dir: str
-) -> list[Skill]:
- """Find and load all .md files from a skills directory in the workspace.
-
- Args:
- workspace: AsyncRemoteWorkspace to execute commands
- skill_dir: Path to skills directory
- working_dir: Working directory for command execution
-
- Returns:
- List of Skill objects loaded from the files (excluding README.md)
- """
- skills = []
-
- try:
- # Find all .md files in the directory
- result = await workspace.execute_command(
- f"find {skill_dir} -type f -name '*.md' 2>/dev/null || true",
- cwd=working_dir,
- timeout=10.0,
- )
-
- if result.exit_code == 0 and result.stdout.strip():
- file_paths = [
- f.strip()
- for f in result.stdout.strip().split('\n')
- if f.strip() and 'README.md' not in f
- ]
-
- # Load skills from the found files
- for file_path in file_paths:
- content = await _read_file_from_workspace(
- workspace, file_path, working_dir
- )
-
- if content:
- # Calculate relative path for skill name
- rel_path = file_path.replace(f'{skill_dir}/', '')
- try:
- # Use simple string path to avoid Path filesystem operations
- skill = Skill.load(
- path=rel_path, skill_dir=None, file_content=content
- )
- skills.append(skill)
- _logger.debug(f'Loaded repo skill: {skill.name}')
- except Exception as e:
- _logger.warning(
- f'Failed to create skill from {rel_path}: {str(e)}'
- )
-
- except Exception as e:
- _logger.debug(f'Failed to find skill files in {skill_dir}: {str(e)}')
-
- return skills
-
-
-def _merge_repo_skills_with_precedence(
- special_skills: list[Skill],
- skills_dir_skills: list[Skill],
- microagents_dir_skills: list[Skill],
-) -> list[Skill]:
- """Merge repository skills with precedence order.
-
- Precedence (highest to lowest):
- 1. Special files (repo root)
- 2. .openhands/skills/ directory
- 3. .openhands/microagents/ directory (backward compatibility)
-
- Args:
- special_skills: Skills from special files in repo root
- skills_dir_skills: Skills from .openhands/skills/ directory
- microagents_dir_skills: Skills from .openhands/microagents/ directory
-
- Returns:
- Deduplicated list of skills with proper precedence
- """
- # Use a dict to deduplicate by name, with earlier sources taking precedence
- skills_by_name = {}
- for skill in special_skills + skills_dir_skills + microagents_dir_skills:
- # Only add if not already present (earlier sources win)
- if skill.name not in skills_by_name:
- skills_by_name[skill.name] = skill
-
- return list(skills_by_name.values())
-
-
-async def load_repo_skills(
- workspace: AsyncRemoteWorkspace,
- selected_repository: str | None,
- working_dir: str,
-) -> list[Skill]:
- """Load repository-level skills from the workspace.
-
- Loads skills from:
- 1. Special files in repo root: .cursorrules, agents.md, agent.md
- 2. .md files in .openhands/skills/ directory (preferred)
- 3. .md files in .openhands/microagents/ directory (for backward compatibility)
-
- Args:
- workspace: AsyncRemoteWorkspace to execute commands in the sandbox
- selected_repository: Repository name (e.g., 'owner/repo') or None
- working_dir: Working directory path
-
- Returns:
- List of Skill objects loaded from repository.
- Returns empty list on errors.
- """
- try:
- # Determine repository root directory
- repo_root = _determine_repo_root(working_dir, selected_repository)
- _logger.info(f'Loading repo skills from {repo_root}')
-
- # Load special files from repo root
- special_skills = await _load_special_files(workspace, repo_root, working_dir)
-
- # Load .md files from .openhands/skills/ directory (preferred)
- skills_dir = f'{repo_root}/.openhands/skills'
- skills_dir_skills = await _find_and_load_skill_md_files(
- workspace, skills_dir, working_dir
- )
-
- # Load .md files from .openhands/microagents/ directory (backward compatibility)
- microagents_dir = f'{repo_root}/.openhands/microagents'
- microagents_dir_skills = await _find_and_load_skill_md_files(
- workspace, microagents_dir, working_dir
- )
-
- # Merge all loaded skills with proper precedence
- all_skills = _merge_repo_skills_with_precedence(
- special_skills, skills_dir_skills, microagents_dir_skills
- )
-
- _logger.info(
- f'Loaded {len(all_skills)} repo skills: {[s.name for s in all_skills]}'
- )
-
- return all_skills
-
- except Exception as e:
- _logger.warning(f'Failed to load repo skills: {str(e)}')
- return []
-
-
-def _validate_repository_for_org_skills(selected_repository: str) -> bool:
- """Validate that the repository path has sufficient parts for org skills.
-
- Args:
- selected_repository: Repository name (e.g., 'owner/repo')
-
- Returns:
- True if repository is valid for org skills loading, False otherwise
- """
- repo_parts = selected_repository.split('/')
- if len(repo_parts) < 2:
- _logger.warning(
- f'Repository path has insufficient parts ({len(repo_parts)} < 2), skipping org-level skills'
- )
- return False
- return True
-
-
async def _get_org_repository_url(
org_openhands_repo: str, user_context: UserContext
) -> str | None:
@@ -481,224 +210,193 @@ async def _get_org_repository_url(
return None
-async def _clone_org_repository(
- workspace: AsyncRemoteWorkspace,
- remote_url: str,
- org_repo_dir: str,
- working_dir: str,
- org_openhands_repo: str,
-) -> bool:
- """Clone organization repository to temporary directory.
+async def build_org_config(
+ selected_repository: str | None,
+ user_context: UserContext,
+) -> OrgConfig | None:
+ """Build organization config for agent-server API request.
Args:
- workspace: AsyncRemoteWorkspace to execute commands
- remote_url: Authenticated Git URL
- org_repo_dir: Temporary directory path for cloning
- working_dir: Working directory for command execution
- org_openhands_repo: Organization repository path (for logging)
+ selected_repository: Repository name (e.g., 'owner/repo') or None
+ user_context: UserContext to access authentication and provider info
Returns:
- True if clone successful, False otherwise
+ org_config dict if org repository exists and is accessible, None otherwise
"""
- _logger.debug(f'Creating temporary directory for org repo: {org_repo_dir}')
-
- # Clone the repo (shallow clone for efficiency)
- clone_cmd = f'GIT_TERMINAL_PROMPT=0 git clone --depth 1 {remote_url} {org_repo_dir}'
- _logger.info('Executing clone command for org-level repo')
-
- result = await workspace.execute_command(clone_cmd, working_dir, timeout=120.0)
+ if not selected_repository:
+ return None
- if result.exit_code != 0:
- _logger.info(
- f'No org-level skills found at {org_openhands_repo} (exit_code: {result.exit_code})'
+ repo_parts = selected_repository.split('/')
+ if len(repo_parts) < 2:
+ _logger.warning(
+ f'Repository path has insufficient parts ({len(repo_parts)} < 2), '
+ f'skipping org-level skills'
)
- _logger.debug(f'Clone command output: {result.stderr}')
- return False
-
- _logger.info(f'Successfully cloned org-level skills from {org_openhands_repo}')
- return True
-
-
-async def _load_skills_from_org_directories(
- workspace: AsyncRemoteWorkspace, org_repo_dir: str, working_dir: str
-) -> tuple[list[Skill], list[Skill]]:
- """Load skills from both skills/ and microagents/ directories in org repo.
+ return None
- Args:
- workspace: AsyncRemoteWorkspace to execute commands
- org_repo_dir: Path to cloned organization repository
- working_dir: Working directory for command execution
+ try:
+ org_openhands_repo, org_name = await _determine_org_repo_path(
+ selected_repository, user_context
+ )
- Returns:
- Tuple of (skills_dir_skills, microagents_dir_skills)
- """
- skills_dir = f'{org_repo_dir}/skills'
- skills_dir_skills = await _find_and_load_skill_md_files(
- workspace, skills_dir, working_dir
- )
+ org_repo_url = await _get_org_repository_url(org_openhands_repo, user_context)
+ if not org_repo_url:
+ return None
- microagents_dir = f'{org_repo_dir}/microagents'
- microagents_dir_skills = await _find_and_load_skill_md_files(
- workspace, microagents_dir, working_dir
- )
+ provider = await _get_provider_type(selected_repository, user_context)
- return skills_dir_skills, microagents_dir_skills
+ return OrgConfig(
+ repository=selected_repository,
+ provider=provider,
+ org_repo_url=org_repo_url,
+ org_name=org_name,
+ )
+ except Exception as e:
+ _logger.debug(f'Failed to build org config: {str(e)}')
+ return None
-def _merge_org_skills_with_precedence(
- skills_dir_skills: list[Skill], microagents_dir_skills: list[Skill]
-) -> list[Skill]:
- """Merge skills from skills/ and microagents/ with proper precedence.
- Precedence: skills/ > microagents/ (skills/ overrides microagents/ for same name)
+def build_sandbox_config(sandbox: SandboxInfo) -> SandboxConfig | None:
+ """Build sandbox config for agent-server API request.
Args:
- skills_dir_skills: Skills loaded from skills/ directory
- microagents_dir_skills: Skills loaded from microagents/ directory
+ sandbox: SandboxInfo containing exposed URLs
Returns:
- Merged list of skills with proper precedence applied
+ sandbox_config dict if there are exposed URLs, None otherwise
"""
- skills_by_name = {}
- for skill in microagents_dir_skills + skills_dir_skills:
- # Later sources (skills/) override earlier ones (microagents/)
- if skill.name not in skills_by_name:
- skills_by_name[skill.name] = skill
- else:
- _logger.debug(
- f'Overriding org skill "{skill.name}" from microagents/ with skills/'
- )
- skills_by_name[skill.name] = skill
+ if not sandbox.exposed_urls:
+ return None
- return list(skills_by_name.values())
+ exposed_urls = [
+ ExposedUrlConfig(name=url.name, url=url.url, port=url.port)
+ for url in sandbox.exposed_urls
+ ]
+ return SandboxConfig(exposed_urls=exposed_urls)
-async def _cleanup_org_repository(
- workspace: AsyncRemoteWorkspace, org_repo_dir: str, working_dir: str
-) -> None:
- """Clean up cloned organization repository directory.
- Args:
- workspace: AsyncRemoteWorkspace to execute commands
- org_repo_dir: Path to cloned organization repository
- working_dir: Working directory for command execution
- """
- cleanup_cmd = f'rm -rf {org_repo_dir}'
- await workspace.execute_command(cleanup_cmd, working_dir, timeout=10.0)
-
-
-async def load_org_skills(
- workspace: AsyncRemoteWorkspace,
- selected_repository: str | None,
- working_dir: str,
- user_context: UserContext,
+async def load_skills_from_agent_server(
+ agent_server_url: str,
+ session_api_key: str | None,
+ project_dir: str,
+ org_config: OrgConfig | None = None,
+ sandbox_config: SandboxConfig | None = None,
+ load_public: bool = True,
+ load_user: bool = True,
+ load_project: bool = True,
+ load_org: bool = True,
) -> list[Skill]:
- """Load organization-level skills from the organization 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 skills from both the ./skills/ and ./microagents/ folders.
+ """Load all skills from the agent-server.
- 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).
+ This function makes a single API call to the agent-server's /api/skills
+ endpoint to load and merge skills from all configured sources.
Args:
- workspace: AsyncRemoteWorkspace to execute commands in the sandbox
- selected_repository: Repository name (e.g., 'owner/repo') or None
- working_dir: Working directory path
- user_context: UserContext to access provider handler and authentication
+ agent_server_url: URL of the agent server (e.g., 'http://localhost:8000')
+ session_api_key: Session API key for authentication (optional)
+ project_dir: Workspace directory path for project skills
+ org_config: Organization skills configuration (optional)
+ sandbox_config: Sandbox skills configuration (optional)
+ load_public: Whether to load public skills (default: True)
+ load_user: Whether to load user skills (default: True)
+ load_project: Whether to load project skills (default: True)
+ load_org: Whether to load organization skills (default: True)
Returns:
- List of Skill objects loaded from organization repository.
- Returns empty list if no repository selected or on errors.
+ List of Skill objects merged from all sources.
+ Returns empty list on error.
"""
- if not selected_repository:
- return []
-
try:
- _logger.debug(
- f'Starting org-level skill loading for repository: {selected_repository}'
- )
-
- # Validate repository path
- if not _validate_repository_for_org_skills(selected_repository):
- return []
-
- # Determine organization repository path
- org_openhands_repo, org_name = await _determine_org_repo_path(
- selected_repository, user_context
- )
-
- _logger.info(f'Checking for org-level skills at {org_openhands_repo}')
+ # Build request payload
+ payload = {
+ 'load_public': load_public,
+ 'load_user': load_user,
+ 'load_project': load_project,
+ 'load_org': load_org,
+ 'project_dir': project_dir,
+ 'org_config': org_config.model_dump() if org_config else None,
+ 'sandbox_config': sandbox_config.model_dump() if sandbox_config else None,
+ }
+
+ # Build headers
+ headers = {'Content-Type': 'application/json'}
+ if session_api_key:
+ headers['X-Session-API-Key'] = session_api_key
+
+ # Make API request
+ async with httpx.AsyncClient() as client:
+ response = await client.post(
+ f'{agent_server_url}/api/skills',
+ json=payload,
+ headers=headers,
+ timeout=60.0,
+ )
+ response.raise_for_status()
- # Get authenticated URL for org repository
- remote_url = await _get_org_repository_url(org_openhands_repo, user_context)
- if not remote_url:
- return []
+ data = response.json()
- # Clone the organization repository
- org_repo_dir = f'{working_dir}/_org_openhands_{org_name}'
- clone_success = await _clone_org_repository(
- workspace, remote_url, org_repo_dir, working_dir, org_openhands_repo
- )
- if not clone_success:
- return []
-
- # Load skills from both skills/ and microagents/ directories
- (
- skills_dir_skills,
- microagents_dir_skills,
- ) = await _load_skills_from_org_directories(
- workspace, org_repo_dir, working_dir
- )
-
- # Merge skills with proper precedence
- loaded_skills = _merge_org_skills_with_precedence(
- skills_dir_skills, microagents_dir_skills
- )
+ # Convert response to Skill objects
+ skills: list[Skill] = []
+ for skill_data_dict in data.get('skills', []):
+ try:
+ skill_info = SkillInfo.model_validate(skill_data_dict)
+ skill = _convert_skill_info_to_skill(skill_info)
+ skills.append(skill)
+ except Exception as e:
+ skill_name = (
+ skill_data_dict.get('name', 'unknown')
+ if isinstance(skill_data_dict, dict)
+ else 'unknown'
+ )
+ _logger.warning(f'Failed to convert skill {skill_name}: {e}')
+ sources = data.get('sources', {})
_logger.info(
- f'Loaded {len(loaded_skills)} skills from org-level repository {org_openhands_repo}: {[s.name for s in loaded_skills]}'
+ f'Loaded {len(skills)} skills from agent-server: '
+ f'sources={sources}, names={[s.name for s in skills]}'
)
- # Clean up the org repo directory
- await _cleanup_org_repository(workspace, org_repo_dir, working_dir)
-
- return loaded_skills
+ return skills
- except AuthenticationError as e:
- _logger.debug(f'org-level skill directory not found: {str(e)}')
+ except httpx.HTTPStatusError as e:
+ _logger.warning(
+ f'Agent-server returned error status {e.response.status_code}: '
+ f'{e.response.text}'
+ )
+ return []
+ except httpx.RequestError as e:
+ _logger.warning(f'Failed to connect to agent-server: {e}')
return []
except Exception as e:
- _logger.warning(f'Failed to load org-level skills: {str(e)}')
+ _logger.warning(f'Failed to load skills from agent-server: {e}')
return []
-def merge_skills(skill_lists: list[list[Skill]]) -> list[Skill]:
- """Merge multiple skill lists, avoiding duplicates by name.
-
- Later lists take precedence over earlier lists for duplicate names.
+def _convert_skill_info_to_skill(skill_info: SkillInfo) -> Skill:
+ """Convert skill info from API response to Skill object.
Args:
- skill_lists: List of skill lists to merge
+ skill_info: SkillInfo model from API response
Returns:
- Deduplicated list of skills with later lists overriding earlier ones
+ Skill object
"""
- skills_by_name = {}
+ trigger = None
- for skill_list in skill_lists:
- for skill in skill_list:
- if skill.name in skills_by_name:
- _logger.debug(
- f'Overriding skill "{skill.name}" from earlier source with later source'
- )
- skills_by_name[skill.name] = skill
-
- result = list(skills_by_name.values())
- _logger.debug(f'Merged skills: {[s.name for s in result]}')
- return result
+ if skill_info.triggers:
+ # Determine trigger type based on content
+ if any(t.startswith('/') for t in skill_info.triggers):
+ trigger = TaskTrigger(triggers=skill_info.triggers)
+ else:
+ trigger = KeywordTrigger(keywords=skill_info.triggers)
+
+ return Skill(
+ name=skill_info.name,
+ content=skill_info.content,
+ trigger=trigger,
+ source=skill_info.source,
+ description=skill_info.description,
+ is_agentskills_format=skill_info.is_agentskills_format,
+ )
diff --git a/tests/unit/app_server/test_app_conversation_service_base.py b/tests/unit/app_server/test_app_conversation_service_base.py
index 5cedd5997f..701a59198a 100644
--- a/tests/unit/app_server/test_app_conversation_service_base.py
+++ b/tests/unit/app_server/test_app_conversation_service_base.py
@@ -17,6 +17,7 @@ from openhands.app_server.app_conversation.app_conversation_service_base import
)
from openhands.app_server.sandbox.sandbox_models import SandboxInfo
from openhands.app_server.user.user_context import UserContext
+from openhands.sdk.context.skills import Skill
class MockUserInfo:
@@ -920,347 +921,251 @@ async def test_configure_git_user_settings_special_characters_in_name(mock_works
# =============================================================================
-# Tests for load_and_merge_all_skills with org skills
+# Tests for load_and_merge_all_skills (updated to use agent-server)
# =============================================================================
-class TestLoadAndMergeAllSkillsWithOrgSkills:
- """Test load_and_merge_all_skills includes organization skills."""
+class TestMergeSkills:
+ """Test _merge_skills method."""
- @pytest.mark.asyncio
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_sandbox_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_global_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_user_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_org_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_repo_skills'
- )
- async def test_load_and_merge_includes_org_skills(
- self,
- mock_load_repo,
- mock_load_org,
- mock_load_user,
- mock_load_global,
- mock_load_sandbox,
- ):
- """Test that load_and_merge_all_skills loads and merges org skills."""
+ def test_merges_skills_with_no_duplicates(self):
+ """Test merging skill lists with no duplicate names."""
# Arrange
mock_user_context = Mock(spec=UserContext)
- with patch.object(
- AppConversationServiceBase,
- '__abstractmethods__',
- set(),
- ):
+ with patch.object(AppConversationServiceBase, '__abstractmethods__', set()):
service = AppConversationServiceBase(
- init_git_in_empty_workspace=True,
- user_context=mock_user_context,
+ init_git_in_empty_workspace=True, user_context=mock_user_context
)
- sandbox = Mock(spec=SandboxInfo)
- sandbox.exposed_urls = []
- remote_workspace = AsyncMock()
-
- # Create distinct mock skills for each source
- sandbox_skill = Mock()
- sandbox_skill.name = 'sandbox_skill'
- global_skill = Mock()
- global_skill.name = 'global_skill'
- user_skill = Mock()
- user_skill.name = 'user_skill'
- org_skill = Mock()
- org_skill.name = 'org_skill'
- repo_skill = Mock()
- repo_skill.name = 'repo_skill'
-
- mock_load_sandbox.return_value = [sandbox_skill]
- mock_load_global.return_value = [global_skill]
- mock_load_user.return_value = [user_skill]
- mock_load_org.return_value = [org_skill]
- mock_load_repo.return_value = [repo_skill]
+ skill1 = Mock(spec=Skill)
+ skill1.name = 'skill1'
+ skill2 = Mock(spec=Skill)
+ skill2.name = 'skill2'
+ skill3 = Mock(spec=Skill)
+ skill3.name = 'skill3'
+
+ skill_lists = [[skill1], [skill2], [skill3]]
# Act
- result = await service.load_and_merge_all_skills(
- sandbox, remote_workspace, 'owner/repo', '/workspace'
- )
+ result = service._merge_skills(skill_lists)
# Assert
- assert len(result) == 5
+ assert len(result) == 3
names = {s.name for s in result}
- assert names == {
- 'sandbox_skill',
- 'global_skill',
- 'user_skill',
- 'org_skill',
- 'repo_skill',
- }
- mock_load_org.assert_called_once_with(
- remote_workspace, 'owner/repo', '/workspace', mock_user_context
+ assert names == {'skill1', 'skill2', 'skill3'}
+
+ def test_merges_skills_with_duplicates_later_wins(self):
+ """Test that later skill lists override earlier ones for duplicate names."""
+ # Arrange
+ mock_user_context = Mock(spec=UserContext)
+ with patch.object(AppConversationServiceBase, '__abstractmethods__', set()):
+ service = AppConversationServiceBase(
+ init_git_in_empty_workspace=True, user_context=mock_user_context
)
+ skill1_v1 = Mock(spec=Skill)
+ skill1_v1.name = 'skill1'
+ skill1_v1.version = 'v1'
+
+ skill1_v2 = Mock(spec=Skill)
+ skill1_v2.name = 'skill1'
+ skill1_v2.version = 'v2'
+
+ skill2 = Mock(spec=Skill)
+ skill2.name = 'skill2'
+
+ skill_lists = [[skill1_v1], [skill1_v2, skill2]]
+
+ # Act
+ result = service._merge_skills(skill_lists)
+
+ # Assert
+ assert len(result) == 2
+ skill1_result = next(s for s in result if s.name == 'skill1')
+ assert skill1_result.version == 'v2'
+
+
+class TestLoadAndMergeAllSkills:
+ """Test load_and_merge_all_skills method (updated to use agent-server)."""
+
@pytest.mark.asyncio
@patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_sandbox_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_global_skills'
+ 'openhands.app_server.app_conversation.app_conversation_service_base.load_skills_from_agent_server'
)
@patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_user_skills'
+ 'openhands.app_server.app_conversation.app_conversation_service_base.build_org_config'
)
@patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_org_skills'
+ 'openhands.app_server.app_conversation.app_conversation_service_base.build_sandbox_config'
)
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_repo_skills'
- )
- async def test_load_and_merge_org_skills_precedence(
+ async def test_loads_skills_successfully(
self,
- mock_load_repo,
- mock_load_org,
- mock_load_user,
- mock_load_global,
- mock_load_sandbox,
+ mock_build_sandbox_config,
+ mock_build_org_config,
+ mock_load_skills,
):
- """Test that org skills have correct precedence (higher than user, lower than repo)."""
+ """Test successfully loading skills from agent-server."""
# Arrange
mock_user_context = Mock(spec=UserContext)
- with patch.object(
- AppConversationServiceBase,
- '__abstractmethods__',
- set(),
- ):
+ with patch.object(AppConversationServiceBase, '__abstractmethods__', set()):
service = AppConversationServiceBase(
- init_git_in_empty_workspace=True,
- user_context=mock_user_context,
+ init_git_in_empty_workspace=True, user_context=mock_user_context
)
- sandbox = Mock(spec=SandboxInfo)
- sandbox.exposed_urls = []
- remote_workspace = AsyncMock()
+ mock_workspace = AsyncMock()
+ mock_workspace.working_dir = '/workspace'
- # Create skills with same name but different sources
- user_skill = Mock()
- user_skill.name = 'common_skill'
- user_skill.source = 'user'
+ from openhands.app_server.sandbox.sandbox_models import ExposedUrl
- org_skill = Mock()
- org_skill.name = 'common_skill'
- org_skill.source = 'org'
+ sandbox = Mock(spec=SandboxInfo)
+ exposed_url = ExposedUrl(
+ name='AGENT_SERVER', url='http://localhost:8000', port=8000
+ )
+ sandbox.exposed_urls = [exposed_url]
+ sandbox.session_api_key = 'test-api-key'
- repo_skill = Mock()
- repo_skill.name = 'common_skill'
- repo_skill.source = 'repo'
+ skill1 = Mock(spec=Skill)
+ skill1.name = 'skill1'
+ skill2 = Mock(spec=Skill)
+ skill2.name = 'skill2'
- mock_load_sandbox.return_value = []
- mock_load_global.return_value = []
- mock_load_user.return_value = [user_skill]
- mock_load_org.return_value = [org_skill]
- mock_load_repo.return_value = [repo_skill]
+ mock_load_skills.return_value = [skill1, skill2]
+ mock_build_org_config.return_value = {'repository': 'owner/repo'}
+ mock_build_sandbox_config.return_value = {'exposed_urls': []}
# Act
result = await service.load_and_merge_all_skills(
- sandbox, remote_workspace, 'owner/repo', '/workspace'
+ sandbox, 'owner/repo', '/workspace', 'http://localhost:8000'
)
# Assert
- # Should have only one skill with repo source (highest precedence)
- assert len(result) == 1
- assert result[0].source == 'repo'
+ assert len(result) == 2
+ assert result[0].name == 'skill1'
+ assert result[1].name == 'skill2'
+ mock_load_skills.assert_called_once()
+ call_kwargs = mock_load_skills.call_args[1]
+ assert call_kwargs['agent_server_url'] == 'http://localhost:8000'
+ assert call_kwargs['session_api_key'] == 'test-api-key'
+ assert call_kwargs['project_dir'] == '/workspace/repo'
@pytest.mark.asyncio
@patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_sandbox_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_global_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_user_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_org_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_repo_skills'
+ 'openhands.app_server.app_conversation.app_conversation_service_base.load_skills_from_agent_server'
)
- async def test_load_and_merge_org_skills_override_user_skills(
- self,
- mock_load_repo,
- mock_load_org,
- mock_load_user,
- mock_load_global,
- mock_load_sandbox,
- ):
- """Test that org skills override user skills for same name."""
+ async def test_returns_empty_list_when_no_agent_server_url(self, mock_load_skills):
+ """Test returns empty list when agent-server URL is not available."""
# Arrange
mock_user_context = Mock(spec=UserContext)
- with patch.object(
- AppConversationServiceBase,
- '__abstractmethods__',
- set(),
- ):
+ with patch.object(AppConversationServiceBase, '__abstractmethods__', set()):
service = AppConversationServiceBase(
- init_git_in_empty_workspace=True,
- user_context=mock_user_context,
+ init_git_in_empty_workspace=True, user_context=mock_user_context
)
- sandbox = Mock(spec=SandboxInfo)
- sandbox.exposed_urls = []
- remote_workspace = AsyncMock()
-
- # Create skills with same name
- user_skill = Mock()
- user_skill.name = 'shared_skill'
- user_skill.priority = 'low'
-
- org_skill = Mock()
- org_skill.name = 'shared_skill'
- org_skill.priority = 'high'
+ AsyncMock()
+ from openhands.app_server.sandbox.sandbox_models import ExposedUrl
- mock_load_sandbox.return_value = []
- mock_load_global.return_value = []
- mock_load_user.return_value = [user_skill]
- mock_load_org.return_value = [org_skill]
- mock_load_repo.return_value = []
+ sandbox = Mock(spec=SandboxInfo)
+ exposed_url = ExposedUrl(
+ name='VSCODE', url='http://localhost:8080', port=8080
+ )
+ sandbox.exposed_urls = [exposed_url]
- # Act
+ # Act - pass empty string to simulate no agent server URL
+ # This should still call load_skills_from_agent_server but it will fail
result = await service.load_and_merge_all_skills(
- sandbox, remote_workspace, 'owner/repo', '/workspace'
+ sandbox, 'owner/repo', '/workspace', ''
)
- # Assert
- assert len(result) == 1
- assert result[0].priority == 'high' # Org skill should win
+ # Assert - should return empty list when agent_server_url is empty
+ assert result == []
@pytest.mark.asyncio
@patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_sandbox_skills'
+ 'openhands.app_server.app_conversation.app_conversation_service_base.load_skills_from_agent_server'
)
@patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_global_skills'
+ 'openhands.app_server.app_conversation.app_conversation_service_base.build_org_config'
)
@patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_user_skills'
+ 'openhands.app_server.app_conversation.app_conversation_service_base.build_sandbox_config'
)
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_org_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_repo_skills'
- )
- async def test_load_and_merge_handles_org_skills_failure(
+ async def test_uses_working_dir_when_no_repository(
self,
- mock_load_repo,
- mock_load_org,
- mock_load_user,
- mock_load_global,
- mock_load_sandbox,
+ mock_build_sandbox_config,
+ mock_build_org_config,
+ mock_load_skills,
):
- """Test that failure to load org skills doesn't break the overall process."""
+ """Test uses working_dir as project_dir when no repository is selected."""
# Arrange
mock_user_context = Mock(spec=UserContext)
- with patch.object(
- AppConversationServiceBase,
- '__abstractmethods__',
- set(),
- ):
+ with patch.object(AppConversationServiceBase, '__abstractmethods__', set()):
service = AppConversationServiceBase(
- init_git_in_empty_workspace=True,
- user_context=mock_user_context,
+ init_git_in_empty_workspace=True, user_context=mock_user_context
)
- sandbox = Mock(spec=SandboxInfo)
- sandbox.exposed_urls = []
- remote_workspace = AsyncMock()
+ AsyncMock()
+ from openhands.app_server.sandbox.sandbox_models import ExposedUrl
- global_skill = Mock()
- global_skill.name = 'global_skill'
- repo_skill = Mock()
- repo_skill.name = 'repo_skill'
+ sandbox = Mock(spec=SandboxInfo)
+ exposed_url = ExposedUrl(
+ name='AGENT_SERVER', url='http://localhost:8000', port=8000
+ )
+ sandbox.exposed_urls = [exposed_url]
+ sandbox.session_api_key = 'test-key'
- mock_load_sandbox.return_value = []
- mock_load_global.return_value = [global_skill]
- mock_load_user.return_value = []
- mock_load_org.return_value = [] # Org skills failed/empty
- mock_load_repo.return_value = [repo_skill]
+ mock_load_skills.return_value = []
+ mock_build_org_config.return_value = None
+ mock_build_sandbox_config.return_value = None
# Act
- result = await service.load_and_merge_all_skills(
- sandbox, remote_workspace, 'owner/repo', '/workspace'
+ await service.load_and_merge_all_skills(
+ sandbox, None, '/workspace', 'http://localhost:8000'
)
# Assert
- # Should still have skills from other sources
- assert len(result) == 2
- names = {s.name for s in result}
- assert names == {'global_skill', 'repo_skill'}
+ call_kwargs = mock_load_skills.call_args[1]
+ assert call_kwargs['project_dir'] == '/workspace'
@pytest.mark.asyncio
@patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_sandbox_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_global_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_user_skills'
+ 'openhands.app_server.app_conversation.app_conversation_service_base.load_skills_from_agent_server'
)
@patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_org_skills'
+ 'openhands.app_server.app_conversation.app_conversation_service_base.build_org_config'
)
@patch(
- 'openhands.app_server.app_conversation.app_conversation_service_base.load_repo_skills'
+ 'openhands.app_server.app_conversation.app_conversation_service_base.build_sandbox_config'
)
- async def test_load_and_merge_no_selected_repository(
+ async def test_handles_exception_gracefully(
self,
- mock_load_repo,
- mock_load_org,
- mock_load_user,
- mock_load_global,
- mock_load_sandbox,
+ mock_build_sandbox_config,
+ mock_build_org_config,
+ mock_load_skills,
):
- """Test skill loading when no repository is selected."""
+ """Test handles exceptions during skill loading."""
# Arrange
mock_user_context = Mock(spec=UserContext)
- with patch.object(
- AppConversationServiceBase,
- '__abstractmethods__',
- set(),
- ):
+ with patch.object(AppConversationServiceBase, '__abstractmethods__', set()):
service = AppConversationServiceBase(
- init_git_in_empty_workspace=True,
- user_context=mock_user_context,
+ init_git_in_empty_workspace=True, user_context=mock_user_context
)
- sandbox = Mock(spec=SandboxInfo)
- sandbox.exposed_urls = []
- remote_workspace = AsyncMock()
+ AsyncMock()
+ from openhands.app_server.sandbox.sandbox_models import ExposedUrl
- global_skill = Mock()
- global_skill.name = 'global_skill'
+ sandbox = Mock(spec=SandboxInfo)
+ exposed_url = ExposedUrl(
+ name='AGENT_SERVER', url='http://localhost:8000', port=8000
+ )
+ sandbox.exposed_urls = [exposed_url]
+ sandbox.session_api_key = 'test-key'
- mock_load_sandbox.return_value = []
- mock_load_global.return_value = [global_skill]
- mock_load_user.return_value = []
- mock_load_org.return_value = []
- mock_load_repo.return_value = []
+ mock_load_skills.side_effect = Exception('Network error')
# Act
result = await service.load_and_merge_all_skills(
- sandbox, remote_workspace, None, '/workspace'
+ sandbox, 'owner/repo', '/workspace', 'http://localhost:8000'
)
# Assert
- assert len(result) == 1
- # Org skills should be called even with None repository
- mock_load_org.assert_called_once_with(
- remote_workspace, None, '/workspace', mock_user_context
- )
+ assert result == []
diff --git a/tests/unit/app_server/test_live_status_app_conversation_service.py b/tests/unit/app_server/test_live_status_app_conversation_service.py
index 880244fda4..98b0d88aaa 100644
--- a/tests/unit/app_server/test_live_status_app_conversation_service.py
+++ b/tests/unit/app_server/test_live_status_app_conversation_service.py
@@ -1288,7 +1288,7 @@ class TestLiveStatusAppConversationService:
task.sandbox_id = self.mock_sandbox.id
yield task
- async def mock_run_setup_scripts(task, sandbox, workspace):
+ async def mock_run_setup_scripts(task, sandbox, workspace, agent_server_url):
yield task
self.service._wait_for_sandbox_start = mock_wait_for_sandbox
diff --git a/tests/unit/app_server/test_skill_loader.py b/tests/unit/app_server/test_skill_loader.py
index c709b8333f..3ce567ed33 100644
--- a/tests/unit/app_server/test_skill_loader.py
+++ b/tests/unit/app_server/test_skill_loader.py
@@ -1,37 +1,38 @@
"""Tests for skill_loader module.
-This module tests the loading of skills from various sources
-(global, user, and repository-level) into SDK Skill objects for V1 conversations.
+This module tests the loading of skills from the agent-server,
+which centralizes all skill loading logic. The app-server acts as a
+thin proxy that builds configs and calls the agent-server's /api/skills endpoint.
"""
-import tempfile
-from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, Mock, patch
+import httpx
import pytest
from openhands.app_server.app_conversation.skill_loader import (
- _cleanup_org_repository,
- _clone_org_repository,
+ OrgConfig,
+ SandboxConfig,
+ SkillInfo,
+ _convert_skill_info_to_skill,
_determine_org_repo_path,
- _determine_repo_root,
- _find_and_load_global_skill_files,
- _find_and_load_skill_md_files,
_get_org_repository_url,
+ _get_provider_type,
_is_azure_devops_repository,
_is_gitlab_repository,
- _load_skills_from_org_directories,
- _load_special_files,
- _merge_org_skills_with_precedence,
- _read_file_from_workspace,
- _validate_repository_for_org_skills,
- load_global_skills,
- load_org_skills,
- load_repo_skills,
- merge_skills,
+ build_org_config,
+ build_sandbox_config,
+ load_skills_from_agent_server,
)
+from openhands.app_server.sandbox.sandbox_models import (
+ ExposedUrl,
+ SandboxInfo,
+ SandboxStatus,
+)
+from openhands.app_server.user.user_context import UserContext
from openhands.integrations.provider import ProviderType
from openhands.integrations.service_types import AuthenticationError
+from openhands.sdk.context.skills import KeywordTrigger, Skill, TaskTrigger
# ===== Test Fixtures =====
@@ -58,628 +59,406 @@ def mock_skills_list():
@pytest.fixture
-def mock_async_remote_workspace():
- """Create a mock AsyncRemoteWorkspace."""
- workspace = AsyncMock()
- return workspace
+def mock_user_context():
+ """Create a mock UserContext."""
+ return AsyncMock(spec=UserContext)
@pytest.fixture
-def temp_skills_dir():
- """Create a temporary directory with test skill files."""
- with tempfile.TemporaryDirectory() as temp_dir:
- root = Path(temp_dir)
-
- # Create test skill files
- test_skill = """---
-name: test_skill
-triggers:
- - test
- - testing
----
-
-# Test Skill
-
-This is a test skill for testing purposes.
-"""
- (root / 'test_skill.md').write_text(test_skill)
-
- another_skill = """---
-name: another_skill
----
-
-# Another Skill
-
-Another test skill.
-"""
- (root / 'another_skill.md').write_text(another_skill)
-
- # Create README.md which should be ignored
- (root / 'README.md').write_text('# README\n\nThis should be ignored.')
-
- yield root
-
-
-def command_result_success():
- """Create a successful command result."""
- result = Mock()
- result.exit_code = 0
- result.stdout = 'test output'
- return result
+def mock_sandbox_info():
+ """Create a mock SandboxInfo with exposed URLs."""
+ return SandboxInfo(
+ id='test-sandbox-123',
+ created_by_user_id='user-123',
+ sandbox_spec_id='spec-123',
+ status=SandboxStatus.RUNNING,
+ session_api_key='test-api-key',
+ exposed_urls=[
+ ExposedUrl(name='AGENT_SERVER', url='http://localhost:8000', port=8000),
+ ExposedUrl(name='VSCODE', url='http://localhost:8080', port=8080),
+ ],
+ )
@pytest.fixture
-def command_result_failure():
- """Create a failed command result."""
- result = Mock()
- result.exit_code = 1
- result.stdout = ''
- return result
-
-
-# ===== Tests for Helper Functions =====
-
-
-class TestDetermineRepoRoot:
- """Test _determine_repo_root helper function."""
-
- def test_with_selected_repository(self):
- """Test determining repo root with selected repository."""
- result = _determine_repo_root('/workspace/project', 'owner/repo-name')
- assert result == '/workspace/project/repo-name'
-
- def test_without_selected_repository(self):
- """Test determining repo root without selected repository."""
- result = _determine_repo_root('/workspace/project', None)
- assert result == '/workspace/project'
-
- def test_with_complex_repository_name(self):
- """Test with complex repository name."""
- result = _determine_repo_root('/workspace', 'org-name/complex-repo-123')
- assert result == '/workspace/complex-repo-123'
-
-
-class TestReadFileFromWorkspace:
- """Test _read_file_from_workspace helper function."""
-
- @pytest.mark.asyncio
- async def test_successful_read(
- self, mock_async_remote_workspace, command_result_success
- ):
- """Test successfully reading a file from workspace."""
- command_result_success.stdout = 'file content\n'
- mock_async_remote_workspace.execute_command.return_value = (
- command_result_success
- )
-
- result = await _read_file_from_workspace(
- mock_async_remote_workspace, '/path/to/file.md', '/workspace'
- )
-
- assert result == 'file content\n'
- mock_async_remote_workspace.execute_command.assert_called_once_with(
- 'cat /path/to/file.md', cwd='/workspace', timeout=10.0
- )
-
- @pytest.mark.asyncio
- async def test_file_not_found(
- self, mock_async_remote_workspace, command_result_failure
- ):
- """Test reading a non-existent file."""
- mock_async_remote_workspace.execute_command.return_value = (
- command_result_failure
- )
-
- result = await _read_file_from_workspace(
- mock_async_remote_workspace, '/nonexistent/file.md', '/workspace'
- )
-
- assert result is None
-
- @pytest.mark.asyncio
- async def test_empty_file(self, mock_async_remote_workspace):
- """Test reading an empty file."""
- result_obj = Mock()
- result_obj.exit_code = 0
- result_obj.stdout = ' ' # Only whitespace
- mock_async_remote_workspace.execute_command.return_value = result_obj
-
- result = await _read_file_from_workspace(
- mock_async_remote_workspace, '/empty/file.md', '/workspace'
- )
-
- assert result is None
-
- @pytest.mark.asyncio
- async def test_command_exception(self, mock_async_remote_workspace):
- """Test handling exception during file read."""
- mock_async_remote_workspace.execute_command.side_effect = Exception(
- 'Connection error'
- )
-
- result = await _read_file_from_workspace(
- mock_async_remote_workspace, '/path/to/file.md', '/workspace'
- )
-
- assert result is None
+def mock_sandbox_info_no_urls():
+ """Create a mock SandboxInfo without exposed URLs."""
+ return SandboxInfo(
+ id='test-sandbox-123',
+ created_by_user_id='user-123',
+ sandbox_spec_id='spec-123',
+ status=SandboxStatus.RUNNING,
+ session_api_key='test-api-key',
+ exposed_urls=None,
+ )
-class TestLoadSpecialFiles:
- """Test _load_special_files helper function."""
+# ===== Tests for New Functions =====
- @pytest.mark.asyncio
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._read_file_from_workspace'
- )
- @patch('openhands.app_server.app_conversation.skill_loader.Skill')
- async def test_load_all_special_files(
- self,
- mock_skill_class,
- mock_read_file,
- mock_async_remote_workspace,
- mock_skills_list,
- ):
- """Test loading all special files successfully."""
- # Mock reading files - return content for each special file
- mock_read_file.side_effect = [
- 'cursorrules content',
- 'agents.md content',
- 'agent.md content',
- ]
-
- # Mock skill creation
- mock_skill_class.load.side_effect = mock_skills_list
-
- result = await _load_special_files(
- mock_async_remote_workspace, '/repo', '/workspace'
- )
- assert len(result) == 3
- assert result == mock_skills_list
- assert mock_read_file.call_count == 3
- assert mock_skill_class.load.call_count == 3
+class TestGetProviderType:
+ """Test _get_provider_type function."""
@pytest.mark.asyncio
+ @patch('openhands.app_server.app_conversation.skill_loader._is_gitlab_repository')
@patch(
- 'openhands.app_server.app_conversation.skill_loader._read_file_from_workspace'
+ 'openhands.app_server.app_conversation.skill_loader._is_azure_devops_repository'
)
- @patch('openhands.app_server.app_conversation.skill_loader.Skill')
- async def test_load_partial_special_files(
- self, mock_skill_class, mock_read_file, mock_async_remote_workspace, mock_skill
+ async def test_returns_gitlab_for_gitlab_repo(
+ self, mock_is_azure, mock_is_gitlab, mock_user_context
):
- """Test loading when only some special files exist."""
- # Only .cursorrules exists
- mock_read_file.side_effect = ['cursorrules content', None, None]
- mock_skill_class.load.return_value = mock_skill
+ """Test returns 'gitlab' for GitLab repository."""
+ # Arrange
+ mock_is_gitlab.return_value = True
+ mock_is_azure.return_value = False
- result = await _load_special_files(
- mock_async_remote_workspace, '/repo', '/workspace'
- )
+ # Act
+ result = await _get_provider_type('owner/repo', mock_user_context)
- assert len(result) == 1
- assert result[0] == mock_skill
- assert mock_read_file.call_count == 3
- assert mock_skill_class.load.call_count == 1
+ # Assert
+ assert result == 'gitlab'
+ mock_is_gitlab.assert_called_once_with('owner/repo', mock_user_context)
@pytest.mark.asyncio
+ @patch('openhands.app_server.app_conversation.skill_loader._is_gitlab_repository')
@patch(
- 'openhands.app_server.app_conversation.skill_loader._read_file_from_workspace'
+ 'openhands.app_server.app_conversation.skill_loader._is_azure_devops_repository'
)
- async def test_load_no_special_files(
- self, mock_read_file, mock_async_remote_workspace
+ async def test_returns_azure_for_azure_repo(
+ self, mock_is_azure, mock_is_gitlab, mock_user_context
):
- """Test when no special files exist."""
- mock_read_file.return_value = None
-
- result = await _load_special_files(
- mock_async_remote_workspace, '/repo', '/workspace'
- )
-
- assert len(result) == 0
+ """Test returns 'azure' for Azure DevOps repository."""
+ # Arrange
+ mock_is_gitlab.return_value = False
+ mock_is_azure.return_value = True
+ # Act
+ result = await _get_provider_type('org/project/repo', mock_user_context)
-class TestFindAndLoadSkillMdFiles:
- """Test _find_and_load_skill_md_files helper function."""
+ # Assert
+ assert result == 'azure'
+ mock_is_azure.assert_called_once_with('org/project/repo', mock_user_context)
@pytest.mark.asyncio
+ @patch('openhands.app_server.app_conversation.skill_loader._is_gitlab_repository')
@patch(
- 'openhands.app_server.app_conversation.skill_loader._read_file_from_workspace'
+ 'openhands.app_server.app_conversation.skill_loader._is_azure_devops_repository'
)
- @patch('openhands.app_server.app_conversation.skill_loader.Skill')
- async def test_find_and_load_files_success(
- self,
- mock_skill_class,
- mock_read_file,
- mock_async_remote_workspace,
- mock_skills_list,
+ async def test_returns_github_for_github_repo(
+ self, mock_is_azure, mock_is_gitlab, mock_user_context
):
- """Test successfully finding and loading skill .md files."""
- result_obj = Mock()
- result_obj.exit_code = 0
- result_obj.stdout = (
- '/repo/.openhands/skills/test1.md\n/repo/.openhands/skills/test2.md\n'
- )
- mock_async_remote_workspace.execute_command.return_value = result_obj
+ """Test returns 'github' for GitHub repository (default)."""
+ # Arrange
+ mock_is_gitlab.return_value = False
+ mock_is_azure.return_value = False
- mock_read_file.side_effect = ['content1', 'content2']
- mock_skill_class.load.side_effect = mock_skills_list[:2]
+ # Act
+ result = await _get_provider_type('owner/repo', mock_user_context)
- result = await _find_and_load_skill_md_files(
- mock_async_remote_workspace, '/repo/.openhands/skills', '/workspace'
- )
+ # Assert
+ assert result == 'github'
- assert len(result) == 2
- assert result == mock_skills_list[:2]
- # Verify relative paths are used
- assert mock_skill_class.load.call_args_list[0][1]['path'] == 'test1.md'
- assert mock_skill_class.load.call_args_list[1][1]['path'] == 'test2.md'
+class TestBuildOrgConfig:
+ """Test build_org_config function."""
@pytest.mark.asyncio
@patch(
- 'openhands.app_server.app_conversation.skill_loader._read_file_from_workspace'
+ 'openhands.app_server.app_conversation.skill_loader._determine_org_repo_path'
)
- @patch('openhands.app_server.app_conversation.skill_loader.Skill')
- async def test_find_and_load_excludes_readme(
- self, mock_skill_class, mock_read_file, mock_async_remote_workspace, mock_skill
+ @patch('openhands.app_server.app_conversation.skill_loader._get_org_repository_url')
+ @patch('openhands.app_server.app_conversation.skill_loader._get_provider_type')
+ async def test_builds_config_successfully(
+ self, mock_get_provider, mock_get_url, mock_determine_path, mock_user_context
):
- """Test that README.md files are excluded."""
- result_obj = Mock()
- result_obj.exit_code = 0
- result_obj.stdout = (
- '/repo/.openhands/skills/test.md\n/repo/.openhands/skills/README.md\n'
- )
- mock_async_remote_workspace.execute_command.return_value = result_obj
-
- mock_read_file.return_value = 'content'
- mock_skill_class.load.return_value = mock_skill
+ """Test successfully building org config."""
+ # Arrange
+ mock_determine_path.return_value = ('owner/.openhands', 'owner')
+ mock_get_url.return_value = 'https://[email protected]/owner/.openhands.git'
+ mock_get_provider.return_value = 'github'
- result = await _find_and_load_skill_md_files(
- mock_async_remote_workspace, '/repo/.openhands/skills', '/workspace'
- )
+ # Act
+ result = await build_org_config('owner/repo', mock_user_context)
- assert len(result) == 1
- assert result[0] == mock_skill
- # Verify README.md was not processed
- assert mock_read_file.call_count == 1
+ # Assert
+ assert result is not None
+ assert isinstance(result, OrgConfig)
+ assert result.repository == 'owner/repo'
+ assert result.provider == 'github'
+ assert result.org_repo_url == 'https://[email protected]/owner/.openhands.git'
+ assert result.org_name == 'owner'
@pytest.mark.asyncio
- async def test_find_and_load_no_results(
- self, mock_async_remote_workspace, command_result_failure
- ):
- """Test when no files are found."""
- mock_async_remote_workspace.execute_command.return_value = (
- command_result_failure
- )
-
- result = await _find_and_load_skill_md_files(
- mock_async_remote_workspace, '/nonexistent', '/workspace'
- )
+ async def test_returns_none_when_no_repository(self, mock_user_context):
+ """Test returns None when selected_repository is None."""
+ # Act
+ result = await build_org_config(None, mock_user_context)
- assert len(result) == 0
+ # Assert
+ assert result is None
@pytest.mark.asyncio
- async def test_find_and_load_exception(self, mock_async_remote_workspace):
- """Test handling exception during file search."""
- mock_async_remote_workspace.execute_command.side_effect = Exception(
- 'Command error'
- )
-
- result = await _find_and_load_skill_md_files(
- mock_async_remote_workspace, '/repo/.openhands/skills', '/workspace'
- )
+ async def test_returns_none_when_repository_has_insufficient_parts(
+ self, mock_user_context
+ ):
+ """Test returns None when repository path has less than 2 parts."""
+ # Act
+ result = await build_org_config('repo', mock_user_context)
- assert len(result) == 0
+ # Assert
+ assert result is None
@pytest.mark.asyncio
@patch(
- 'openhands.app_server.app_conversation.skill_loader._read_file_from_workspace'
+ 'openhands.app_server.app_conversation.skill_loader._determine_org_repo_path'
)
- async def test_find_and_load_some_missing(
- self, mock_read_file, mock_async_remote_workspace
+ @patch('openhands.app_server.app_conversation.skill_loader._get_org_repository_url')
+ async def test_returns_none_when_url_not_available(
+ self, mock_get_url, mock_determine_path, mock_user_context
):
- """Test loading when some files fail to read."""
- result_obj = Mock()
- result_obj.exit_code = 0
- result_obj.stdout = (
- '/repo/.openhands/skills/test1.md\n/repo/.openhands/skills/missing.md\n'
- )
- mock_async_remote_workspace.execute_command.return_value = result_obj
-
- mock_read_file.side_effect = ['content1', None]
-
- with patch(
- 'openhands.app_server.app_conversation.skill_loader.Skill'
- ) as mock_skill_class:
- mock_skill = Mock()
- mock_skill_class.load.return_value = mock_skill
-
- result = await _find_and_load_skill_md_files(
- mock_async_remote_workspace,
- '/repo/.openhands/skills',
- '/workspace',
- )
-
- assert len(result) == 1
- assert mock_skill_class.load.call_count == 1
-
-
-class TestFindAndLoadGlobalSkillFiles:
- """Test _find_and_load_global_skill_files helper function."""
+ """Test returns None when org repository URL cannot be retrieved."""
+ # Arrange
+ mock_determine_path.return_value = ('owner/.openhands', 'owner')
+ mock_get_url.return_value = None
- @patch('openhands.app_server.app_conversation.skill_loader.Skill')
- def test_find_and_load_global_files_success(
- self, mock_skill_class, temp_skills_dir, mock_skills_list
- ):
- """Test successfully finding and loading global skill files."""
- file_paths = list(temp_skills_dir.glob('*.md'))
- file_paths = [f for f in file_paths if f.name.lower() != 'readme.md']
+ # Act
+ result = await build_org_config('owner/repo', mock_user_context)
- mock_skill_class.load.side_effect = mock_skills_list[: len(file_paths)]
+ # Assert
+ assert result is None
- result = _find_and_load_global_skill_files(temp_skills_dir)
- # Should find and load .md files but not README.md
- assert len(result) == len(file_paths)
- assert mock_skill_class.load.call_count == len(file_paths)
- skill_names = [s.name for s in result]
- assert len(skill_names) == len(file_paths)
+class TestBuildSandboxConfig:
+ """Test build_sandbox_config function."""
- @patch('openhands.app_server.app_conversation.skill_loader.Skill')
- def test_find_and_load_global_files_with_errors(
- self, mock_skill_class, temp_skills_dir, mock_skill
- ):
- """Test loading when some files fail to parse."""
- file_paths = list(temp_skills_dir.glob('*.md'))
- file_paths = [f for f in file_paths if f.name.lower() != 'readme.md']
+ def test_builds_config_with_exposed_urls(self, mock_sandbox_info):
+ """Test building sandbox config with exposed URLs."""
+ # Act
+ result = build_sandbox_config(mock_sandbox_info)
- # First file succeeds, second file fails
- mock_skill_class.load.side_effect = [mock_skill, Exception('Parse error')]
+ # Assert
+ assert result is not None
+ assert isinstance(result, SandboxConfig)
+ assert len(result.exposed_urls) == 2
+ assert result.exposed_urls[0].name == 'AGENT_SERVER'
+ assert result.exposed_urls[0].url == 'http://localhost:8000'
+ assert result.exposed_urls[0].port == 8000
- result = _find_and_load_global_skill_files(temp_skills_dir)
+ def test_returns_none_when_no_exposed_urls(self, mock_sandbox_info_no_urls):
+ """Test returns None when sandbox has no exposed URLs."""
+ # Act
+ result = build_sandbox_config(mock_sandbox_info_no_urls)
- assert len(result) == 1
- assert result[0] == mock_skill
+ # Assert
+ assert result is None
- def test_find_and_load_global_files_empty_dir(self, tmp_path):
- """Test finding and loading files in empty directory."""
- result = _find_and_load_global_skill_files(tmp_path)
- assert len(result) == 0
+ def test_returns_none_when_exposed_urls_is_empty_list(self):
+ """Test returns None when exposed_urls is empty list."""
+ # Arrange
+ sandbox = SandboxInfo(
+ id='test-sandbox',
+ created_by_user_id='user-123',
+ sandbox_spec_id='spec-123',
+ status=SandboxStatus.RUNNING,
+ session_api_key='test-key',
+ exposed_urls=[],
+ )
- def test_find_and_load_global_files_nonexistent_dir(self):
- """Test finding and loading files in non-existent directory."""
- nonexistent = Path('/nonexistent/path')
- result = _find_and_load_global_skill_files(nonexistent)
- assert len(result) == 0
+ # Act
+ result = build_sandbox_config(sandbox)
+ # Assert
+ assert result is None
-# ===== Tests for Main Loader Functions =====
+class TestConvertSkillInfoToSkill:
+ """Test _convert_skill_info_to_skill function."""
-class TestLoadGlobalSkills:
- """Test load_global_skills main function."""
+ def test_converts_skill_with_keyword_trigger(self):
+ """Test converting skill data with keyword triggers."""
+ # Arrange
+ skill_info = SkillInfo(
+ name='test_skill',
+ content='Test content',
+ triggers=['test', 'testing'],
+ source='repo',
+ description='A test skill',
+ )
- @patch('openhands.app_server.app_conversation.skill_loader.Path')
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._find_and_load_global_skill_files'
- )
- def test_load_global_skills_success(
- self,
- mock_find_and_load,
- mock_path_class,
- temp_skills_dir,
- mock_skills_list,
- ):
- """Test successfully loading global skills."""
- mock_path_obj = MagicMock()
- mock_path_obj.exists.return_value = True
- mock_path_class.return_value = mock_path_obj
+ # Act
+ skill = _convert_skill_info_to_skill(skill_info)
- mock_find_and_load.return_value = mock_skills_list
+ # Assert
+ assert isinstance(skill, Skill)
+ assert skill.name == 'test_skill'
+ assert skill.content == 'Test content'
+ assert isinstance(skill.trigger, KeywordTrigger)
+ assert skill.trigger.keywords == ['test', 'testing']
+ assert skill.source == 'repo'
+ assert skill.description == 'A test skill'
- result = load_global_skills()
+ def test_converts_skill_with_task_trigger(self):
+ """Test converting skill data with task triggers (starting with /)."""
+ # Arrange
+ skill_info = SkillInfo(
+ name='task_skill',
+ content='Task content',
+ triggers=['/task1', '/task2'],
+ source='org',
+ )
- assert len(result) == len(mock_skills_list)
- assert result == mock_skills_list
+ # Act
+ skill = _convert_skill_info_to_skill(skill_info)
- @patch('openhands.app_server.app_conversation.skill_loader.Path')
- def test_load_global_skills_dir_not_exists(self, mock_path_class):
- """Test when global skills directory doesn't exist."""
- mock_path_obj = MagicMock()
- mock_path_obj.exists.return_value = False
- mock_path_class.return_value = mock_path_obj
+ # Assert
+ assert isinstance(skill, Skill)
+ assert skill.name == 'task_skill'
+ assert isinstance(skill.trigger, TaskTrigger)
+ assert skill.trigger.triggers == ['/task1', '/task2']
- result = load_global_skills()
+ def test_converts_skill_without_trigger(self):
+ """Test converting skill data without triggers."""
+ # Arrange
+ skill_info = SkillInfo(
+ name='repo_skill',
+ content='Repo content',
+ source='project',
+ )
- assert len(result) == 0
+ # Act
+ skill = _convert_skill_info_to_skill(skill_info)
- @patch('openhands.app_server.app_conversation.skill_loader.Path')
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._find_and_load_global_skill_files'
- )
- def test_load_global_skills_exception(self, mock_find_and_load, mock_path_class):
- """Test handling exception during global skill loading."""
- mock_path_obj = MagicMock()
- mock_path_obj.exists.return_value = True
- mock_path_class.return_value = mock_path_obj
+ # Assert
+ assert isinstance(skill, Skill)
+ assert skill.name == 'repo_skill'
+ assert skill.trigger is None
- mock_find_and_load.side_effect = Exception('File system error')
+ def test_converts_skill_with_empty_triggers(self):
+ """Test converting skill data with empty triggers list."""
+ # Arrange
+ skill_info = SkillInfo(
+ name='skill',
+ content='Content',
+ triggers=[],
+ )
- result = load_global_skills()
+ # Act
+ skill = _convert_skill_info_to_skill(skill_info)
- assert len(result) == 0
+ # Assert
+ assert skill.trigger is None
-class TestLoadRepoSkills:
- """Test load_repo_skills main function."""
+class TestLoadSkillsFromAgentServer:
+ """Test load_skills_from_agent_server function."""
@pytest.mark.asyncio
- @patch('openhands.app_server.app_conversation.skill_loader._load_special_files')
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._find_and_load_skill_md_files'
- )
- async def test_load_repo_skills_success(
- self,
- mock_find_and_load,
- mock_load_special,
- mock_async_remote_workspace,
- mock_skills_list,
- ):
- """Test successfully loading repo skills."""
- special_skills = [mock_skills_list[0]]
- skills_dir_skills = [mock_skills_list[1]]
- microagents_dir_skills = [mock_skills_list[2]]
-
- mock_load_special.return_value = special_skills
- # Mock loading from both directories
- mock_find_and_load.side_effect = [skills_dir_skills, microagents_dir_skills]
-
- result = await load_repo_skills(
- mock_async_remote_workspace, 'owner/repo', '/workspace/project'
+ @patch('httpx.AsyncClient')
+ async def test_loads_skills_successfully(self, mock_client_class):
+ """Test successfully loading skills from agent-server."""
+ # Arrange
+ mock_response = MagicMock()
+ mock_response.json.return_value = {
+ 'skills': [
+ {
+ 'name': 'skill1',
+ 'content': 'Content 1',
+ 'triggers': ['keyword1'],
+ },
+ {
+ 'name': 'skill2',
+ 'content': 'Content 2',
+ 'triggers': [],
+ },
+ ],
+ 'sources': {'public': 1, 'user': 1},
+ }
+ mock_response.raise_for_status = MagicMock()
+
+ mock_client = AsyncMock()
+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)
+ mock_client.__aexit__ = AsyncMock(return_value=None)
+ mock_client.post = AsyncMock(return_value=mock_response)
+ mock_client_class.return_value = mock_client
+
+ # Act
+ result = await load_skills_from_agent_server(
+ agent_server_url='http://localhost:8000',
+ session_api_key='test-key',
+ project_dir='/workspace/project',
+ org_config=OrgConfig(
+ repository='owner/repo',
+ provider='github',
+ org_repo_url='https://github.com/owner/.openhands.git',
+ org_name='owner',
+ ),
+ sandbox_config=SandboxConfig(exposed_urls=[]),
)
- assert len(result) == 3
- # Verify all skills are present (merged with precedence)
- assert special_skills[0] in result
- assert skills_dir_skills[0] in result
- assert microagents_dir_skills[0] in result
-
- @pytest.mark.asyncio
- @patch('openhands.app_server.app_conversation.skill_loader._load_special_files')
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._find_and_load_skill_md_files'
- )
- async def test_load_repo_skills_no_selected_repository(
- self,
- mock_find_and_load,
- mock_load_special,
- mock_async_remote_workspace,
- mock_skills_list,
- ):
- """Test loading repo skills without selected repository."""
- mock_load_special.return_value = [mock_skills_list[0]]
- mock_find_and_load.return_value = []
-
- result = await load_repo_skills(
- mock_async_remote_workspace, None, '/workspace/project'
+ # Assert
+ assert len(result) == 2
+ assert result[0].name == 'skill1'
+ assert result[1].name == 'skill2'
+ mock_client.post.assert_called_once()
+ call_args = mock_client.post.call_args
+ assert call_args[0][0] == 'http://localhost:8000/api/skills'
+ assert 'X-Session-API-Key' in call_args[1]['headers']
+ assert call_args[1]['headers']['X-Session-API-Key'] == 'test-key'
+
+ @pytest.mark.asyncio
+ @patch('httpx.AsyncClient')
+ async def test_handles_http_status_error(self, mock_client_class):
+ """Test handling HTTP status error from agent-server."""
+ # Arrange
+ mock_response = MagicMock()
+ mock_response.status_code = 500
+ mock_response.text = 'Internal Server Error'
+
+ mock_client = AsyncMock()
+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)
+ mock_client.__aexit__ = AsyncMock(return_value=None)
+ mock_client.post = AsyncMock(
+ side_effect=httpx.HTTPStatusError(
+ 'Server error', request=MagicMock(), response=mock_response
+ )
)
+ mock_client_class.return_value = mock_client
- assert len(result) == 1
- # Verify repo root is working_dir when no repository selected
- mock_load_special.assert_called_once_with(
- mock_async_remote_workspace, '/workspace/project', '/workspace/project'
+ # Act
+ result = await load_skills_from_agent_server(
+ agent_server_url='http://localhost:8000',
+ session_api_key='test-key',
+ project_dir='/workspace',
)
- # Verify both directories were checked
- assert mock_find_and_load.call_count == 2
- @pytest.mark.asyncio
- @patch('openhands.app_server.app_conversation.skill_loader._load_special_files')
- async def test_load_repo_skills_exception(
- self, mock_load_special, mock_async_remote_workspace
- ):
- """Test handling exception during repo skill loading."""
- mock_load_special.side_effect = Exception('Workspace error')
+ # Assert
+ assert result == []
- result = await load_repo_skills(
- mock_async_remote_workspace, 'owner/repo', '/workspace/project'
+ @pytest.mark.asyncio
+ @patch('httpx.AsyncClient')
+ async def test_handles_request_error(self, mock_client_class):
+ """Test handling request error (connection failure)."""
+ # Arrange
+ mock_client = AsyncMock()
+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)
+ mock_client.__aexit__ = AsyncMock(return_value=None)
+ mock_client.post = AsyncMock(
+ side_effect=httpx.RequestError('Connection failed')
)
+ mock_client_class.return_value = mock_client
- assert len(result) == 0
-
-
-class TestMergeSkills:
- """Test merge_skills function."""
-
- def test_merge_skills_no_duplicates(self):
- """Test merging skills with no duplicates."""
- skill1 = Mock()
- skill1.name = 'skill1'
- skill2 = Mock()
- skill2.name = 'skill2'
- skill3 = Mock()
- skill3.name = 'skill3'
-
- result = merge_skills([[skill1], [skill2], [skill3]])
-
- assert len(result) == 3
- names = {s.name for s in result}
- assert names == {'skill1', 'skill2', 'skill3'}
-
- def test_merge_skills_with_duplicates(self):
- """Test merging skills with duplicates - later takes precedence."""
- skill1_v1 = Mock()
- skill1_v1.name = 'skill1'
- skill1_v1.version = 'v1'
-
- skill1_v2 = Mock()
- skill1_v2.name = 'skill1'
- skill1_v2.version = 'v2'
-
- skill2 = Mock()
- skill2.name = 'skill2'
-
- result = merge_skills([[skill1_v1, skill2], [skill1_v2]])
-
- assert len(result) == 2
- names = {s.name for s in result}
- assert names == {'skill1', 'skill2'}
-
- # Verify later version takes precedence
- skill1_result = next(s for s in result if s.name == 'skill1')
- assert skill1_result.version == 'v2'
-
- def test_merge_skills_empty_lists(self):
- """Test merging empty skill lists."""
- result = merge_skills([[], [], []])
- assert len(result) == 0
-
- def test_merge_skills_single_list(self):
- """Test merging single skill list."""
- skill1 = Mock()
- skill1.name = 'skill1'
- skill2 = Mock()
- skill2.name = 'skill2'
-
- result = merge_skills([[skill1, skill2]])
-
- assert len(result) == 2
-
- def test_merge_skills_precedence_order(self):
- """Test that skill precedence follows list order."""
- # Create three versions of the same skill
- skill_v1 = Mock()
- skill_v1.name = 'test_skill'
- skill_v1.priority = 'low'
-
- skill_v2 = Mock()
- skill_v2.name = 'test_skill'
- skill_v2.priority = 'medium'
-
- skill_v3 = Mock()
- skill_v3.name = 'test_skill'
- skill_v3.priority = 'high'
-
- # List order: low -> medium -> high
- # Should result in high priority (last one)
- result = merge_skills([[skill_v1], [skill_v2], [skill_v3]])
-
- assert len(result) == 1
- assert result[0].priority == 'high'
-
- def test_merge_skills_mixed_empty_and_filled(self):
- """Test merging with mix of empty and filled lists."""
- skill1 = Mock()
- skill1.name = 'skill1'
- skill2 = Mock()
- skill2.name = 'skill2'
-
- result = merge_skills([[], [skill1], [], [skill2], []])
+ # Act
+ result = await load_skills_from_agent_server(
+ agent_server_url='http://localhost:8000',
+ session_api_key='test-key',
+ project_dir='/workspace',
+ )
- assert len(result) == 2
+ # Assert
+ assert result == []
-# ===== Tests for Organization Skills Functions =====
+# ===== Tests for Organization Skills Functions (Still Existing) =====
class TestIsGitlabRepository:
@@ -863,42 +642,6 @@ class TestDetermineOrgRepoPath:
assert org_name == 'org'
-class TestValidateRepositoryForOrgSkills:
- """Test _validate_repository_for_org_skills helper function."""
-
- def test_valid_repository_two_parts(self):
- """Test validation passes for repository with two parts."""
- # Act
- result = _validate_repository_for_org_skills('owner/repo')
-
- # Assert
- assert result is True
-
- def test_valid_repository_three_parts(self):
- """Test validation passes for repository with three parts (Azure DevOps)."""
- # Act
- result = _validate_repository_for_org_skills('org/project/repo')
-
- # Assert
- assert result is True
-
- def test_invalid_repository_one_part(self):
- """Test validation fails for repository with only one part."""
- # Act
- result = _validate_repository_for_org_skills('repo')
-
- # Assert
- assert result is False
-
- def test_invalid_repository_empty_string(self):
- """Test validation fails for empty string."""
- # Act
- result = _validate_repository_for_org_skills('')
-
- # Assert
- assert result is False
-
-
class TestGetOrgRepositoryUrl:
"""Test _get_org_repository_url helper function."""
@@ -948,593 +691,3 @@ class TestGetOrgRepositoryUrl:
# Assert
assert result is None
-
-
-class TestCloneOrgRepository:
- """Test _clone_org_repository helper function."""
-
- @pytest.mark.asyncio
- async def test_successful_clone(self, mock_async_remote_workspace):
- """Test successful repository clone."""
- # Arrange
- result_obj = Mock()
- result_obj.exit_code = 0
- mock_async_remote_workspace.execute_command.return_value = result_obj
-
- # Act
- success = await _clone_org_repository(
- mock_async_remote_workspace,
- 'https://github.com/owner/.openhands.git',
- '/workspace/_org_openhands_owner',
- '/workspace',
- 'owner/.openhands',
- )
-
- # Assert
- assert success is True
- mock_async_remote_workspace.execute_command.assert_called_once()
- call_args = mock_async_remote_workspace.execute_command.call_args
- assert 'git clone' in call_args[0][0]
- assert '--depth 1' in call_args[0][0]
-
- @pytest.mark.asyncio
- async def test_failed_clone(self, mock_async_remote_workspace):
- """Test failed repository clone."""
- # Arrange
- result_obj = Mock()
- result_obj.exit_code = 1
- result_obj.stderr = 'Repository not found'
- mock_async_remote_workspace.execute_command.return_value = result_obj
-
- # Act
- success = await _clone_org_repository(
- mock_async_remote_workspace,
- 'https://github.com/owner/.openhands.git',
- '/workspace/_org_openhands_owner',
- '/workspace',
- 'owner/.openhands',
- )
-
- # Assert
- assert success is False
-
-
-class TestLoadSkillsFromOrgDirectories:
- """Test _load_skills_from_org_directories helper function."""
-
- @pytest.mark.asyncio
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._find_and_load_skill_md_files'
- )
- async def test_load_from_both_directories(
- self, mock_find_and_load, mock_async_remote_workspace, mock_skills_list
- ):
- """Test loading skills from both skills/ and microagents/ directories."""
- # Arrange
- skills_dir_skills = [mock_skills_list[0]]
- microagents_dir_skills = [mock_skills_list[1], mock_skills_list[2]]
- mock_find_and_load.side_effect = [skills_dir_skills, microagents_dir_skills]
-
- # Act
- result_skills, result_microagents = await _load_skills_from_org_directories(
- mock_async_remote_workspace, '/workspace/_org_openhands_owner', '/workspace'
- )
-
- # Assert
- assert result_skills == skills_dir_skills
- assert result_microagents == microagents_dir_skills
- assert mock_find_and_load.call_count == 2
-
- # Verify correct directories were checked
- first_call = mock_find_and_load.call_args_list[0]
- second_call = mock_find_and_load.call_args_list[1]
- assert '/skills' in first_call[0][1]
- assert '/microagents' in second_call[0][1]
-
- @pytest.mark.asyncio
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._find_and_load_skill_md_files'
- )
- async def test_load_with_empty_directories(
- self, mock_find_and_load, mock_async_remote_workspace
- ):
- """Test loading when both directories are empty."""
- # Arrange
- mock_find_and_load.side_effect = [[], []]
-
- # Act
- result_skills, result_microagents = await _load_skills_from_org_directories(
- mock_async_remote_workspace, '/workspace/_org_openhands_owner', '/workspace'
- )
-
- # Assert
- assert result_skills == []
- assert result_microagents == []
-
-
-class TestMergeOrgSkillsWithPrecedence:
- """Test _merge_org_skills_with_precedence helper function."""
-
- def test_merge_no_duplicates(self, mock_skills_list):
- """Test merging skills with no name conflicts."""
- # Arrange
- skills_dir_skills = [mock_skills_list[0]]
- microagents_dir_skills = [mock_skills_list[1], mock_skills_list[2]]
-
- # Act
- result = _merge_org_skills_with_precedence(
- skills_dir_skills, microagents_dir_skills
- )
-
- # Assert
- assert len(result) == 3
- names = {s.name for s in result}
- assert names == {'skill_0', 'skill_1', 'skill_2'}
-
- def test_merge_with_duplicate_skills_dir_wins(self):
- """Test skills/ directory takes precedence over microagents/."""
- # Arrange
- skill_from_microagents = Mock()
- skill_from_microagents.name = 'common_skill'
- skill_from_microagents.source = 'microagents'
-
- skill_from_skills = Mock()
- skill_from_skills.name = 'common_skill'
- skill_from_skills.source = 'skills'
-
- # Act
- result = _merge_org_skills_with_precedence(
- [skill_from_skills], [skill_from_microagents]
- )
-
- # Assert
- assert len(result) == 1
- assert result[0].source == 'skills'
-
- def test_merge_with_empty_lists(self):
- """Test merging with empty skill lists."""
- # Act
- result = _merge_org_skills_with_precedence([], [])
-
- # Assert
- assert result == []
-
- def test_merge_with_only_skills_dir(self, mock_skills_list):
- """Test merging with only skills/ directory populated."""
- # Act
- result = _merge_org_skills_with_precedence([mock_skills_list[0]], [])
-
- # Assert
- assert len(result) == 1
- assert result[0] == mock_skills_list[0]
-
- def test_merge_with_only_microagents_dir(self, mock_skills_list):
- """Test merging with only microagents/ directory populated."""
- # Act
- result = _merge_org_skills_with_precedence([], [mock_skills_list[0]])
-
- # Assert
- assert len(result) == 1
- assert result[0] == mock_skills_list[0]
-
-
-class TestCleanupOrgRepository:
- """Test _cleanup_org_repository helper function."""
-
- @pytest.mark.asyncio
- async def test_cleanup_successful(self, mock_async_remote_workspace):
- """Test successful cleanup of org repository directory."""
- # Arrange
- result_obj = Mock()
- result_obj.exit_code = 0
- mock_async_remote_workspace.execute_command.return_value = result_obj
-
- # Act
- await _cleanup_org_repository(
- mock_async_remote_workspace,
- '/workspace/_org_openhands_owner',
- '/workspace',
- )
-
- # Assert
- mock_async_remote_workspace.execute_command.assert_called_once()
- call_args = mock_async_remote_workspace.execute_command.call_args
- assert 'rm -rf' in call_args[0][0]
- assert '/workspace/_org_openhands_owner' in call_args[0][0]
-
-
-class TestLoadOrgSkills:
- """Test load_org_skills main function."""
-
- @pytest.mark.asyncio
- async def test_load_org_skills_no_selected_repository(
- self, mock_async_remote_workspace
- ):
- """Test load_org_skills returns empty list when no repository selected."""
- # Arrange
- mock_user_context = AsyncMock()
-
- # Act
- result = await load_org_skills(
- mock_async_remote_workspace, None, '/workspace', mock_user_context
- )
-
- # Assert
- assert result == []
-
- @pytest.mark.asyncio
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._validate_repository_for_org_skills'
- )
- async def test_load_org_skills_invalid_repository(
- self, mock_validate, mock_async_remote_workspace
- ):
- """Test load_org_skills returns empty list for invalid repository."""
- # Arrange
- mock_validate.return_value = False
- mock_user_context = AsyncMock()
-
- # Act
- result = await load_org_skills(
- mock_async_remote_workspace, 'invalid', '/workspace', mock_user_context
- )
-
- # Assert
- assert result == []
- mock_validate.assert_called_once_with('invalid')
-
- @pytest.mark.asyncio
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._validate_repository_for_org_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._determine_org_repo_path'
- )
- @patch('openhands.app_server.app_conversation.skill_loader._get_org_repository_url')
- async def test_load_org_skills_no_url_available(
- self,
- mock_get_url,
- mock_determine_path,
- mock_validate,
- mock_async_remote_workspace,
- ):
- """Test load_org_skills returns empty list when URL cannot be retrieved."""
- # Arrange
- mock_validate.return_value = True
- mock_determine_path.return_value = ('owner/.openhands', 'owner')
- mock_get_url.return_value = None
- mock_user_context = AsyncMock()
-
- # Act
- result = await load_org_skills(
- mock_async_remote_workspace,
- 'owner/repo',
- '/workspace',
- mock_user_context,
- )
-
- # Assert
- assert result == []
-
- @pytest.mark.asyncio
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._validate_repository_for_org_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._determine_org_repo_path'
- )
- @patch('openhands.app_server.app_conversation.skill_loader._get_org_repository_url')
- @patch('openhands.app_server.app_conversation.skill_loader._clone_org_repository')
- async def test_load_org_skills_clone_fails(
- self,
- mock_clone,
- mock_get_url,
- mock_determine_path,
- mock_validate,
- mock_async_remote_workspace,
- ):
- """Test load_org_skills returns empty list when clone fails."""
- # Arrange
- mock_validate.return_value = True
- mock_determine_path.return_value = ('owner/.openhands', 'owner')
- mock_get_url.return_value = 'https://github.com/owner/.openhands.git'
- mock_clone.return_value = False
- mock_user_context = AsyncMock()
-
- # Act
- result = await load_org_skills(
- mock_async_remote_workspace,
- 'owner/repo',
- '/workspace',
- mock_user_context,
- )
-
- # Assert
- assert result == []
-
- @pytest.mark.asyncio
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._validate_repository_for_org_skills'
- )
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._determine_org_repo_path'
- )
- @patch('openhands.app_server.app_conversation.skill_loader._get_org_repository_url')
- @patch('openhands.app_server.app_conversation.skill_loader._clone_org_repository')
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._load_skills_from_org_directories'
- )
- @patch('openhands.app_server.app_conversation.skill_loader._cleanup_org_repository')
- async def test_load_org_skills_success(
- self,
- mock_cleanup,
- mock_load_skills,
- mock_clone,
- mock_get_url,
- mock_determine_path,
- mock_validate,
- mock_async_remote_workspace,
- mock_skills_list,
- ):
- """Test successful org skills loading."""
- # Arrange
- mock_validate.return_value = True
- mock_determine_path.return_value = ('owner/.openhands', 'owner')
- mock_get_url.return_value = 'https://github.com/owner/.openhands.git'
- mock_clone.return_value = True
- mock_load_skills.return_value = ([mock_skills_list[0]], [mock_skills_list[1]])
- mock_user_context = AsyncMock()
-
- # Act
- result = await load_org_skills(
- mock_async_remote_workspace,
- 'owner/repo',
- '/workspace',
- mock_user_context,
- )
-
- # Assert
- assert len(result) == 2
- mock_cleanup.assert_called_once()
-
- @pytest.mark.asyncio
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._validate_repository_for_org_skills'
- )
- async def test_load_org_skills_handles_authentication_error(
- self, mock_validate, mock_async_remote_workspace
- ):
- """Test load_org_skills handles AuthenticationError gracefully."""
- # Arrange
- mock_validate.side_effect = AuthenticationError('Auth failed')
- mock_user_context = AsyncMock()
-
- # Act
- result = await load_org_skills(
- mock_async_remote_workspace,
- 'owner/repo',
- '/workspace',
- mock_user_context,
- )
-
- # Assert
- assert result == []
-
- @pytest.mark.asyncio
- @patch(
- 'openhands.app_server.app_conversation.skill_loader._validate_repository_for_org_skills'
- )
- async def test_load_org_skills_handles_general_exception(
- self, mock_validate, mock_async_remote_workspace
- ):
- """Test load_org_skills handles general exceptions gracefully."""
- # Arrange
- mock_validate.side_effect = Exception('Unexpected error')
- mock_user_context = AsyncMock()
-
- # Act
- result = await load_org_skills(
- mock_async_remote_workspace,
- 'owner/repo',
- '/workspace',
- mock_user_context,
- )
-
- # Assert
- assert result == []
-
-
-# ===== Integration Tests =====
-
-
-class TestSkillLoaderIntegration:
- """Integration tests for the skill loader."""
-
- @pytest.mark.asyncio
- @patch('openhands.app_server.app_conversation.skill_loader.load_global_skills')
- @patch('openhands.sdk.context.skills.load_user_skills')
- @patch('openhands.app_server.app_conversation.skill_loader.load_repo_skills')
- async def test_full_loading_workflow(
- self,
- mock_load_repo,
- mock_load_user,
- mock_load_global,
- mock_async_remote_workspace,
- ):
- """Test the full workflow of loading all skill types."""
- # Create distinct mock skills for each source
- global_skill = Mock()
- global_skill.name = 'global_skill'
-
- user_skill = Mock()
- user_skill.name = 'user_skill'
-
- repo_skill = Mock()
- repo_skill.name = 'repo_skill'
-
- mock_load_global.return_value = [global_skill]
- mock_load_user.return_value = [user_skill]
- mock_load_repo.return_value = [repo_skill]
-
- # Simulate loading all sources
- global_skills = mock_load_global()
- user_skills = mock_load_user()
- repo_skills = await mock_load_repo(
- mock_async_remote_workspace, 'owner/repo', '/workspace'
- )
-
- # Merge all skills
- all_skills = merge_skills([global_skills, user_skills, repo_skills])
-
- assert len(all_skills) == 3
- names = {s.name for s in all_skills}
- assert names == {'global_skill', 'user_skill', 'repo_skill'}
-
- @pytest.mark.asyncio
- @patch('openhands.app_server.app_conversation.skill_loader.load_global_skills')
- @patch('openhands.sdk.context.skills.load_user_skills')
- @patch('openhands.app_server.app_conversation.skill_loader.load_repo_skills')
- async def test_loading_with_override_precedence(
- self,
- mock_load_repo,
- mock_load_user,
- mock_load_global,
- mock_async_remote_workspace,
- ):
- """Test that repo skills override user skills, and user skills override global."""
- # Create skills with same name but different sources
- global_skill = Mock()
- global_skill.name = 'common_skill'
- global_skill.source = 'global'
-
- user_skill = Mock()
- user_skill.name = 'common_skill'
- user_skill.source = 'user'
-
- repo_skill = Mock()
- repo_skill.name = 'common_skill'
- repo_skill.source = 'repo'
-
- mock_load_global.return_value = [global_skill]
- mock_load_user.return_value = [user_skill]
- mock_load_repo.return_value = [repo_skill]
-
- # Load and merge in correct precedence order
- global_skills = mock_load_global()
- user_skills = mock_load_user()
- repo_skills = await mock_load_repo(
- mock_async_remote_workspace, 'owner/repo', '/workspace'
- )
-
- all_skills = merge_skills([global_skills, user_skills, repo_skills])
-
- # Should have only one skill with repo source (highest precedence)
- assert len(all_skills) == 1
- assert all_skills[0].source == 'repo'
-
- @pytest.mark.asyncio
- @patch('openhands.app_server.app_conversation.skill_loader.load_global_skills')
- @patch('openhands.sdk.context.skills.load_user_skills')
- @patch('openhands.app_server.app_conversation.skill_loader.load_org_skills')
- @patch('openhands.app_server.app_conversation.skill_loader.load_repo_skills')
- async def test_loading_with_org_skills_precedence(
- self,
- mock_load_repo,
- mock_load_org,
- mock_load_user,
- mock_load_global,
- mock_async_remote_workspace,
- ):
- """Test that org skills fit correctly in precedence order."""
- # Arrange
- # Create skills with same name but different sources
- global_skill = Mock()
- global_skill.name = 'shared_skill'
- global_skill.priority = 'low'
-
- user_skill = Mock()
- user_skill.name = 'shared_skill'
- user_skill.priority = 'medium'
-
- org_skill = Mock()
- org_skill.name = 'shared_skill'
- org_skill.priority = 'high'
-
- repo_skill = Mock()
- repo_skill.name = 'shared_skill'
- repo_skill.priority = 'highest'
-
- mock_load_global.return_value = [global_skill]
- mock_load_user.return_value = [user_skill]
- mock_load_org.return_value = [org_skill]
- mock_load_repo.return_value = [repo_skill]
-
- mock_user_context = AsyncMock()
-
- # Act
- global_skills = mock_load_global()
- user_skills = mock_load_user()
- org_skills = await mock_load_org(
- mock_async_remote_workspace, 'owner/repo', '/workspace', mock_user_context
- )
- repo_skills = await mock_load_repo(
- mock_async_remote_workspace, 'owner/repo', '/workspace'
- )
-
- # Merge with correct precedence: global < user < org < repo
- all_skills = merge_skills([global_skills, user_skills, org_skills, repo_skills])
-
- # Assert
- assert len(all_skills) == 1
- assert all_skills[0].priority == 'highest' # Repo has highest precedence
-
- @pytest.mark.asyncio
- @patch('openhands.app_server.app_conversation.skill_loader.load_global_skills')
- @patch('openhands.sdk.context.skills.load_user_skills')
- @patch('openhands.app_server.app_conversation.skill_loader.load_org_skills')
- @patch('openhands.app_server.app_conversation.skill_loader.load_repo_skills')
- async def test_loading_org_skills_with_unique_names(
- self,
- mock_load_repo,
- mock_load_org,
- mock_load_user,
- mock_load_global,
- mock_async_remote_workspace,
- ):
- """Test loading org skills with unique names alongside other sources."""
- # Arrange
- global_skill = Mock()
- global_skill.name = 'global_skill'
-
- user_skill = Mock()
- user_skill.name = 'user_skill'
-
- org_skill = Mock()
- org_skill.name = 'org_skill'
-
- repo_skill = Mock()
- repo_skill.name = 'repo_skill'
-
- mock_load_global.return_value = [global_skill]
- mock_load_user.return_value = [user_skill]
- mock_load_org.return_value = [org_skill]
- mock_load_repo.return_value = [repo_skill]
-
- mock_user_context = AsyncMock()
-
- # Act
- global_skills = mock_load_global()
- user_skills = mock_load_user()
- org_skills = await mock_load_org(
- mock_async_remote_workspace, 'owner/repo', '/workspace', mock_user_context
- )
- repo_skills = await mock_load_repo(
- mock_async_remote_workspace, 'owner/repo', '/workspace'
- )
-
- all_skills = merge_skills([global_skills, user_skills, org_skills, repo_skills])
-
- # Assert
- assert len(all_skills) == 4
- names = {s.name for s in all_skills}
- assert names == {'global_skill', 'user_skill', 'org_skill', 'repo_skill'}