Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/01_standalone_sdk/25_agent_delegation.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@
get_logger,
)
from openhands.sdk.context import Skill
from openhands.sdk.subagent import register_agent
from openhands.sdk.tool import register_tool
from openhands.tools.delegate import (
DelegateTool,
DelegationVisualizer,
register_agent,
)
from openhands.tools.preset.default import get_default_tools

Expand Down
3 changes: 2 additions & 1 deletion examples/01_standalone_sdk/41_task_tool_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@

from openhands.sdk import LLM, Agent, AgentContext, Conversation, Tool
from openhands.sdk.context import Skill
from openhands.tools.delegate import DelegationVisualizer, register_agent
from openhands.sdk.subagent import register_agent
from openhands.tools.delegate import DelegationVisualizer
from openhands.tools.task import TaskToolSet


Expand Down
69 changes: 69 additions & 0 deletions examples/01_standalone_sdk/42_file_based_subagents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""Example: Defining a sub-agent inline with AgentDefinition.

Defines a grammar-checker sub-agent using AgentDefinition, registers it,
and delegates work to it from an orchestrator agent. The orchestrator then
asks the builtin default agent to judge the results.
"""

import os
from pathlib import Path

from openhands.sdk import (
LLM,
Agent,
Conversation,
Tool,
agent_definition_to_factory,
register_agent,
)
from openhands.sdk.subagent import AgentDefinition
from openhands.sdk.tool import register_tool
from openhands.tools.delegate import DelegateTool, DelegationVisualizer


# 1. Define a sub-agent using AgentDefinition
grammar_checker = AgentDefinition(
name="grammar-checker",
description="Checks documents for grammatical errors.",
tools=["file_editor"],
system_prompt="You are a grammar expert. Find and list grammatical errors.",
)

# 2. Register it in the delegate registry
register_agent(
name=grammar_checker.name,
factory_func=agent_definition_to_factory(grammar_checker),
description=grammar_checker.description,
)

# 3. Set up the orchestrator agent with the DelegateTool
llm = LLM(
model=os.getenv("LLM_MODEL", "anthropic/claude-sonnet-4-5-20250929"),
api_key=os.getenv("LLM_API_KEY"),
base_url=os.getenv("LLM_BASE_URL"),
usage_id="file-agents-demo",
)

register_tool("DelegateTool", DelegateTool)
main_agent = Agent(
llm=llm,
tools=[Tool(name="DelegateTool")],
)
conversation = Conversation(
agent=main_agent,
workspace=Path.cwd(),
visualizer=DelegationVisualizer(name="Orchestrator"),
)

# 4. Ask the orchestrator to delegate to our agent
task = (
"Please delegate to the grammar-checker agent and ask it to review "
"the README.md file in search of grammatical errors.\n"
"Then ask the default agent to judge the errors."
)
conversation.send_message(task)
conversation.run()

cost = conversation.conversation_stats.get_combined_metrics().accumulated_cost
print(f"\nTotal cost: ${cost:.4f}")
print(f"EXAMPLE_COST: {cost:.4f}")
12 changes: 12 additions & 0 deletions openhands-sdk/openhands/sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@
create_mcp_tools,
)
from openhands.sdk.plugin import Plugin
from openhands.sdk.subagent import (
agent_definition_to_factory,
load_agents_from_dir,
load_project_agents,
load_user_agents,
register_agent,
)
from openhands.sdk.tool import (
Action,
Observation,
Expand Down Expand Up @@ -113,6 +120,11 @@
"Workspace",
"LocalWorkspace",
"RemoteWorkspace",
"register_agent",
"load_project_agents",
"load_user_agents",
"load_agents_from_dir",
"agent_definition_to_factory",
"load_project_skills",
"load_skills_from_dir",
"load_user_skills",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@
from openhands.sdk.security.confirmation_policy import (
ConfirmationPolicyBase,
)
from openhands.sdk.subagent import (
AgentDefinition,
register_file_agents,
register_plugin_agents,
)
from openhands.sdk.subagent.registry import register_builtins_agents
from openhands.sdk.tool.schema import Action, Observation
from openhands.sdk.utils.cipher import Cipher
from openhands.sdk.workspace import LocalWorkspace
Expand Down Expand Up @@ -310,6 +316,7 @@ def _ensure_plugins_loaded(self) -> None:
return

all_plugin_hooks: list[HookConfig] = []
all_plugin_agents: list[AgentDefinition] = []

# Load plugins if specified
if self._plugin_specs:
Expand Down Expand Up @@ -347,6 +354,10 @@ def _ensure_plugins_loaded(self) -> None:
if plugin.hooks and not plugin.hooks.is_empty():
all_plugin_hooks.append(plugin.hooks)

# Collect agent definitions
if plugin.agents:
all_plugin_agents.extend(plugin.agents)

Comment thread
VascoSch92 marked this conversation as resolved.
Resolved
# Update agent with merged content
self.agent = self.agent.model_copy(
update={
Expand All @@ -361,6 +372,10 @@ def _ensure_plugins_loaded(self) -> None:

logger.info(f"Loaded {len(self._plugin_specs)} plugin(s) via Conversation")

# Register file-based agents defined in plugins
if all_plugin_agents:
register_plugin_agents(all_plugin_agents)

# Combine explicit hook_config with plugin hooks
# Explicit hooks run first (before plugin hooks)
final_hook_config = self._pending_hook_config
Expand All @@ -387,21 +402,44 @@ def _ensure_plugins_loaded(self) -> None:

self._plugins_loaded = True

def _register_file_based_agents(self) -> None:
"""Discover and register file-based agents into the agent registry.

