diff --git a/ACPAGENT_IMPLEMENTATION.md b/ACPAGENT_IMPLEMENTATION.md new file mode 100644 index 00000000000..813183f6c49 --- /dev/null +++ b/ACPAGENT_IMPLEMENTATION.md @@ -0,0 +1,186 @@ +# ACPAgent Implementation + +This document describes the minimal implementation of `ACPAgent` for the OpenHands SDK. + +## Overview + +`ACPAgent` is an Agent-Client Protocol (ACP) client implementation that allows OpenHands to communicate with ACP servers like Claude-Code or Gemini CLI. It acts as a bridge between the OpenHands SDK and ACP servers. + +## Architecture + +``` +┌─────────────────────────┐ +│ OpenHands SDK │ +│ (Conversation) │ +└───────────┬─────────────┘ + │ + ▼ +┌─────────────────────────┐ +│ ACPAgent │ +│ (ACP Client) │ +└───────────┬─────────────┘ + │ JSON-RPC 2.0 + │ via stdin/stdout + ▼ +┌─────────────────────────┐ +│ ACP Server │ +│ (claude-code, etc.) │ +└─────────────────────────┘ +``` + +## Key Features + +### Implemented + +1. **Basic ACP Protocol Support** + - JSON-RPC 2.0 communication + - Session initialization (`session/new`) + - Prompt/response flow (`session/prompt`) + - Subprocess management for ACP servers + +2. **SDK Integration** + - Inherits from `AgentBase` + - Implements `step()` method + - Converts SDK conversation state to ACP messages + - Translates ACP responses back to SDK events + +3. **Feature Validation** + - Checks for unsupported features at initialization + - Raises `NotImplementedError` for: + - Custom tools + - MCP configuration + - Agent context (microagents) + - Security analyzers + - Context condensers + +### Not Yet Supported + +The following SDK features are not currently supported by ACPAgent: +- Custom tools (ACP server manages its own tools) +- MCP configuration +- Microagents +- Security analyzers +- Context condensers +- Tool filtering + +## Usage Example + +```python +from openhands.sdk import LLM, Conversation +from openhands.sdk.agent import ACPAgent + +# Create LLM configuration +llm = LLM(model="claude-sonnet-4-20250514", api_key="your-key") + +# Create ACPAgent with ACP server command +agent = ACPAgent( + llm=llm, + acp_command=["npx", "-y", "claude-code-acp"], + acp_args=[], +) + +# Create conversation +conversation = Conversation(agent=agent, workspace="/tmp/workspace") + +# Send a message +conversation.send_message("Hello! Can you help me write a Python script?") + +# Run the conversation +conversation.run() + +# Check the response +for event in conversation.state.events: + if isinstance(event, MessageEvent): + print(f"Message: {event.content}") +``` + +## Implementation Details + +### File Structure + +``` +openhands-sdk/openhands/sdk/agent/ +├── acp_agent.py # ACPAgent implementation +└── __init__.py # Export ACPAgent + +examples/01_standalone_sdk/ +└── 27_acp_agent_example.py # Usage example + +tests/sdk/agent/ +└── test_acp_agent.py # Unit tests +``` + +### ACP Protocol Flow + +1. **Initialization** + - Start ACP server subprocess + - Send `initialize` request + - Create new session with `session/new` + +2. **Message Exchange** + - Convert SDK messages to ACP format + - Send `session/prompt` request + - Parse ACP response + - Create SDK MessageEvent + +3. **Cleanup** + - Terminate ACP server subprocess + +### JSON-RPC Message Format + +Request: +```json +{ + "jsonrpc": "2.0", + "id": 1, + "method": "session/prompt", + "params": { + "sessionId": "session-uuid", + "prompt": "User message here" + } +} +``` + +Response: +```json +{ + "jsonrpc": "2.0", + "id": 1, + "result": { + "response": "Agent response here" + } +} +``` + +## Testing + +Run the ACPAgent tests: +```bash +uv run pytest tests/sdk/agent/test_acp_agent.py -v +``` + +Tests cover: +- Agent initialization +- Feature validation +- Subprocess management +- Error handling + +## Future Work + +### Short Term +1. Complete JSON-RPC implementation +2. Handle all ACP protocol events +3. Implement proper error handling +4. Add more comprehensive tests + +### Long Term +1. Support microagents through ACP +2. Tool translation layer +3. Security policy integration +4. Context management + +## References + +- [Agent-Client Protocol Specification](https://agentclientprotocol.com/protocol/overview) +- [Claude-Code ACP](https://github.com/zed-industries/claude-code-acp) +- [OpenHands SDK Documentation](https://github.com/OpenHands/docs/tree/main/sdk) diff --git a/examples/01_standalone_sdk/27_acp_agent_example.py b/examples/01_standalone_sdk/27_acp_agent_example.py new file mode 100644 index 00000000000..5f5923228a9 --- /dev/null +++ b/examples/01_standalone_sdk/27_acp_agent_example.py @@ -0,0 +1,67 @@ +""" +Minimal example demonstrating ACPAgent usage with the OpenHands SDK. + +This example shows how to use ACPAgent to interact with ACP servers +(like Claude-Code or Gemini CLI) through the Agent-Client Protocol. + +Prerequisites: + - An ACP server command available (e.g., npx -y claude-code-acp) + - API keys for the ACP server if required (managed by the ACP server) + +Note: + - ACPAgent does NOT require an LLM parameter - the ACP server manages its own LLM + - This is a minimal implementation. Many advanced SDK features + (microagents, custom tools, security analyzers) are not yet supported. +""" + +import os + +from openhands.sdk.agent import ACPAgent +from openhands.sdk.conversation import LocalConversation +from openhands.sdk.event import MessageEvent + + +# Create an ACPAgent that connects to an ACP server +# Example 1: Using Claude-Code ACP server (requires claude-code-acp to be available) +agent = ACPAgent( + acp_command=["npx", "-y", "claude-code-acp"], + acp_args=[], # Add any additional arguments for the ACP server +) + +# Example 2: Using a local ACP server script +# agent = ACPAgent( +# acp_command=["python", "/path/to/your/acp_server.py"], +# acp_args=["--verbose"], +# ) + +# Example 3: Using Gemini CLI ACP server (hypothetical) +# agent = ACPAgent( +# acp_command=["gemini-cli-acp"], +# acp_args=[], +# ) + +# Create a conversation with the agent +cwd = os.getcwd() +conversation = LocalConversation(agent=agent, workspace=cwd) + +# Send a message to the agent +print("Sending message to ACP agent...") +conversation.send_message("Hello! Please tell me about the Agent-Client Protocol.") + +# Run the conversation +print("Running conversation...") +conversation.run() + +# Access the events from the conversation state +print("\nConversation completed!") +print(f"Total events: {len(conversation.state.events)}") + +# Print the last assistant message event +for event in reversed(list(conversation.state.events)): + if isinstance(event, MessageEvent) and event.source == "agent": + if event.llm_message and event.llm_message.content: + for content in event.llm_message.content: + print(f"\nAgent response: {content}") + break + +print("\nNote: The ACP server subprocess will be automatically cleaned up.") diff --git a/openhands-sdk/openhands/sdk/agent/__init__.py b/openhands-sdk/openhands/sdk/agent/__init__.py index 6fd3a744871..30610ce9510 100644 --- a/openhands-sdk/openhands/sdk/agent/__init__.py +++ b/openhands-sdk/openhands/sdk/agent/__init__.py @@ -1,8 +1,10 @@ +from openhands.sdk.agent.acp_agent import ACPAgent from openhands.sdk.agent.agent import Agent from openhands.sdk.agent.base import AgentBase __all__ = [ + "ACPAgent", "Agent", "AgentBase", ] diff --git a/openhands-sdk/openhands/sdk/agent/acp_agent.py b/openhands-sdk/openhands/sdk/agent/acp_agent.py new file mode 100644 index 00000000000..43ee486e7ee --- /dev/null +++ b/openhands-sdk/openhands/sdk/agent/acp_agent.py @@ -0,0 +1,377 @@ +""" +ACPAgent: An Agent-Client Protocol client implementation for OpenHands SDK. + +This agent acts as an ACP client that communicates with ACP servers +(like Claude-Code, Gemini CLI) to provide AI agent capabilities through +the Agent-Client Protocol (https://agentclientprotocol.com/). + +Uses the official agent-client-protocol Python SDK for protocol communication. +""" + +import asyncio +import asyncio.subprocess as aio_subprocess +import os +from typing import TYPE_CHECKING, Any + +from pydantic import Field + +from openhands.sdk.agent.base import AgentBase +from openhands.sdk.conversation.state import ConversationExecutionStatus +from openhands.sdk.event import MessageEvent +from openhands.sdk.llm import Message, TextContent +from openhands.sdk.logger import get_logger + + +if TYPE_CHECKING: + from acp import ClientSideConnection # type: ignore[import-not-found] + + from openhands.sdk.conversation import ( + ConversationCallbackType, + ConversationState, + ) + from openhands.sdk.conversation.impl.local_conversation import LocalConversation + +logger = get_logger(__name__) + +# Lazy import ACP SDK to avoid hard dependency +_ACP_AVAILABLE = False +try: + from acp import ( # type: ignore[import-not-found] + PROTOCOL_VERSION, + Client, + ClientSideConnection, + InitializeRequest, + NewSessionRequest, + PromptRequest, + RequestError, + text_block, + ) + from acp.schema import ( # type: ignore[import-not-found] + AgentMessageChunk, + AudioContentBlock, + ClientCapabilities, + EmbeddedResourceContentBlock, + ImageContentBlock, + Implementation, + ResourceContentBlock, + TextContentBlock, + ) + + _ACP_AVAILABLE = True + + class _OpenHandsACPClient(Client): # type: ignore[misc] + """ + OpenHands implementation of ACP Client interface. + + This client implementation accumulates agent responses and provides + minimal implementations of required ACP client methods. + """ + + def __init__(self) -> None: + super().__init__() + self.accumulated_text: list[str] = [] + + async def requestPermission(self, params: Any) -> Any: # type: ignore[override] # noqa: ARG002 + raise RequestError.method_not_found("session/request_permission") + + async def writeTextFile(self, params: Any) -> Any: # type: ignore[override] # noqa: ARG002 + raise RequestError.method_not_found("fs/write_text_file") + + async def readTextFile(self, params: Any) -> Any: # type: ignore[override] # noqa: ARG002 + raise RequestError.method_not_found("fs/read_text_file") + + async def createTerminal(self, params: Any) -> Any: # type: ignore[override] # noqa: ARG002 + raise RequestError.method_not_found("terminal/create") + + async def terminalOutput(self, params: Any) -> Any: # type: ignore[override] # noqa: ARG002 + raise RequestError.method_not_found("terminal/output") + + async def releaseTerminal(self, params: Any) -> Any: # type: ignore[override] # noqa: ARG002 + raise RequestError.method_not_found("terminal/release") + + async def waitForTerminalExit(self, params: Any) -> Any: # type: ignore[override] # noqa: ARG002 + raise RequestError.method_not_found("terminal/wait_for_exit") + + async def killTerminal(self, params: Any) -> Any: # type: ignore[override] # noqa: ARG002 + raise RequestError.method_not_found("terminal/kill") + + async def sessionUpdate(self, params: Any) -> None: # type: ignore[override] + """Handle session updates from the ACP server.""" + update = params.update + if not isinstance(update, AgentMessageChunk): + return + + content = update.content + text: str + if isinstance(content, TextContentBlock): + text = content.text + elif isinstance(content, ImageContentBlock): + text = "" + elif isinstance(content, AudioContentBlock): + text = "