Skip to content
Closed
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
186 changes: 186 additions & 0 deletions ACPAGENT_IMPLEMENTATION.md
Original file line number Diff line number Diff line change
@@ -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)
67 changes: 67 additions & 0 deletions examples/01_standalone_sdk/27_acp_agent_example.py
Original file line number Diff line number Diff line change
@@ -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.")
2 changes: 2 additions & 0 deletions openhands-sdk/openhands/sdk/agent/__init__.py
Original file line number Diff line number Diff line change
@@ -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",
]
Loading