# Agent2Agent (A2A) Protocol Support

VT Code implements the [Agent2Agent (A2A) Protocol](https://a2a-protocol.org), an open standard enabling communication and interoperability between AI agents.

## Overview

The A2A Protocol enables:

-   **Agent Discovery**: Via Agent Cards at `/.well-known/agent-card.json`
-   **Task Lifecycle Management**: States like `submitted`, `working`, `completed`, `failed`
-   **Real-time Streaming**: Via Server-Sent Events (SSE)
-   **Rich Content Types**: Text, file, and structured data parts
-   **Multi-agent workflows**: Agents can discover and communicate with each other

## Architecture

VT Code's A2A support is organized into the `vtcode-core::a2a` module with the following components:

### Core Types (`types.rs`)

-   **Task**: Represents a stateful unit of work with ID, status, artifacts, and history
-   **Message**: Communication unit with role (user/agent), content parts, and metadata
-   **Part**: Content unit - text, file (URI or inline), or structured JSON data
-   **TaskState**: Lifecycle states - submitted, working, completed, failed, canceled, etc.
-   **Artifact**: Tangible output generated by tasks

### Task Manager (`task_manager.rs`)

-   In-memory task storage with concurrent access via `Arc<RwLock>`
-   Task creation, retrieval, status updates, artifact management
-   Eviction of old completed tasks when at capacity
-   Filtering and pagination support

### Agent Card & Discovery (`agent_card.rs`)

-   Agent metadata for capability advertisement
-   Describes agent identity, version, capabilities, and security requirements
-   Served at `/.well-known/agent-card.json` for discovery
-   Includes support for skills and extensions

### JSON-RPC Protocol (`rpc.rs`)

-   JSON-RPC 2.0 compatible request/response structures
-   RPC method constants: `message/send`, `message/stream`, `tasks/get`, `tasks/list`, `tasks/cancel`
-   Request parameters for each method
-   Streaming event types for SSE

### Error Handling (`errors.rs`)

-   Standard JSON-RPC 2.0 error codes (-32700 to -32603)
-   A2A-specific error codes (-32001 to -32007)
-   Type-safe `A2aErrorCode` enum for error handling
-   `A2aError` with detailed error context

### HTTP Server (`server.rs`, feature: `a2a-server`)

-   Axum-based HTTP server for A2A protocol endpoints
-   Endpoints:
    -   `GET /.well-known/agent-card.json` - Agent discovery
    -   `POST /a2a` - JSON-RPC RPC requests
    -   `POST /a2a/stream` - Streaming with SSE (placeholder)
-   CORS support for cross-origin requests
-   Type-safe error responses with appropriate HTTP status codes

## Usage

### Basic Setup

```rust
use vtcode_core::a2a::{TaskManager, AgentCard};

// Create a task manager
let manager = TaskManager::new();

// Create an agent card for discovery
let card = AgentCard::vtcode_default("http://localhost:8080");
```

### Creating and Managing Tasks

```rust
use vtcode_core::a2a::types::{Message, MessageRole};

// Create a task
let task = manager.create_task(Some("conversation-id".to_string())).await;

// Add a message
let msg = Message::user_text("What should I do?");
manager.add_message(&task.id, msg).await?;

// Update task status
manager.update_status(&task.id, TaskState::Working, None).await?;

// Add an artifact
let artifact = Artifact::text("output", "Generated content");
manager.add_artifact(&task.id, artifact).await?;
```

### Running the HTTP Server

```rust
use vtcode_core::a2a::server::{A2aServerState, run};
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
    let state = A2aServerState::vtcode_default("http://localhost:8080");
    let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
    run(state, addr).await.unwrap();
}
```

Build with the `a2a-server` feature:

```bash
cargo build --features a2a-server
```

## JSON-RPC API Reference

### message/send

Send a message to initiate or continue a task.

**Request:**

```json
{
    "jsonrpc": "2.0",
    "method": "message/send",
    "params": {
        "message": {
            "role": "user",
            "parts": [{ "type": "text", "text": "Hello agent" }]
        },
        "taskId": "task-123"
    },
    "id": "req-1"
}
```

**Response:**

```json
{
    "jsonrpc": "2.0",
    "result": {
        "id": "task-123",
        "contextId": "ctx-1",
        "status": {
            "state": "working",
            "timestamp": "2025-01-01T00:00:00Z"
        },
        "artifacts": [],
        "history": []
    },
    "id": "req-1"
}
```

### tasks/get

Retrieve the current state of a task.

**Request:**

```json
{
    "jsonrpc": "2.0",
    "method": "tasks/get",
    "params": {
        "id": "task-123"
    },
    "id": "req-2"
}
```

### tasks/list

List tasks with optional filtering.

**Request:**

```json
{
    "jsonrpc": "2.0",
    "method": "tasks/list",
    "params": {
        "contextId": "ctx-1",
        "pageSize": 50
    },
    "id": "req-3"
}
```

### tasks/cancel

Cancel a running task.

**Request:**

```json
{
    "jsonrpc": "2.0",
    "method": "tasks/cancel",
    "params": {
        "id": "task-123"
    },
    "id": "req-4"
}
```

## Error Handling

JSON-RPC errors follow this format:

```json
{
    "jsonrpc": "2.0",
    "error": {
        "code": -32001,
        "message": "Task not found",
        "data": {}
    },
    "id": "req-1"
}
```

Common error codes:

-   `-32600` (InvalidRequest): Invalid JSON-RPC request
-   `-32601` (MethodNotFound): Unknown method
-   `-32602` (InvalidParams): Invalid method parameters
-   `-32001` (TaskNotFound): Task does not exist
-   `-32002` (TaskNotCancelable): Cannot cancel task in current state

## Implementation Status

### Phase 1: Core Types and Task Manager

-   Task and message types
-   Task lifecycle management
-   In-memory storage
-   Full test coverage

### Phase 2: HTTP Server

-   Axum-based server implementation
-   Agent discovery endpoint
-   JSON-RPC request handlers
-   Error response handling
-   CORS support
-   Basic SSE placeholder

### Phase 3: Client & Advanced Features

-   A2A client for agent-to-agent communication
-   Full SSE streaming implementation
-   Push notification support
-   Authentication handling

## Configuration

A2A server can be configured via environment variables or `vtcode.toml`:

```toml
[a2a]
enabled = true
host = "127.0.0.1"
port = 8080
max_tasks = 1000
```

## Testing

Run A2A tests:

```bash
cargo test --package vtcode-core a2a::
cargo test --package vtcode-core --features a2a-server
```

## References

-   [A2A Protocol Specification](https://a2a-protocol.org)
-   [VT Code Architecture](../ARCHITECTURE.md)
-   [Contributing Guide](../../docs/CONTRIBUTING.md)