Agents are loaded from Markdown definition files and registered via
`register_agent_if_absent`, so they never overwrite agents that were
already registered programmatically or by plugins.

Registration order (highest to lowest priority):
1. Programmatic `register_agent()` calls (already in the registry)
2. Plugin agents (registered during plugin loading, i.e.,
in _ensure_plugins_loaded())
3. Project-level file agents (`{project}/.agents/agents/*.md`,
then `{project}/.openhands/agents/*.md`)
4. User-level file agents (`~/.agents/agents/*.md`,
then `~/.openhands/agents/*.md`)
5. SDK builtin agents (`subagent/builtins/*.md`)
"""
# register project-level and then user-level file-based agents
register_file_agents(self.workspace.working_dir)
# register builtins agents
register_builtins_agents()

def _ensure_agent_ready(self) -> None:
"""Ensure agent is fully initialized with plugins loaded.
"""Ensure the agent is fully initialized with plugins and agents loaded.

This method combines plugin loading and agent initialization to ensure
the agent is initialized exactly once with complete configuration.
Performs one-time lazy initialization on the first `send_message()`
or `run()` call. The steps executed (in order) are:

Called lazily on first send_message() or run() to:
1. Load plugins (if specified)
2. Initialize agent with complete plugin config and hooks
3. Register LLMs in the registry
1. Load plugins (merges skills, MCP config, and hooks).
2. Register file-based agents into the agent registry.
3. Initialize the agent with complete plugin config and hooks.
4. Register LLMs in the LLM registry.

This preserves the design principle that constructors should not perform
I/O or error-prone operations, while eliminating double initialization.

Thread-safe: Uses state lock to prevent concurrent initialization.
Thread-safe: uses a double-checked lock on the conversation state to
prevent concurrent initialization.
"""
# Fast path: if already initialized, skip lock acquisition entirely.
# This is crucial for concurrent send_message() calls during run(),
Expand All @@ -419,6 +457,9 @@ def _ensure_agent_ready(self) -> None:
# Load plugins first (merges skills, MCP config, hooks)
self._ensure_plugins_loaded()

# register file-based agents
self._register_file_based_agents()

# Initialize agent with complete configuration
self.agent.init_state(self._state, on_event=self._on_event)

