Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(gateway): add A2A ingress channel and interconnect design doc

yechenzhen84cac06e7ace
diff --git a/docs/en/A2A.md b/docs/en/A2A.md
new file mode 100644
index 0000000000..eb50c71410
--- /dev/null
+++ b/docs/en/A2A.md
@@ -0,0 +1,145 @@
+# A2A Integration Guide
+
+This page explains the Gateway-side **A2A Server** (`A2AChannel`): implementation location, configuration, mapping to internal `Message`/E2A, and local verification commands. For outbound A2A (agent calling external services), see section 7.
+
+> **Implementation**: `jiuwenclaw/channel/a2a_channel.py` (`A2AChannel` + `a2a-sdk`). **Entrypoint process**: `python -m jiuwenclaw.app_gateway` (registered and started in `jiuwenclaw/app_gateway.py`). In case of mismatch, source code is the source of truth.
+
+---
+
+## 0. Document Location and Source of Truth
+
+| Location | Role |
+|------|------|
+| **docs/en/A2A.md** (this page) | Integration and dev debugging: modules, config, mapping, verification |
+| `jiuwenclaw/channel/a2a_channel.py` | A2A HTTP service, `AgentCard`, request/response to `Message` conversion |
+| `jiuwenclaw/app_gateway.py` | Env loading, `A2AChannel` construction, `channel_manager.register_channel` |
+| `jiuwenclaw/gateway/message_handler.py` | Gateway↔AgentServer E2A exchange and internal `Message` orchestration |
+| `jiuwenclaw/gateway/channel_manager.py` | Channel registration and `robot_messages` → `Channel.send` dispatch |
+| [E2A-protocol.md](E2A-protocol.md) | Inner protocol between Gateway and AgentServer |
+
+---
+
+## 1. Responsibility Boundary
+
+- **Inbound (this page)**: external A2A client → `A2AChannel` → `ChannelManager` → `MessageHandler` → E2A → AgentServer; responses return through the same path, emitted as `TaskStatusUpdateEvent` / `TaskArtifactUpdateEvent` (streaming) or aggregated result (non-streaming).
+- **Outbound**: Agent-side access to external A2A services (for example via A2A MCP Hub style tooling) belongs to the AgentServer adapter layer (see section 7), not `A2AChannel`.
+
+---
+
+## 2. Comparison with Web / ACP Channels
+
+| Item | Web | ACP | A2A (current) |
+|------|-----|-----|-------------|
+| Bindings | `WEB_HOST` / `WEB_PORT` / `WEB_PATH` | `ACP_GATEWAY_*` | `A2A_SERVER_*` |
+| Config source | Env + CLI (`--host`, etc.) | Env only | Env only |
+| `.env` loading | `app_gateway` calls `load_dotenv(get_env_file())`, i.e. `~/.jiuwenclaw/config/.env` | same | same |
+
+---
+
+## 3. Environment Variables (Gateway)
+
+Set these in `~/.jiuwenclaw/config/.env` or process environment (read by `app_gateway.py`):
+
+| Variable | Default | Notes |
+|------|------|------|
+| `A2A_SERVER_ENABLED` | disabled when unset | `1` / `true` / `yes` / `on` enable it |
+| `A2A_SERVER_HOST` | `127.0.0.1` | HTTP bind address; `0.0.0.0` is common for external access |
+| `A2A_SERVER_PORT` | `19100` | avoid conflicts with Web/ACP ports |
+| `A2A_SERVER_PATH` | `/a2a` | JSON-RPC entry path |
+| `A2A_SERVER_PROTOCOL_VERSION` | `1.0.0` | written into `AgentCard.AgentInterface.protocol_version` |
+| `A2A_SERVER_CARD_PATH` | `/.well-known/agent-card.json` | Agent Card path |
+| `A2A_SERVER_EXTENDED_CARD_PATH` | `/agent/authenticatedExtendedCard` | Extended Card path |
+| `A2A_SERVER_APP_NAME` | `JiuwenClaw Gateway A2A Server` | Agent Card `name` |
+| `A2A_SERVER_APP_DESCRIPTION` | `A2A ingress for JiuwenClaw Gateway` | Agent Card `description` |
+| `A2A_SERVER_APP_VERSION` | `0.1.0` | Agent Card `version` |
+
+AgentServer connectivity still follows existing gateway config (for example `AGENT_SERVER_URL`) and is independent from the A2A listening endpoint.
+
+---
+
+## 4. External Endpoints
+
+- **JSON-RPC**: `http://{A2A_SERVER_HOST}:{A2A_SERVER_PORT}{A2A_SERVER_PATH}`
+- **Agent Card**: `http://{host}:{port}/.well-known/agent-card.json` (path defined by `A2AChannelConfig.card_path`, default `/.well-known/agent-card.json`)
+
+`AgentCard` is built in `A2AChannel.start()`: `supported_interfaces[0].url` points to the JSON-RPC endpoint above; `capabilities.streaming` and skills are defined in code.
+
+---
+
+## 5. Data Flow (Overview)
+
+```mermaid
+flowchart LR
+ Caller["A2A Caller"]
+ Ch["A2AChannel"]
+ CM["ChannelManager"]
+ MH["MessageHandler"]
+ AS["AgentServer E2A"]
+
+ Caller --> Ch
+ Ch --> CM
+ CM --> MH
+ MH --> AS
+ AS --> MH
+ MH --> CM
+ CM --> Ch
+ Ch --> Caller
+```
+
+Inbound A2A `message.parts` are mapped into internal `Message.params.query` and optional `files`; no dedicated `params["a2a"]` extension object is written. Outbound internal `Message.payload` is mapped to A2A `Part` list (including multimodal parts and textified tool events).
+
+---
+
+## 6. Field Mapping Summary
+
+### 6.1 Request (A2A → `Message`)
+
+| A2A / context | Internal |
+|--------------|------|
+| `task_id` or generated value | `Message.id` (used to correlate replies) |
+| `context_id` | `Message.session_id` |
+| `parts[].text` | merged into `params.query` |
+| non-text parts (`url` / `data` / `raw`) | `params.files[]` (includes web-compatible redundant keys) |
+| metadata | `Message.metadata` |
+
+### 6.2 Response (`Message` → A2A)
+
+| Internal | A2A |
+|------|-----|
+| `payload.content`, tool-related events, etc. | `Part(text=...)`, etc. |
+| `payload.files[]` | `Part` url / data / raw fields |
+
+---
+
+## 7. Outbound A2A (Agent Side)
+
+- This repository currently does not include a dedicated A2A MCP Hub registration module. If/when that capability is restored, follow the actual wiring code and environment variable definitions.
+
+---
+
+## 8. Local Verification (Examples)
+
+Non-streaming:
+
+```bash
+curl -sS -X POST "http://127.0.0.1:${A2A_SERVER_PORT:-19100}${A2A_SERVER_PATH:-/a2a}" \
+ -H 'Content-Type: application/json' \
+ -d '{"jsonrpc":"2.0","id":"t1","method":"SendMessage","params":{"message":{"messageId":"m1","contextId":"c1","role":"ROLE_USER","parts":[{"text":"ping"}]}}}'
+```
+
+Streaming:
+
+```bash
+curl -sS -N -X POST "http://127.0.0.1:${A2A_SERVER_PORT:-19100}${A2A_SERVER_PATH:-/a2a}" \
+ -H 'Content-Type: application/json' \
+ -d '{"jsonrpc":"2.0","id":"t2","method":"SendStreamingMessage","params":{"message":{"messageId":"m2","contextId":"c2","role":"ROLE_USER","parts":[{"text":"ping"}]}}}'
+```
+
+Start both AgentServer and Gateway, and ensure `A2A_SERVER_ENABLED=true`.
+
+---
+
+## 9. Known Extension Points
+
+- Authentication, rate limit, timeout, and observability metrics are better enforced by gateway or upstream proxy, while keeping `A2AChannel` focused on protocol/message mapping.
+- If `jiuwenclaw/resources/.env.template` does not include A2A/ACP keys, append them manually in local `.env` (consistent with section 2).
diff --git a/docs/en/SUMMARY.md b/docs/en/SUMMARY.md
index b1be135386..268b2c01fb 100644
--- a/docs/en/SUMMARY.md
+++ b/docs/en/SUMMARY.md
@@ -2,6 +2,7 @@
- [Quick start](Quickstart.md)
- [E2A protocol (Gateway↔Agent)](E2A-protocol.md)
+- [A2A integration](A2A.md)
- [Configuration](Configuration.md)
- [User guide](README.md)
- [Channels](Channels.md)
diff --git a/docs/zh/A2A.md b/docs/zh/A2A.md
new file mode 100644
index 0000000000..0a17e6a339
--- /dev/null
+++ b/docs/zh/A2A.md
@@ -0,0 +1,145 @@
+# A2A 接入说明
+
+本文说明 Gateway 侧 **A2A Server**(`A2AChannel`)的实现位置、配置方式、与内部 `Message`/E2A 的对应关系及本地验证命令;出站 A2A(Agent 调外部)见 §7。
+
+> **实现**:`jiuwenclaw/channel/a2a_channel.py`(`A2AChannel` + `a2a-sdk`)。**入口进程**:`python -m jiuwenclaw.app_gateway`(`jiuwenclaw/app_gateway.py` 中注册并启动)。**冲突时**:以源码为准,并回头修正本文。
+
+---
+
+## 0. 文档位置与单一真源
+
+| 位置 | 角色 |
+|------|------|
+| **docs/zh/A2A.md**(本文) | 接入与开发联调:模块、配置、映射、验证 |
+| `jiuwenclaw/channel/a2a_channel.py` | A2A HTTP 服务、`AgentCard`、请求/响应与 `Message` 互转 |
+| `jiuwenclaw/app_gateway.py` | 环境变量读取、`A2AChannel` 构造与 `channel_manager.register_channel` |
+| `jiuwenclaw/gateway/message_handler.py` | 与 AgentServer 的 E2A 收发、内部 `Message` 编排 |
+| `jiuwenclaw/gateway/channel_manager.py` | 频道注册与 `robot_messages` → `Channel.send` 派发 |
+| [E2A-protocol.md](E2A-protocol.md) | Gateway↔AgentServer 内层协议 |
+
+---
+
+## 1. 职责边界
+
+- **入站(本文)**:外部 A2A 客户端 → `A2AChannel` → `ChannelManager` → `MessageHandler` → E2A → AgentServer;回复沿同一路径返回,经 `TaskStatusUpdateEvent` / `TaskArtifactUpdateEvent` 输出(流式)或聚合结果(非流式)。
+- **出站**:Agent 侧通过 A2A MCP Hub 等工具访问外部 A2A,接线在 AgentServer 适配层(见 §7),不在 `A2AChannel` 内实现。
+
+---
+
+## 2. 与 Web / ACP 通道的对照
+
+| 项目 | Web | ACP | A2A(当前) |
+|------|-----|-----|-------------|
+| 绑定 | `WEB_HOST` / `WEB_PORT` / `WEB_PATH` | `ACP_GATEWAY_*` | `A2A_SERVER_*` |
+| 配置来源 | 环境变量 + CLI(`--host` 等) | 仅环境变量 | 仅环境变量 |
+| `.env` | `app_gateway` 启动时 `load_dotenv(get_env_file())`,即 `~/.jiuwenclaw/config/.env` | 同上 | 同上 |
+
+---
+
+## 3. 环境变量(Gateway)
+
+在 `~/.jiuwenclaw/config/.env` 或进程环境中设置(`app_gateway.py` 读取):
+
+| 变量 | 默认 | 说明 |
+|------|------|------|
+| `A2A_SERVER_ENABLED` | 未设则关闭 | `1` / `true` / `yes` / `on` 为开启 |
+| `A2A_SERVER_HOST` | `127.0.0.1` | HTTP 监听地址;对外服务常用 `0.0.0.0` |
+| `A2A_SERVER_PORT` | `19100` | 与 Web、ACP 端口勿冲突 |
+| `A2A_SERVER_PATH` | `/a2a` | JSON-RPC 入口路径 |
+| `A2A_SERVER_PROTOCOL_VERSION` | `1.0.0` | 写入 `AgentCard` 的 `AgentInterface.protocol_version` |
+| `A2A_SERVER_CARD_PATH` | `/.well-known/agent-card.json` | Agent Card 对外路径 |
+| `A2A_SERVER_EXTENDED_CARD_PATH` | `/agent/authenticatedExtendedCard` | Extended Card 对外路径 |
+| `A2A_SERVER_APP_NAME` | `JiuwenClaw Gateway A2A Server` | Agent Card `name` |
+| `A2A_SERVER_APP_DESCRIPTION` | `A2A ingress for JiuwenClaw Gateway` | Agent Card `description` |
+| `A2A_SERVER_APP_VERSION` | `0.1.0` | Agent Card `version` |
+
+AgentServer 连接仍由网关既有逻辑配置(例如 `AGENT_SERVER_URL` 等),与 A2A 监听端口独立。
+
+---
+
+## 4. 对外端点
+
+- **JSON-RPC**:`http://{A2A_SERVER_HOST}:{A2A_SERVER_PORT}{A2A_SERVER_PATH}`
+- **Agent Card**:`http://{host}:{port}/.well-known/agent-card.json`(路径由 `A2AChannelConfig.card_path` 定义,默认 `/.well-known/agent-card.json`)
+
+`AgentCard` 在 `A2AChannel.start()` 内构造:`supported_interfaces[0].url` 指向上述 JSON-RPC;`capabilities.streaming` 与技能列表见源码。
+
+---
+
+## 5. 数据流(概要)
+
+```mermaid
+flowchart LR
+ Caller["A2A 调用方"]
+ Ch["A2AChannel"]
+ CM["ChannelManager"]
+ MH["MessageHandler"]
+ AS["AgentServer E2A"]
+
+ Caller --> Ch
+ Ch --> CM
+ CM --> MH
+ MH --> AS
+ AS --> MH
+ MH --> CM
+ CM --> Ch
+ Ch --> Caller
+```
+
+入站将 A2A `message.parts` 映射为 `Message.params` 的 `query` 与可选 `files`;不写入 `params["a2a"]` 等扩展结构。回包将内部 `Message.payload` 映射为 A2A `Part` 列表(含多模态与工具事件文本化)。
+
+---
+
+## 6. 字段映射摘要
+
+### 6.1 请求(A2A → `Message`)
+
+| A2A / 上下文 | 内部 |
+|--------------|------|
+| `task_id` 或生成值 | `Message.id`(与回包关联) |
+| `context_id` | `Message.session_id` |
+| `parts[].text` | 合并为 `params.query` |
+| `parts` 中非文本(url / data / raw) | `params.files[]`(含与 web 对齐的冗余键) |
+| 元数据 | `Message.metadata` |
+
+### 6.2 响应(`Message` → A2A)
+
+| 内部 | A2A |
+|------|-----|
+| `payload.content`、工具相关事件等 | `Part(text=...)` 等 |
+| `payload.files[]` | `Part` 的 url / data / raw 等 |
+
+---
+
+## 7. 出站 A2A(Agent 侧)
+
+- 当前仓库未包含独立的 A2A MCP Hub 注册模块;若后续恢复该能力,请以实际接线代码与环境变量定义为准。
+
+---
+
+## 8. 本地验证(示例)
+
+非流式:
+
+```bash
+curl -sS -X POST "http://127.0.0.1:${A2A_SERVER_PORT:-19100}${A2A_SERVER_PATH:-/a2a}" \
+ -H 'Content-Type: application/json' \
+ -d '{"jsonrpc":"2.0","id":"t1","method":"SendMessage","params":{"message":{"messageId":"m1","contextId":"c1","role":"ROLE_USER","parts":[{"text":"ping"}]}}}'
+```
+
+流式:
+
+```bash
+curl -sS -N -X POST "http://127.0.0.1:${A2A_SERVER_PORT:-19100}${A2A_SERVER_PATH:-/a2a}" \
+ -H 'Content-Type: application/json' \
+ -d '{"jsonrpc":"2.0","id":"t2","method":"SendStreamingMessage","params":{"message":{"messageId":"m2","contextId":"c2","role":"ROLE_USER","parts":[{"text":"ping"}]}}}'
+```
+
+需同时启动 AgentServer 与 Gateway,且 `A2A_SERVER_ENABLED=true`。
+
+---
+
+## 9. 已知扩展点
+
+- 鉴权、限流、超时与观测指标:由网关或前置代理统一补强时,保持 `A2AChannel` 只做协议与消息映射为宜。
+- `jiuwenclaw/resources/.env.template` 未预置 A2A/ACP 键时,可在本地 `.env` 手工追加(与 §2 一致)。
diff --git a/docs/zh/SUMMARY.md b/docs/zh/SUMMARY.md
index 3be9dd23bf..47fd1c998e 100644
--- a/docs/zh/SUMMARY.md
+++ b/docs/zh/SUMMARY.md
@@ -2,6 +2,7 @@
- [快速开始](Quickstart.md)
- [E2A 协议(Gateway↔Agent)](E2A-protocol.md)
+- [A2A 接入说明](A2A.md)
- [配置说明](配置信息.md)
- [使用指南](README.md)
- [频道](频道.md)
diff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.py
index bc07eb799d..a20c896010 100644
--- a/jiuwenclaw/app_gateway.py
+++ b/jiuwenclaw/app_gateway.py
@@ -678,6 +678,7 @@ async def _run(
web_port: int,
web_path: str,
) -> None:
+ from jiuwenclaw.channel.a2a_channel import A2AChannel, A2AChannelConfig
from jiuwenclaw.channel.dingding import DingTalkChannel, DingTalkConfig
from jiuwenclaw.channel.feishu import FeishuChannel, FeishuConfig
from jiuwenclaw.channel.whatsapp_channel import WhatsAppChannel, WhatsAppChannelConfig
@@ -968,6 +969,45 @@ async def _run(
binding.install(gateway_server)
gateway_server.on_message(acp_inbound_server.handle_message)
+ a2a_server_enabled = str(os.getenv("A2A_SERVER_ENABLED", "")).strip().lower() in {
+ "1",
+ "true",
+ "yes",
+ "on",
+ }
+ a2a_channel = A2AChannel(
+ A2AChannelConfig(
+ enabled=a2a_server_enabled,
+ host=str(os.getenv("A2A_SERVER_HOST", "127.0.0.1")).strip() or "127.0.0.1",
+ port=int(os.getenv("A2A_SERVER_PORT", "19100")),
+ rpc_path=str(os.getenv("A2A_SERVER_PATH", "/a2a")).strip() or "/a2a",
+ protocol_version=str(os.getenv("A2A_SERVER_PROTOCOL_VERSION", "1.0.0")).strip() or "1.0.0",
+ card_path=str(
+ os.getenv("A2A_SERVER_CARD_PATH", "/.well-known/agent-card.json")
+ ).strip()
+ or "/.well-known/agent-card.json",
+ extended_card_path=str(
+ os.getenv("A2A_SERVER_EXTENDED_CARD_PATH", "/agent/authenticatedExtendedCard")
+ ).strip()
+ or "/agent/authenticatedExtendedCard",
+ app_name=str(
+ os.getenv("A2A_SERVER_APP_NAME", "JiuwenClaw Gateway A2A Server")
+ ).strip()
+ or "JiuwenClaw Gateway A2A Server",
+ app_description=str(
+ os.getenv("A2A_SERVER_APP_DESCRIPTION", "A2A ingress for JiuwenClaw Gateway")
+ ).strip()
+ or "A2A ingress for JiuwenClaw Gateway",
+ app_version=str(
+ os.getenv("A2A_SERVER_APP_VERSION", "0.1.0")
+ ).strip()
+ or "0.1.0",
+ ),
+ _DummyBus(),
+ )
+ channel_manager.register_channel(a2a_channel)
+ a2a_task = asyncio.create_task(a2a_channel.start(), name="a2a-channel")
+
feishu_channel = None
feishu_task = None
feishu_enterprise_channels: dict[str, FeishuChannel] = {}
@@ -1484,6 +1524,14 @@ async def _run(
except asyncio.CancelledError:
pass
finally:
+ if a2a_task is not None:
+ a2a_task.cancel()
+ try:
+ await a2a_task
+ except asyncio.CancelledError:
+ pass
+ await a2a_channel.stop()
+ channel_manager.unregister_channel(a2a_channel.channel_id)
if gateway_server_task is not None:
gateway_server_task.cancel()
try:
diff --git a/jiuwenclaw/channel/a2a_channel.py b/jiuwenclaw/channel/a2a_channel.py
new file mode 100644
index 0000000000..41f3ceaf7c
--- /dev/null
+++ b/jiuwenclaw/channel/a2a_channel.py
@@ -0,0 +1,490 @@
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+import uuid
+from dataclasses import dataclass
+from typing import Any
+
+from jiuwenclaw.channel.base import BaseChannel
+from jiuwenclaw.schema.message import EventType, Message, ReqMethod
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class A2AChannelConfig:
+ enabled: bool = False
+ host: str = "127.0.0.1"
+ port: int = 19100
+ rpc_path: str = "/a2a"
+ card_path: str = "/.well-known/agent-card.json"
+ extended_card_path: str = "/agent/authenticatedExtendedCard"
+ protocol_version: str = "1.0.0"
+ channel_id: str = "a2a"
+ app_name: str = "JiuwenClaw Gateway A2A Server"
+ app_description: str = "A2A ingress for JiuwenClaw Gateway"
+ app_version: str = "0.1.0"
+
+
+@dataclass
+class _PendingA2ARequest:
+ queue: asyncio.Queue[Message]
+
+
+class _A2AAgentExecutor:
+ """A2A SDK AgentExecutor that forwards request via channel callback."""
+
+ def __init__(self, channel: "A2AChannel") -> None:
+ self._channel = channel
+
+ async def execute(self, context: Any, event_queue: Any) -> None:
+ from a2a.types import (
+ Artifact,
+ Part,
+ TaskArtifactUpdateEvent,
+ TaskState,
+ TaskStatus,
+ TaskStatusUpdateEvent,
+ )
+
+ request_id = str(context.task_id or f"a2a_{uuid.uuid4().hex[:12]}")
+ task_id = str(context.task_id or request_id)
+ context_id = str(context.context_id or f"a2a_ctx_{uuid.uuid4().hex[:8]}")
+ query, files = self._channel.map_a2a_parts_to_params(
+ getattr(context, "message", None)
+ )
+ if not query:
+ query = str(context.get_user_input() or "").strip()
+ if not query:
+ await event_queue.enqueue_event(
+ TaskStatusUpdateEvent(
+ task_id=task_id,
+ context_id=context_id,
+ status=TaskStatus(
+ state=TaskState.TASK_STATE_FAILED,
+ ),
+ )
+ )
+ await event_queue.close()
+ return
+
+ try:
+ await event_queue.enqueue_event(
+ TaskStatusUpdateEvent(
+ task_id=task_id,
+ context_id=context_id,
+ status=TaskStatus(state=TaskState.TASK_STATE_WORKING),
+ )
+ )
+ pending = await self._channel.dispatch_a2a_request(
+ request_id=request_id,
+ session_id=context_id,
+ query=query,
+ files=files,
+ metadata=dict(context.metadata or {}),
+ )
+ artifact_id = f"{task_id}_response"
+ artifact_started = False
+ while True:
+ response_msg = await pending.queue.get()
+ response_parts = self._channel.message_to_a2a_parts(
+ response_msg,
+ fallback_to_text=False,
+ )
+ is_terminal = self._channel.is_terminal_message(response_msg)
+ if (
+ is_terminal
+ and not response_parts
+ and response_msg.event_type == EventType.CHAT_ERROR
+ ):
+ response_parts = self._channel.message_to_a2a_parts(
+ response_msg,
+ fallback_to_text=True,
+ )
+ filtered_parts = []
+ for part in response_parts:
+ part_text = str(getattr(part, "text", "") or "").strip()
+ if self._channel.is_completion_sentinel_text(part_text):
+ continue
+ filtered_parts.append(part)
+ response_parts = filtered_parts
+ if response_parts:
+ await event_queue.enqueue_event(
+ TaskArtifactUpdateEvent(
+ task_id=task_id,
+ context_id=context_id,
+ artifact=Artifact(
+ artifact_id=artifact_id,
+ name="response",
+ parts=response_parts,
+ metadata=response_msg.metadata or None,
+ ),
+ append=artifact_started,
+ last_chunk=is_terminal,
+ )
+ )
+ artifact_started = True
+ if is_terminal:
+ if response_msg.event_type == EventType.CHAT_ERROR:
+ final_state = TaskState.TASK_STATE_FAILED
+ elif response_msg.event_type == EventType.CHAT_INTERRUPT_RESULT:
+ final_state = TaskState.TASK_STATE_CANCELED
+ else:
+ final_state = TaskState.TASK_STATE_COMPLETED
+ await event_queue.enqueue_event(
+ TaskStatusUpdateEvent(
+ task_id=task_id,
+ context_id=context_id,
+ status=TaskStatus(state=final_state),
+ )
+ )
+ break
+ except Exception as exc: # noqa: BLE001
+ logger.exception("[A2AChannel] execution failed: request_id=%s err=%s", request_id, exc)
+ await event_queue.enqueue_event(
+ TaskStatusUpdateEvent(
+ task_id=task_id,
+ context_id=context_id,
+ status=TaskStatus(state=TaskState.TASK_STATE_FAILED),
+ )
+ )
+ finally:
+ self._channel.clear_pending_request(request_id)
+ await event_queue.close()
+
+ async def cancel(self, context: Any, event_queue: Any) -> None:
+ from a2a.types import Message as A2AMessage, Part, Role, TaskState, TaskStatus, TaskStatusUpdateEvent
+
+ task_id = str(context.task_id or "a2a")
+ context_id = str(context.context_id or f"a2a_ctx_{uuid.uuid4().hex[:8]}")
+ await event_queue.enqueue_event(
+ TaskStatusUpdateEvent(
+ task_id=task_id,
+ context_id=context_id,
+ status=TaskStatus(state=TaskState.TASK_STATE_CANCELED),
+ )
+ )
+ await event_queue.close(immediate=True)
+
+
+class A2AChannel(BaseChannel):
+ name = "a2a"
+
+ def __init__(self, config: A2AChannelConfig, router: Any):
+ super().__init__(config, router)
+ self.config = config
+ self._on_message_cb = None
+ self._pending: dict[str, _PendingA2ARequest] = {}
+ self._uvicorn_server: Any | None = None
+ self._server_task: asyncio.Task | None = None
+
+ @property
+ def channel_id(self) -> str:
+ return str(self.config.channel_id or self.name).strip() or self.name
+
+ def on_message(self, callback) -> None:
+ self._on_message_cb = callback
+
+ async def start(self) -> None:
+ if self._running:
+ return
+ if not self.config.enabled:
+ logger.info("[A2AChannel] disabled by config")
+ return
+
+ from a2a.server.apps import A2AFastAPIApplication
+ from a2a.server.request_handlers import DefaultRequestHandler
+ from a2a.server.tasks import InMemoryPushNotificationConfigStore, InMemoryTaskStore
+ from a2a.types import AgentCapabilities, AgentCard, AgentInterface, AgentSkill
+ import uvicorn
+
+ agent_card = AgentCard(
+ name=self.config.app_name,
+ description=self.config.app_description,
+ version=self.config.app_version,
+ supported_interfaces=[
+ AgentInterface(
+ url=f"http://{self.config.host}:{self.config.port}{self.config.rpc_path}",
+ protocol_binding="jsonrpc",
+ protocol_version=self.config.protocol_version,
+ )
+ ],
+ capabilities=AgentCapabilities(streaming=True, push_notifications=False),
+ default_input_modes=["text/plain"],
+ default_output_modes=["text/plain"],
+ skills=[
+ AgentSkill(
+ id="chat",
+ name="chat",
+ description="Send user prompt to JiuwenClaw via Gateway",
+ tags=["chat", "gateway", "jiuwenclaw"],
+ examples=["Hello", "Summarize this"],
+ input_modes=["text/plain"],
+ output_modes=["text/plain"],
+ )
+ ],
+ )
+ request_handler = DefaultRequestHandler(
+ agent_executor=_A2AAgentExecutor(self),
+ task_store=InMemoryTaskStore(),
+ push_config_store=InMemoryPushNotificationConfigStore(),
+ )
+ app_builder = A2AFastAPIApplication(
+ agent_card=agent_card,
+ http_handler=request_handler,
+ )
+ fastapi_app = app_builder.build(
+ rpc_url=self.config.rpc_path,
+ agent_card_url=self.config.card_path,
+ extended_agent_card_url=self.config.extended_card_path,
+ )
+
+ uv_cfg = uvicorn.Config(
+ app=fastapi_app,
+ host=self.config.host,
+ port=self.config.port,
+ log_level="info",
+ access_log=False,
+ )
+ self._uvicorn_server = uvicorn.Server(uv_cfg)
+ self._server_task = asyncio.create_task(self._uvicorn_server.serve(), name="a2a-channel-server")
+ await asyncio.sleep(0.2)
+ if self._server_task.done():
+ exc = self._server_task.exception()
+ if exc:
+ raise exc
+ self._running = True
+ logger.info(
+ "[A2AChannel] started: http://%s:%s%s",
+ self.config.host,
+ self.config.port,
+ self.config.rpc_path,
+ )
+
+ async def stop(self) -> None:
+ self._running = False
+ if self._uvicorn_server is not None:
+ self._uvicorn_server.should_exit = True
+ if self._server_task is not None:
+ try:
+ await self._server_task
+ except Exception as exc: # noqa: BLE001
+ logger.warning("[A2AChannel] shutdown with error: %s", exc)
+ self._uvicorn_server = None
+ self._server_task = None
+ for pending in list(self._pending.values()):
+ # Wake waiting executors during shutdown.
+ await pending.queue.put(
+ Message(
+ id="a2a_shutdown",
+ type="event",
+ channel_id=self.channel_id,
+ session_id=None,
+ params={},
+ timestamp=time.time(),
+ ok=False,
+ payload={"error": "a2a channel stopped", "is_complete": True},
+ event_type=EventType.CHAT_ERROR,
+ )
+ )
+ self._pending.clear()
+ logger.info("[A2AChannel] stopped")
+
+ async def send(self, msg: Message) -> None:
+ pending = self._pending.get(str(msg.id))
+ if pending is None:
+ return
+ await pending.queue.put(msg)
+
+ async def dispatch_a2a_request(
+ self,
+ *,
+ request_id: str,
+ session_id: str | None,
+ query: str,
+ files: list[dict[str, Any]] | None = None,
+ metadata: dict[str, Any] | None = None,
+ ) -> _PendingA2ARequest:
+ if self._on_message_cb is None:
+ raise RuntimeError("A2AChannel on_message callback is not set")
+ pending = _PendingA2ARequest(queue=asyncio.Queue())
+ self._pending[request_id] = pending
+ try:
+ msg = Message(
+ id=request_id,
+ type="req",
+ channel_id=self.channel_id,
+ session_id=session_id or f"a2a_{uuid.uuid4().hex[:8]}",
+ params=self._build_request_params(query=query, files=files),
+ timestamp=time.time(),
+ ok=True,
+ req_method=ReqMethod.CHAT_SEND,
+ is_stream=True,
+ metadata=metadata or None,
+ )
+ result = self._on_message_cb(msg)
+ if asyncio.iscoroutine(result):
+ await result
+ return pending
+ finally:
+ # Keep pending entry for send() until terminal message is consumed by executor.
+ pass
+
+ def clear_pending_request(self, request_id: str) -> None:
+ self._pending.pop(str(request_id), None)
+
+ @staticmethod
+ def message_to_text(msg: Message) -> str:
+ payload = msg.payload if isinstance(msg.payload, dict) else {}
+ if msg.type == "event" and msg.event_type == EventType.CHAT_ERROR:
+ return str(payload.get("error") or payload.get("content") or "agent request failed")
+ if "content" in payload:
+ return str(payload.get("content") or "")
+ if payload:
+ return str(payload)
+ return ""
+
+ @staticmethod
+ def message_to_a2a_parts(msg: Message, *, fallback_to_text: bool = True) -> list[Any]:
+ """Map internal message payload to A2A response parts."""
+ from a2a.types import Part
+
+ payload = msg.payload if isinstance(msg.payload, dict) else {}
+ parts: list[Any] = []
+
+ # Keep error response readable for A2A callers.
+ if msg.type == "event" and msg.event_type == EventType.CHAT_ERROR:
+ error_text = str(payload.get("error") or payload.get("content") or "agent request failed")
+ return [Part(text=error_text)]
+
+ content = payload.get("content")
+ if isinstance(content, str) and content.strip():
+ normalized_content = content.strip()
+ if not A2AChannel.is_completion_sentinel_text(normalized_content):
+ parts.append(Part(text=normalized_content))
+ elif content is not None and not isinstance(content, (dict, list)):
+ parts.append(Part(text=str(content)))
+ result = payload.get("result")
+ if isinstance(result, str) and result.strip():
+ normalized_result = result.strip()
+ if not A2AChannel.is_completion_sentinel_text(normalized_result):
+ parts.append(Part(text=normalized_result))
+ # Surface tool events in stream mode so callers can observe progress.
+ if msg.event_type == EventType.CHAT_TOOL_CALL and isinstance(payload.get("tool_call"), dict):
+ tool_call = payload.get("tool_call") or {}
+ tool_name = str(tool_call.get("name") or "tool").strip()
+ parts.append(Part(text=f"[tool_call] {tool_name}"))
+ if msg.event_type == EventType.CHAT_TOOL_RESULT:
+ tool_name = str(payload.get("tool_name") or "").strip()
+ tool_result = payload.get("result")
+ if isinstance(tool_result, str) and tool_result.strip():
+ label = f"[tool_result:{tool_name}] " if tool_name else "[tool_result] "
+ parts.append(Part(text=f"{label}{tool_result.strip()}"))
+
+ raw_files = payload.get("files")
+ files = raw_files if isinstance(raw_files, list) else []
+ for idx, file_item in enumerate(files):
+ if not isinstance(file_item, dict):
+ continue
+ file_name = str(file_item.get("filename") or file_item.get("name") or f"file_{idx}").strip()
+ media_type = str(file_item.get("media_type") or file_item.get("type") or "").strip()
+ url = str(file_item.get("url") or file_item.get("uri") or "").strip()
+ data = str(file_item.get("data") or "").strip()
+ raw = str(file_item.get("raw") or "").strip()
+
+ common_fields: dict[str, str] = {}
+ if file_name:
+ common_fields["filename"] = file_name
+ if media_type:
+ common_fields["media_type"] = media_type
+ if url:
+ parts.append(Part(url=url, **common_fields))
+ if data:
+ parts.append(Part(data=data, **common_fields))
+ if raw:
+ parts.append(Part(raw=raw, **common_fields))
+
+ if parts:
+ return parts
+ if fallback_to_text:
+ return [Part(text=A2AChannel.message_to_text(msg))]
+ return []
+
+ @staticmethod
+ def is_completion_sentinel_text(text: str) -> bool:
+ compact = "".join(text.split()).lower()
+ return compact in {"{'is_complete':true}", '{"is_complete":true}'}
+
+ @staticmethod
+ def is_terminal_message(msg: Message) -> bool:
+ if msg.type == "res":
+ return True
+ if msg.type != "event":
+ return False
+ if msg.event_type in {
+ EventType.CHAT_ERROR,
+ EventType.CHAT_INTERRUPT_RESULT,
+ }:
+ return True
+ payload = msg.payload if isinstance(msg.payload, dict) else {}
+ if payload.get("is_complete") is True:
+ return True
+ return False
+
+ @staticmethod
+ def _build_request_params(
+ *,
+ query: str,
+ files: list[dict[str, Any]] | None = None,
+ ) -> dict[str, Any]:
+ params: dict[str, Any] = {"query": query}
+ if files:
+ params["files"] = files
+ return params
+
+ @staticmethod
+ def map_a2a_parts_to_params(a2a_message: Any) -> tuple[str, list[dict[str, Any]]]:
+ """Map A2A message parts to JiuwenClaw-friendly query/files params."""
+ if a2a_message is None:
+ return "", []
+
+ text_segments: list[str] = []
+ files: list[dict[str, Any]] = []
+ parts = getattr(a2a_message, "parts", None) or []
+ for idx, part in enumerate(parts):
+ text = str(getattr(part, "text", "") or "").strip()
+ if text:
+ text_segments.append(text)
+
+ file_name = str(getattr(part, "filename", "") or "").strip()
+ media_type = str(getattr(part, "media_type", "") or "").strip()
+ url = str(getattr(part, "url", "") or "").strip()
+ data = str(getattr(part, "data", "") or "").strip()
+ raw = str(getattr(part, "raw", "") or "").strip()
+
+ # Preserve non-text parts as files metadata for downstream tools.
+ if url or data or raw:
+ normalized_name = file_name or f"a2a_part_{idx}"
+ entry: dict[str, Any] = {
+ # web_channel compatibility keys
+ "name": normalized_name,
+ "filename": normalized_name,
+ }
+ if media_type:
+ entry["media_type"] = media_type
+ # common consumers check `type`
+ entry["type"] = media_type
+ if url:
+ entry["url"] = url
+ entry["uri"] = url
+ if data:
+ entry["data"] = data
+ entry["encoding"] = "base64"
+ if raw:
+ entry["raw"] = raw
+ files.append(entry)
+
+ query = "\n".join(seg for seg in text_segments if seg).strip()
+ return query, files
diff --git a/pyproject.toml b/pyproject.toml
index 25030a07a5..e36f0d79e9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -12,6 +12,7 @@ classifiers = [
"License :: OSI Approved :: Apache Software License",
]
dependencies = [
+ "a2a-sdk[http-server]==1.0.0a0",
"chromadb>=1.5.0",
"ruamel.yaml>=0.18.0",
"lark-oapi>=1.5.3",
diff --git a/tests/unit_tests/channel/test_a2a_channel.py b/tests/unit_tests/channel/test_a2a_channel.py
new file mode 100644
index 0000000000..fce0441cb3
--- /dev/null
+++ b/tests/unit_tests/channel/test_a2a_channel.py
@@ -0,0 +1,222 @@
+import asyncio
+import time
+
+import pytest
+
+from jiuwenclaw.channel.a2a_channel import A2AChannel, A2AChannelConfig
+from jiuwenclaw.schema.message import EventType, Message
+
+
+class DummyBus:
+ @staticmethod
+ async def publish_user_messages(msg):
+ return None
+
+
+class DummyPart:
+ def __init__(
+ self,
+ *,
+ text: str = "",
+ filename: str = "",
+ media_type: str = "",
+ url: str = "",
+ data: str = "",
+ raw: str = "",
+ ):
+ self.text = text
+ self.filename = filename
+ self.media_type = media_type
+ self.url = url
+ self.data = data
+ self.raw = raw
+
+
+class DummyA2AMessage:
+ def __init__(self, parts):
+ self.parts = parts
+
+
+def build_channel() -> A2AChannel:
+ return A2AChannel(A2AChannelConfig(enabled=False), DummyBus())
+
+
+def test_map_a2a_parts_to_params_text_and_files():
+ msg = DummyA2AMessage(
+ [
+ DummyPart(text="hello"),
+ DummyPart(
+ filename="sample-url.txt",
+ media_type="text/plain",
+ url="https://example.com/test.txt",
+ ),
+ DummyPart(
+ filename="inline.txt",
+ media_type="text/plain",
+ data="aGVsbG8gd29ybGQ=",
+ ),
+ DummyPart(raw="opaque-bytes"),
+ ]
+ )
+
+ query, files = A2AChannel.map_a2a_parts_to_params(msg)
+
+ assert query == "hello"
+ assert len(files) == 3
+ assert files[0]["filename"] == "sample-url.txt"
+ assert files[0]["url"] == "https://example.com/test.txt"
+ assert files[0]["uri"] == "https://example.com/test.txt"
+ assert files[1]["filename"] == "inline.txt"
+ assert files[1]["data"] == "aGVsbG8gd29ybGQ="
+ assert files[1]["encoding"] == "base64"
+ # raw-only part should still produce a normalized synthetic filename.
+ assert files[2]["filename"] == "a2a_part_3"
+ assert files[2]["raw"] == "opaque-bytes"
+
+
+def test_message_to_a2a_parts_filters_completion_sentinel_text():
+ msg = Message(
+ id="r1",
+ type="event",
+ channel_id="a2a",
+ session_id="s1",
+ params={},
+ timestamp=time.time(),
+ ok=True,
+ payload={"content": "{'is_complete': True}"},
+ event_type=EventType.CHAT_FINAL,
+ )
+
+ parts = A2AChannel.message_to_a2a_parts(msg, fallback_to_text=False)
+ assert parts == []
+
+
+def test_message_to_a2a_parts_maps_tool_events():
+ tool_call_msg = Message(
+ id="r2",
+ type="event",
+ channel_id="a2a",
+ session_id="s1",
+ params={},
+ timestamp=time.time(),
+ ok=True,
+ payload={"tool_call": {"name": "view_file"}},
+ event_type=EventType.CHAT_TOOL_CALL,
+ )
+ tool_result_msg = Message(
+ id="r3",
+ type="event",
+ channel_id="a2a",
+ session_id="s1",
+ params={},
+ timestamp=time.time(),
+ ok=True,
+ payload={"tool_name": "view_file", "result": "ok"},
+ event_type=EventType.CHAT_TOOL_RESULT,
+ )
+
+ call_parts = A2AChannel.message_to_a2a_parts(tool_call_msg, fallback_to_text=False)
+ result_parts = A2AChannel.message_to_a2a_parts(tool_result_msg, fallback_to_text=False)
+
+ assert len(call_parts) == 1
+ assert getattr(call_parts[0], "text", "") == "[tool_call] view_file"
+ assert len(result_parts) == 2
+ assert getattr(result_parts[0], "text", "") == "ok"
+ assert getattr(result_parts[1], "text", "") == "[tool_result:view_file] ok"
+
+
+def test_is_terminal_message_rules():
+ terminal_error = Message(
+ id="e1",
+ type="event",
+ channel_id="a2a",
+ session_id="s1",
+ params={},
+ timestamp=time.time(),
+ ok=False,
+ payload={"error": "boom"},
+ event_type=EventType.CHAT_ERROR,
+ )
+ terminal_complete = Message(
+ id="e2",
+ type="event",
+ channel_id="a2a",
+ session_id="s1",
+ params={},
+ timestamp=time.time(),
+ ok=True,
+ payload={"is_complete": True},
+ event_type=EventType.CHAT_FINAL,
+ )
+ non_terminal = Message(
+ id="e3",
+ type="event",
+ channel_id="a2a",
+ session_id="s1",
+ params={},
+ timestamp=time.time(),
+ ok=True,
+ payload={"content": "delta"},
+ event_type=EventType.CHAT_DELTA,
+ )
+
+ assert A2AChannel.is_terminal_message(terminal_error) is True
+ assert A2AChannel.is_terminal_message(terminal_complete) is True
+ assert A2AChannel.is_terminal_message(non_terminal) is False
+
+
+def test_dispatch_a2a_request_requires_on_message_callback():
+ channel = build_channel()
+
+ async def _run():
+ await channel.dispatch_a2a_request(
+ request_id="req-1",
+ session_id="sess-1",
+ query="hello",
+ )
+
+ with pytest.raises(RuntimeError, match="on_message callback"):
+ asyncio.run(_run())
+
+
+def test_dispatch_a2a_request_and_send_queue_roundtrip():
+ channel = build_channel()
+ seen = []
+
+ async def on_message(msg: Message):
+ seen.append(msg)
+
+ async def _run():
+ channel.on_message(on_message)
+ pending = await channel.dispatch_a2a_request(
+ request_id="req-2",
+ session_id="sess-2",
+ query="hello",
+ files=[{"filename": "x.txt", "data": "aGVsbG8="}],
+ metadata={"trace_id": "t-1"},
+ )
+
+ assert len(seen) == 1
+ outbound = seen[0]
+ assert outbound.id == "req-2"
+ assert outbound.session_id == "sess-2"
+ assert outbound.params["query"] == "hello"
+ assert outbound.params["files"][0]["filename"] == "x.txt"
+ assert outbound.metadata == {"trace_id": "t-1"}
+
+ inbound = Message(
+ id="req-2",
+ type="event",
+ channel_id="a2a",
+ session_id="sess-2",
+ params={},
+ timestamp=time.time(),
+ ok=True,
+ payload={"content": "ok", "is_complete": True},
+ event_type=EventType.CHAT_FINAL,
+ )
+ await channel.send(inbound)
+ queued = await pending.queue.get()
+ assert queued.payload["content"] == "ok"
+
+ asyncio.run(_run())
diff --git a/uv.lock b/uv.lock
index 898e464cc1..d06211324e 100644
--- a/uv.lock
+++ b/uv.lock
@@ -28,6 +28,12 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/97/f7/673b61a8272c9d36baf9df7169a784e6eda214a830569e9f0c3e442d75bb/a2a_sdk-1.0.0a0-py3-none-any.whl", hash = "sha256:a062e00a00d0fffcdd4325c36392dff27bf0e9ef99a6a6d35344c08676ca45c4", size = 225939, upload-time = "2026-03-17T14:11:02.672Z" },
]
+[package.optional-dependencies]
+http-server = [
+ { name = "fastapi" },
+ { name = "sse-starlette" },
+ { name = "starlette" },
+]
[[package]]
name = "aiofiles"
version = "25.1.0"
@@ -930,6 +936,22 @@ lua = [
{ name = "lupa" },
]
+[[package]]
+name = "fastapi"
+version = "0.135.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "annotated-doc" },
+ { name = "pydantic" },
+ { name = "starlette" },
+ { name = "typing-extensions" },
+ { name = "typing-inspection" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/f7/e6/7adb4c5fa231e82c35b8f5741a9f2d055f520c29af5546fd70d3e8e1cd2e/fastapi-0.135.3.tar.gz", hash = "sha256:bd6d7caf1a2bdd8d676843cdcd2287729572a1ef524fc4d65c17ae002a1be654", size = 396524, upload-time = "2026-04-01T16:23:58.188Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/84/a4/5caa2de7f917a04ada20018eccf60d6cc6145b0199d55ca3711b0fc08312/fastapi-0.135.3-py3-none-any.whl", hash = "sha256:9b0f590c813acd13d0ab43dd8494138eb58e484bfac405db1f3187cfc5810d98", size = 117734, upload-time = "2026-04-01T16:23:59.328Z" },
+]
+
[[package]]
name = "fastmcp"
version = "2.14.5"
@@ -1490,6 +1512,7 @@ name = "jiuwenclaw"
version = "0.1.10"
source = { editable = "." }
dependencies = [
+ { name = "a2a-sdk", extra = ["http-server"] },
{ name = "aiosqlite" },
{ name = "chromadb" },
{ name = "croniter" },
@@ -1555,6 +1578,7 @@ test = [
[package.metadata]
requires-dist = [
+ { name = "a2a-sdk", extras = ["http-server"], specifier = "==1.0.0a0" },
{ name = "aiosqlite", specifier = ">=0.22.1" },
{ name = "chromadb", specifier = ">=1.5.0" },
{ name = "coverage", marker = "extra == 'test'", specifier = ">=7.7.1" },