Expand Down
2 changes: 0 additions & 2 deletions openhands-sdk/openhands/sdk/plugin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
from openhands.sdk.plugin.loader import load_plugins
from openhands.sdk.plugin.plugin import Plugin
from openhands.sdk.plugin.types import (
AgentDefinition,
CommandDefinition,
Marketplace,
MarketplaceMetadata,
Expand All @@ -36,7 +35,6 @@
"PluginAuthor",
"PluginSource",
"ResolvedPluginSource",
"AgentDefinition",
"CommandDefinition",
# Plugin loading
"load_plugins",
Expand Down
2 changes: 1 addition & 1 deletion openhands-sdk/openhands/sdk/plugin/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@
from openhands.sdk.logger import get_logger
from openhands.sdk.plugin.fetch import fetch_plugin
from openhands.sdk.plugin.types import (
AgentDefinition,
CommandDefinition,
PluginAuthor,
PluginManifest,
)
from openhands.sdk.subagent.schema import AgentDefinition


if TYPE_CHECKING:
Expand Down
100 changes: 0 additions & 100 deletions openhands-sdk/openhands/sdk/plugin/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from __future__ import annotations

import json
import re
from pathlib import Path
from typing import TYPE_CHECKING, Any

Expand Down Expand Up @@ -177,105 +176,6 @@ class PluginManifest(BaseModel):
model_config = {"extra": "allow"}


def _extract_examples(description: str) -> list[str]:
"""Extract <example> tags from description for agent triggering."""
pattern = r"<example>(.*?)</example>"
matches = re.findall(pattern, description, re.DOTALL | re.IGNORECASE)
return [m.strip() for m in matches if m.strip()]


class AgentDefinition(BaseModel):
"""Agent definition loaded from markdown file.

Agents are specialized configurations that can be triggered based on
user input patterns. They define custom system prompts and tool access.
"""

name: str = Field(description="Agent name (from frontmatter or filename)")
description: str = Field(default="", description="Agent description")
model: str = Field(
default="inherit", description="Model to use ('inherit' uses parent model)"
)
color: str | None = Field(default=None, description="Display color for the agent")
tools: list[str] = Field(
default_factory=list, description="List of allowed tools for this agent"
)
system_prompt: str = Field(default="", description="System prompt content")
source: str | None = Field(
default=None, description="Source file path for this agent"
)
# whenToUse examples extracted from description
when_to_use_examples: list[str] = Field(
default_factory=list,
description="Examples of when to use this agent (for triggering)",
)
# Raw frontmatter for any additional fields
metadata: dict[str, Any] = Field(
default_factory=dict, description="Additional metadata from frontmatter"
)

@classmethod
def load(cls, agent_path: Path) -> AgentDefinition:
"""Load an agent definition from a markdown file.

Agent markdown files have YAML frontmatter with:
- name: Agent name
- description: Description with optional <example> tags for triggering
- model: Model to use (default: 'inherit')
- color: Display color
- tools: List of allowed tools

The body of the markdown is the system prompt.

Args:
agent_path: Path to the agent markdown file.

Returns:
Loaded AgentDefinition instance.
"""
with open(agent_path) as f:
post = frontmatter.load(f)

fm = post.metadata
content = post.content.strip()

# Extract frontmatter fields with proper type handling
name = str(fm.get("name", agent_path.stem))
description = str(fm.get("description", ""))
model = str(fm.get("model", "inherit"))
color_raw = fm.get("color")
color: str | None = str(color_raw) if color_raw is not None else None
tools_raw = fm.get("tools", [])

# Ensure tools is a list of strings
tools: list[str]
if isinstance(tools_raw, str):
tools = [tools_raw]
elif isinstance(tools_raw, list):
tools = [str(t) for t in tools_raw]
else:
tools = []

# Extract whenToUse examples from description
when_to_use_examples = _extract_examples(description)

# Remove known fields from metadata to get extras
known_fields = {"name", "description", "model", "color", "tools"}
metadata = {k: v for k, v in fm.items() if k not in known_fields}

return cls(
name=name,
description=description,
model=model,
color=color,
tools=tools,
system_prompt=content,
source=str(agent_path),
when_to_use_examples=when_to_use_examples,
metadata=metadata,
)


class CommandDefinition(BaseModel):
"""Command definition loaded from markdown file.

Expand Down
Loading
Loading