diff --git a/docs/02-a2a-protocol.md b/docs/02-a2a-protocol.md new file mode 100644 index 0000000..8a5da2a --- /dev/null +++ b/docs/02-a2a-protocol.md @@ -0,0 +1,465 @@ +# A2A 协议(Agent-to-Agent Protocol) + +> 版本:1.0.0 +> 状态:草案 +> 类型:实现规范 +> 基于:[灵隙原始协议(Synapse Raw Protocol) v1.0.0](./01-synapse-raw-protocol.md) + +--- + +## 1. 概述 + +A2A 协议定义了两个 Agent 之间进行点对点(P2P)任务协作的完整规范,包括消息类型、交互流程、状态机、接口定义与错误处理。 + +### 1.1 适用场景 +- 单个任务请求与响应 +- 任务状态实时同步 +- 任务取消 +- 信息补全交互 +- 人类介入决策 + +### 1.2 非适用场景 +- 多 Agent 群组协作(参见 A2N 组群协议) +- 非 Agent 调用方接入(参见 P2A 调用协议) + +--- + +## 2. 消息类型 + +### 2.1 消息类型清单 + +所有消息类型前缀:`p2p:` + +| 消息类型 | 方向 | 说明 | +|---------|------|------| +| `p2p:task_request` | 请求方 → 执行方 | 提交任务请求 | +| `p2p:task_confirm` | 执行方 → 请求方 | 确认接受任务 | +| `p2p:task_reject` | 执行方 → 请求方 | 拒绝任务 | +| `p2p:task_need_info` | 执行方 → 请求方 | 请求补充信息 | +| `p2p:task_info_provided` | 请求方 → 执行方 | 提供补充信息 | +| `p2p:task_status_update` | 执行方 → 请求方 | 任务进度更新 | +| `p2p:task_complete` | 执行方 → 请求方 | 任务完成 | +| `p2p:task_failed` | 执行方 → 请求方 | 任务失败 | +| `p2p:task_cancel` | 请求方 → 执行方 | 取消任务 | +| `p2p:task_ack` | 双向 | 任务级确认 | +| `p2p:ack` | 双向 | 通用确认 | +| `p2p:nack` | 双向 | 通用否定确认(错误) | +| `p2p:heartbeat` | 双向 | 心跳保活 | +| `p2p:capability_query` | 双向 | 查询对方能力 | +| `p2p:capability_response` | 双向 | 返回能力清单 | +| `p2p:task_need_human` | 执行方 → 请求方 | 请求人类介入 | +| `p2p:human_decision` | 请求方 → 执行方 | 人类决策结果 | + +### 2.2 消息类型完整定义 + +参见代码:[types/types.go](../types/types.go) + +--- + +## 3. 任务状态机 + +### 3.1 状态定义 + +| 状态 | 说明 | +|------|------| +| `idle` | 空闲(初始状态) | +| `pending` | 待确认(已发送请求,等待确认) | +| `confirmed` | 已确认(对方接受任务) | +| `executing` | 执行中 | +| `info_needed` | 需要信息 | +| `info_provided` | 信息已提供 | +| `need_human` | 需要人类介入 | +| `human_deciding` | 人类决策中 | +| `human_approved` | 人类已批准 | +| `human_rejected` | 人类已拒绝 | +| `completed` | 已完成(终态) | +| `failed` | 已失败(终态) | +| `cancelled` | 已取消(终态) | +| `rejected` | 已拒绝(终态) | + +### 3.2 状态流转图 + +``` +请求方视角: + +idle → pending → confirmed → executing → completed + ↓ ↓ → failed + rejected info_needed → cancelled + ↑↓ + info_provided + ↓ + need_human + ↑↓ + human_decision +``` + +--- + +## 4. 核心交互流程 + +### 4.1 正常任务提交流程 + +``` +请求方 Agent 执行方 Agent + | | + |-------- task_request ------------->| 1. 提交任务 + | | + |<------- task_confirm / task_reject -| 2. 确认/拒绝 + | | + |<------- task_status_update --------| 3. 进度更新(多次) + | | + |<------- task_complete -------------| 4. 完成通知 + | | + |-------- task_ack ----------------->| 5. 确认收到 + | | +``` + +### 4.2 信息补全流程 + +``` +请求方 Agent 执行方 Agent + | | + |-------- task_request ------------->| + | | + |<------- task_need_info ------------| 发现信息缺失 + | | + |-------- task_info_provided ------->| 补充信息 + | | + |<------- task_status_update --------| 继续执行 + | | +``` + +### 4.3 人类介入流程 + +``` +请求方 Agent 执行方 Agent + | | + |-------- task_request ------------->| + | | + |<------- task_need_human -----------| 需要人类决策 + | | + | [人类做出决策] | + | | + |-------- human_decision ----------->| 决策结果 + | | + |<------- task_status_update --------| 继续执行 + | | +``` + +### 4.4 任务取消流程 + +``` +请求方 Agent 执行方 Agent + | | + |-------- task_request ------------->| + | | + |-------- task_cancel -------------->| 取消任务 + | | + |<------- task_ack ------------------| 确认取消 + | | +``` + +--- + +## 5. 接口规范 + +### 5.1 P2P 协议处理器接口 + +**接口定义:** + +```go +type P2PProtocol interface { + // 处理收到的消息 + HandleMessage(ctx context.Context, msg *UnifiedSynapseMessage) (*UnifiedSynapseMessage, error) + + // 设置任务处理器 + SetTaskHandler(h TaskHandler) + + // 设置回调发送器 + SetCallbackSender(s CallbackSender) + + // 获取 Agent 端点 + AgentEndpoint() AgentEndpoint + + // 查询任务状态 + GetTaskStatus(taskID string) (P2PTaskStatus, bool) + + // 列出所有任务 + ListTasks() map[string]P2PTaskStatus +} +``` + +**参考实现:** [p2p/protocol.go](../p2p/protocol.go) + +### 5.2 任务处理器接口 + +```go +type TaskHandler interface { + // 执行任务并返回结果 + ExecuteTask(ctx context.Context, taskType string, payload map[string]interface{}) (any, error) + + // 验证任务是否可执行,返回缺失字段列表和是否可处理 + ValidateTask(taskType string, payload map[string]interface{}) ([]MissingField, bool) + + // 获取能力列表 + GetCapabilities() []string +} +``` + +**说明:** +- `ExecuteTask`:实际执行业务逻辑的入口 +- `ValidateTask`:在任务确认前调用,用于判断是否接受任务或需要补充信息 +- `GetCapabilities`:返回 Agent 支持的任务类型列表 + +### 5.3 回调发送器接口 + +```go +type CallbackSender interface { + // 向远程 Agent 发送消息 + SendCallback(ctx context.Context, endpoint string, msg *UnifiedSynapseMessage) error +} +``` + +**说明:** +- 传输层实现此接口 +- 支持多种传输方式(HTTP、gRPC、WebSocket 等) + +### 5.4 配置项 + +```go +type P2PConfig struct { + MaxRetries int // 最大重试次数(默认 5) + RetryBaseDelay time.Duration // 重试基础延迟(默认 2s,指数退避) + TaskTimeout time.Duration // 任务执行超时(默认 5 分钟) + HeartbeatInterval time.Duration // 心跳间隔(默认 30 秒) +} +``` + +--- + +## 6. 载荷格式 + +### 6.1 TaskRequestPayload(任务请求) + +```json +{ + "task": { + "id": "task-xxx", + "type": "text_generation", + "priority": "normal", + "deadline": "2026-01-01T00:00:00Z", + "payload": { + "prompt": "写一首诗", + "style": "古典" + } + }, + "context": { + "session_id": "sess-xxx", + "parent_task_id": "parent-xxx", + "correlation_id": "corr-xxx", + "metadata": {} + } +} +``` + +### 6.2 TaskConfirmPayload(任务确认) + +```json +{ + "task_id": "task-xxx", + "confirmed": true, + "estimated_duration": 120, + "expected_completion": "2026-01-01T00:02:00Z", + "capabilities_used": ["text_generation"], + "constraints": { + "max_retries": 3, + "fallback_enabled": true + } +} +``` + +### 6.3 TaskRejectPayload(任务拒绝) + +```json +{ + "task_id": "task-xxx", + "reason": { + "code": "capability_lacking", + "message": "不支持该任务类型", + "details": null + }, + "alternatives": { + "suggested_agent_id": "other-agent", + "retry_after": 300, + "partial_support": false + } +} +``` + +### 6.4 TaskStatusUpdatePayload(状态更新) + +```json +{ + "task_id": "task-xxx", + "status": "executing", + "progress": 50, + "message": "正在生成内容", + "intermediate_result": null +} +``` + +### 6.5 TaskCompletePayload(任务完成) + +```json +{ + "task_id": "task-xxx", + "result": { + "output_type": "text", + "output": "生成的文本内容...", + "metadata": { + "tokens": 1024, + "model": "gpt-4" + } + }, + "summary": "任务已完成" +} +``` + +### 6.6 TaskFailedPayload(任务失败) + +```json +{ + "task_id": "task-xxx", + "error": { + "code": "execution_error", + "message": "模型调用超时", + "recoverable": true, + "details": null + }, + "partial_result": null +} +``` + +### 6.7 TaskNeedInfoPayload(需要信息) + +```json +{ + "task_id": "task-xxx", + "missing_fields": [ + { + "field": "style", + "reason": "未指定生成风格", + "suggested_value": "古典", + "alternatives": ["现代", "浪漫"] + } + ], + "question": "请选择生成风格", + "required_by": "2026-01-01T00:01:00Z" +} +``` + +### 6.8 TaskNeedHumanPayload(需要人类) + +```json +{ + "task_id": "task-xxx", + "reason": { + "code": "ethical_decision", + "message": "涉及伦理决策需要人工审核" + }, + "context": { + "task_summary": "生成一张人物肖像", + "current_progress": 30, + "blocked_reason": "需要确认肖像使用授权" + }, + "options": [ + { + "field": "authorized", + "value": true, + "pros_cons": "继续生成,假设已授权", + "confidence": 70 + } + ], + "escalation_level": 1, + "deadline": "2026-01-01T00:05:00Z" +} +``` + +### 6.9 HumanDecisionPayload(人类决策) + +```json +{ + "task_id": "task-xxx", + "decision_id": "dec-xxx", + "reply_to": "msg-xxx", + "decided_by": { + "user_id": "user-123", + "user_name": "张三", + "role": "reviewer" + }, + "decision": { + "action": "approve", + "approved_fields": { + "authorized": true + }, + "rejection_reason": "" + }, + "notes": "已确认授权", + "timestamp": "2026-01-01T00:03:00Z" +} +``` + +**完整载荷定义:** [types/types.go](../types/types.go) + +--- + +## 7. 错误码 + +| 错误码 | 说明 | HTTP 状态码(如适用) | +|--------|------|---------------------| +| `message_format_invalid` | 消息格式无效 | 400 | +| `capability_lacking` | 能力不足 | 403 | +| `agent_not_ready` | Agent 未就绪 | 503 | +| `task_not_found` | 任务不存在 | 404 | +| `task_already_completed` | 任务已完成 | 409 | +| `execution_timeout` | 执行超时 | 504 | +| `execution_failed` | 执行失败 | 500 | +| `permission_denied` | 权限不足 | 403 | +| `invalid_params` | 参数无效 | 400 | +| `rate_limited` | 限流 | 429 | + +**完整错误定义:** [types/errors.go](../types/errors.go) + +--- + +## 8. 传输要求 + +### 8.1 HTTP 传输 +- Content-Type: `application/json` +- 请求方法:`POST` +- 端点路径:由 Agent 自行定义,建议 `/synapse/callback` +- 超时:建议 30 秒 + +### 8.2 签名验证(可选) +- 使用 HMAC-SHA256 签名 +- 签名放在 Header:`X-Synapse-Signature` +- 或放在消息体:`signature` 字段 + +--- + +## 9. 参考实现 + +本协议的参考实现位于 `p2p/` 目录: + +| 文件 | 说明 | +|------|------| +| [p2p/protocol.go](../p2p/protocol.go) | P2P 协议核心实现 | +| [types/types.go](../types/types.go) | 数据类型定义 | +| [types/errors.go](../types/errors.go) | 错误定义 | +| [transport/transport.go](../transport/transport.go) | HTTP 传输实现 | + +--- + +## 附录 A:能力声明格式 + +参见 [灵隙原始协议(Synapse Raw Protocol) - Capability](./01-synapse-raw-protocol.md#44-capability能力) diff --git a/docs/03-a2n-protocol.md b/docs/03-a2n-protocol.md new file mode 100644 index 0000000..fa70c90 --- /dev/null +++ b/docs/03-a2n-protocol.md @@ -0,0 +1,545 @@ +# A2N 协议(Agent-to-N Protocol) + +> 版本:1.0.0 +> 状态:草案 +> 类型:实现规范 +> 基于:[灵隙原始协议(Synapse Raw Protocol) v1.0.0](./01-synapse-raw-protocol.md) + +--- + +## 1. 概述 + +A2N(Agent-to-N)组群协议定义了多个 Agent 组成群组进行协同工作的完整规范,包括群组管理、任务拆分与合并、群体决策、角色与权限等。 + +### 1.1 适用场景 +- 复杂任务的拆分与并行执行(MapReduce 模式) +- 多 Agent 协同完成单一目标 +- 群体投票与共识决策 +- 临时或永久的 Agent 工作组 +- 分级升级(escalation)机制 + +### 1.2 依赖 +- 依赖 A2A 协议的点对点通信能力 +- 群组内成员间的单播通信使用 A2A 协议 + +--- + +## 2. 核心概念 + +### 2.1 Group(群组) +由多个 Agent 组成的协作单元,具有明确的拓扑结构、角色分工与协作规则。 + +### 2.2 Topology(拓扑结构) + +| 拓扑类型 | 说明 | 适用场景 | +|---------|------|---------| +| `star` | 星型,中心 coordinator 协调 | 简单任务分发 | +| `mesh` | 网状,成员间可直接通信 | 对等协作 | +| `chain` | 链式,流水线模式 | 顺序处理 | +| `hierarchical` | 层级型,多层管理 | 大型复杂任务 | +| `fullmesh` | 全连接网状 | 高可靠协作 | + +### 2.3 Role(角色) + +| 角色 | 说明 | 权限 | +|------|------|------| +| `coordinator` | 协调者 | 创建/解散群组、任务拆分、发起投票 | +| `worker` | 工作者 | 执行子任务、提交结果 | +| `reviewer` | 审核者 | 审核结果、发起投票 | +| `observer` | 观察者 | 只读,查看进度 | + +### 2.4 GroupStatus(群组状态) + +| 状态 | 说明 | +|------|------| +| `creating` | 创建中 | +| `active` | 活跃 | +| `frozen` | 冻结(不可执行新任务) | +| `disbanded` | 已解散(终态) | + +--- + +## 3. 消息类型 + +### 3.1 消息类型清单 + +所有消息类型前缀:`group:` 或 `inter_group:` + +#### 群组管理 + +| 消息类型 | 说明 | +|---------|------| +| `group:create` | 创建群组 | +| `group:disband` | 解散群组 | +| `group:join` | 加入群组 | +| `group:leave` | 离开群组 | +| `group:invite` | 邀请加入 | +| `group:accept_invite` | 接受邀请 | +| `group:reject_invite` | 拒绝邀请 | +| `group:member_update` | 成员更新通知 | +| `group:role_change` | 角色变更 | + +#### 群组通信 + +| 消息类型 | 说明 | +|---------|------| +| `group:broadcast` | 广播(所有成员) | +| `group:multicast` | 组播(指定成员) | +| `group:direct` | 群内单播 | +| `group:relay` | 消息中继 | + +#### 任务协作 + +| 消息类型 | 说明 | +|---------|------| +| `group:task_split` | 任务拆分 | +| `group:task_assign` | 任务分配 | +| `group:task_merge` | 结果合并 | +| `group:task_progress` | 子任务进度 | + +#### 共识与投票 + +| 消息类型 | 说明 | +|---------|------| +| `group:vote` | 发起投票 | +| `group:vote_submit` | 提交投票 | +| `group:consensus` | 达成共识 | + +#### 人在回路(HiL) + +| 消息类型 | 说明 | +|---------|------| +| `group:consensus_escalate` | 共识僵局升级给人类 | +| `group:subtask_escalate` | 子任务阻塞升级给人类 | +| `group:human_decision` | 人类决策结果 | +| `inter_group:escalate` | 跨群组升级 | + +**完整定义:** [types/types.go](../types/types.go) + +--- + +## 4. 群组生命周期 + +### 4.1 状态机 + +``` +creating → active → frozen → disbanded + ↑ ↓ + └─────────┘ + 解冻 +``` + +### 4.2 群组创建流程 + +``` +创建者 被邀请成员 + | | + |------ group:invite -------------->| 发送邀请 + | | + |<----- group:accept_invite --------| 接受邀请 + | | + |------ group:member_update ------->| 通知成员更新 + | | + [群组创建完成,状态变为 active] | +``` + +### 4.3 群组解散流程 + +``` +coordinator 所有成员 + | | + |------ group:disband ------------->| 通知解散 + | | + [群组状态变为 disbanded] | +``` + +--- + +## 5. 任务协作流程 + +### 5.1 MapReduce 模式(拆分-执行-合并) + +``` + ┌──────────────┐ + │ coordinator │ + └──────┬───────┘ + │ + group:task_split(拆分任务) + │ + ┌────────────────┼────────────────┐ + ▼ ▼ ▼ + ┌─────────┐ ┌─────────┐ ┌─────────┐ + │ worker1 │ │ worker2 │ │ worker3 │ + └────┬────┘ └────┬────┘ └────┬────┘ + │ │ │ + │ 执行子任务 │ 执行子任务 │ 执行子任务 + │ │ │ + ▼ ▼ ▼ + 子任务结果 子任务结果 子任务结果 + └────────────────┼────────────────┘ + │ + group:task_merge(合并结果) + ▼ + ┌──────────────┐ + │ 最终结果 │ + └──────────────┘ +``` + +### 5.2 详细流程 + +1. **任务拆分阶段** + - coordinator 接收原始任务 + - 将任务拆分为多个子任务(subtask) + - 为每个子任务指定执行的 worker + - 定义合并策略(merge strategy) + +2. **并行执行阶段** + - 各 worker 并行执行子任务 + - 定期上报进度(`group:task_progress`) + - 子任务完成后上报结果 + +3. **结果合并阶段** + - 所有子任务完成后,coordinator 合并结果 + - 根据合并策略决定最终结果 + - 输出最终结果 + +--- + +## 6. 合并策略(Merge Strategy) + +| 策略 | 说明 | +|------|------| +| `all_success` | 全部成功才认为成功,否则失败 | +| `majority` | 多数子任务成功即可,取多数结果 | +| `any_complete` | 任意一个完成即返回结果 | +| `priority` | 按优先级,高优先级子任务结果优先 | + +--- + +## 7. 投票与共识 + +### 7.1 投票流程 + +``` +发起者 投票者 + | | + |-------- group:vote -------------->| 发起投票 + | | + |<------- group:vote_submit --------| 提交投票 + | | + [计票,判断是否达到阈值] | + | | + |-------- group:consensus --------->| 公布结果 + | | +``` + +### 7.2 投票规则 + +- `threshold`:通过阈值(0-1),如 0.5 表示过半 +- `deadline`:投票截止时间 +- `voters`:有投票权的成员列表 +- 超时未投票视为弃权 + +### 7.3 共识僵局(Consensus Deadlock) + +当投票无法达成共识(如平票、未达阈值且超时)时,可升级给人类决策。 + +--- + +## 8. 人在回路(HiL) + +群组协作中有两种升级场景: + +### 8.1 共识僵局升级 +投票无法达成共识时,升级给人类裁决。 + +**消息:** `group:consensus_escalate` + +### 8.2 子任务阻塞升级 +某个子任务遇到无法自动解决的问题时,升级给人类。 + +**消息:** `group:subtask_escalate` + +### 8.3 跨群组升级 +问题超出当前群组能力时,可升级到上级群组或人类。 + +**消息:** `inter_group:escalate` + +--- + +## 9. 接口规范 + +### 9.1 GroupProtocol 接口 + +```go +type GroupProtocol interface { + // 处理群组消息 + HandleMessage(ctx context.Context, msg *UnifiedSynapseMessage) (*UnifiedSynapseMessage, error) + + // 设置任务处理器 + SetTaskHandler(h GroupTaskHandler) + + // 查询群组列表 + GetGroups() []*AgentGroup + + // 查询特定群组 + GetGroup(groupID string) (*AgentGroup, bool) +} +``` + +**参考实现:** [group/protocol.go](../group/protocol.go) + +### 9.2 GroupTaskHandler 接口 + +```go +type GroupTaskHandler interface { + // 执行子任务 + ExecuteSubtask(ctx context.Context, subtaskID string, payload map[string]interface{}) (any, error) + + // 合并多个子任务结果 + MergeResults(results []SubtaskResult, strategy MergeStrategy) (any, error) + + // 验证任务是否可拆分,返回拆分方案 + ValidateTaskSplit(taskType string, requirements map[string]interface{}) ([]Subtask, bool) +} +``` + +**说明:** +- `ExecuteSubtask`:执行单个子任务的业务逻辑 +- `MergeResults`:根据策略合并多个子任务的结果 +- `ValidateTaskSplit`:验证任务是否可拆分,并给出拆分方案 + +### 9.3 配置项 + +```go +type GroupConfig struct { + MaxGroupSize int // 最大群组人数(默认 20) + MaxSubtasks int // 最大子任务数(默认 50) + ConsensusTimeout time.Duration // 共识超时(默认 5 分钟) + TaskTimeout time.Duration // 任务超时(默认 10 分钟) +} +``` + +--- + +## 10. 载荷格式 + +### 10.1 GroupCreatePayload(创建群组) + +```json +{ + "group": { + "name": "视频制作组", + "topology": "star", + "config": { + "allow_self_leave": true, + "requires_approval": false, + "consensus_required": false, + "consensus_threshold": 0.5, + "broadcast_mode": "all" + }, + "initial_members": [ + { + "agent_id": "worker-1", + "system_id": "sys-a", + "endpoint": "http://worker1/synapse" + } + ], + "roles": [ + { + "id": "coordinator", + "name": "协调者", + "permissions": ["create", "disband", "split", "vote"], + "max_tasks": 10 + } + ] + } +} +``` + +### 10.2 GroupTaskSplitPayload(任务拆分) + +```json +{ + "original_task": { + "id": "task-xxx", + "type": "video_generation", + "requirements": { + "script": "xxx", + "duration": 60 + }, + "deadline": "2026-01-01T00:10:00Z" + }, + "subtasks": [ + { + "id": "sub-1", + "description": "生成脚本", + "assigned_to": "writer-agent", + "dependencies": [], + "estimated_duration": 120, + "priority": 1 + }, + { + "id": "sub-2", + "description": "生成配音", + "assigned_to": "voice-agent", + "dependencies": ["sub-1"], + "estimated_duration": 180, + "priority": 2 + } + ], + "merge_strategy": "all_success" +} +``` + +### 10.3 GroupTaskMergePayload(结果合并) + +```json +{ + "original_task_id": "task-xxx", + "subtask_results": [ + { + "subtask_id": "sub-1", + "assigned_to": "writer-agent", + "status": "success", + "result": { "script": "..." }, + "completed_at": "2026-01-01T00:02:00Z" + } + ], + "merge_strategy_used": "all_success", + "merged_result": { + "video_url": "http://..." + }, + "consensus_achieved": true +} +``` + +### 10.4 GroupVotePayload(投票) + +```json +{ + "vote_id": "vote-xxx", + "question": "是否采用方案A?", + "options": ["方案A", "方案B", "方案C"], + "voters": ["agent-1", "agent-2", "agent-3"], + "deadline": "2026-01-01T00:05:00Z", + "threshold": 0.66, + "status": "open", + "votes": [] +} +``` + +### 10.5 GroupConsensusEscalatePayload(共识升级) + +```json +{ + "vote_id": "vote-xxx", + "escalation_id": "esc-xxx", + "question": "是否采用方案A?", + "votes": [ + { + "voter_id": "agent-1", + "voter_role": "reviewer", + "option": "方案A", + "reason": "质量更好" + } + ], + "consensus_status": { + "required_threshold": 0.66, + "actual_threshold": 0.33, + "leading_option": "方案A", + "options_tied": false + }, + "escalate_reason": { + "code": "no_consensus", + "message": "无法达成共识" + }, + "escalation_level": 2, + "deadline": "2026-01-01T00:10:00Z" +} +``` + +**完整载荷定义:** [types/types.go](../types/types.go) + +--- + +## 11. 数据结构 + +### 11.1 AgentGroup(群组) + +```go +type AgentGroup struct { + ID string + Name string + Topology GroupTopology + CreatedBy string + CreatedAt Timestamp + Config GroupConfig + Members []GroupMember + Roles []GroupRole + Status GroupStatus +} +``` + +### 11.2 GroupMember(群组成员) + +```go +type GroupMember struct { + AgentID string + AgentName string + Role string + JoinedAt Timestamp + Status GroupMemberStatus + Capabilities []string + LoadFactor float64 // 负载因子 0-1,用于任务分配 +} +``` + +### 11.3 Subtask(子任务) + +```go +type Subtask struct { + ID string + Description string + AssignedTo string + Dependencies []string + EstimatedDuration int + Priority int +} +``` + +--- + +## 12. 错误码 + +群组协议特有错误码: + +| 错误码 | 说明 | +|--------|------| +| `group_not_found` | 群组不存在 | +| `group_not_active` | 群组不活跃 | +| `group_full` | 群组已满 | +| `already_member` | 已是成员 | +| `not_group_member` | 不是群组成员 | +| `member_not_found` | 成员不存在 | +| `permission_denied` | 权限不足 | +| `invalid_params` | 参数无效 | + +--- + +## 13. 参考实现 + +本协议的参考实现位于 `group/` 目录: + +| 文件 | 说明 | +|------|------| +| [group/protocol.go](../group/protocol.go) | 群组协议核心实现 | +| [types/types.go](../types/types.go) | 群组相关数据类型 | + +--- + +## 附录 A:与 A2A 协议的关系 + +- 群组内的点对点通信使用 A2A 协议 +- 群组协议在 A2A 协议之上提供群组管理、任务拆分合并、共识投票等能力 +- 群组消息同样使用统一消息信封(`UnifiedSynapseMessage`),通过 `group_id` 字段标识群组上下文 diff --git a/docs/04-p2a-protocol.md b/docs/04-p2a-protocol.md new file mode 100644 index 0000000..70dc4ac --- /dev/null +++ b/docs/04-p2a-protocol.md @@ -0,0 +1,503 @@ +# P2A 协议(Person/Program-to-Agent Protocol) + +> 版本:1.0.0 +> 状态:草案 +> 类型:实现规范 +> 基于:[灵隙原始协议(Synapse Raw Protocol) v1.0.0](./01-synapse-raw-protocol.md) + +--- + +## 1. 概述 + +P2A(Person/Program-to-Agent)调用协议定义了**非 Agent 调用方**(如普通后端服务、前端应用、第三方系统、人类用户)如何调用 Agent 能力的规范。 + +本协议将 A2A 协议的复杂性封装起来,提供简洁的 RESTful API,使调用方无需了解 A2A 协议细节即可使用 Agent 能力。 + +### 1.1 适用场景 +- 前端应用直接调用 Agent 能力 +- 后端业务系统集成 Agent 服务 +- 第三方开发者通过 API 接入 +- 无需实现完整 A2A 协议的调用方 + +### 1.2 设计原则 +- **简单易用**:标准 RESTful API,JSON 格式 +- **两种模式**:回调模式 + 轮询模式,调用方按需选择 +- **认证简单**:API Key 认证,无需 HMAC 签名 +- **文件支持**:支持 multipart/form-data 上传文件 +- **错误友好**:清晰的错误码和错误信息 + +### 1.3 与 A2A 协议的关系 + +``` +外部调用方 ──P2A 协议──▶ External API Layer ──A2A 协议──▶ Agent +``` + +P2A 协议是 A2A 协议的"简化入口",所有请求最终会转换为 灵隙消息发送给 Agent。 + +--- + +## 2. 认证方式 + +### 2.1 API Key 认证 +- 在 HTTP Header 中传递:`X-API-Key: {api_key}` +- 或在 URL Query 中传递:`?api_key={api_key}` +- 如果服务端未配置 API Key,则跳过认证 + +### 2.2 回调验证(可选) +如果调用方提供了 `callback_token`,则服务端在回调时会在 Header 中带上 `X-Callback-Token`,用于调用方验证回调来源。 + +--- + +## 3. API 端点 + +所有端点默认前缀:`/api/v1/synapse` + +### 3.1 端点清单 + +| 方法 | 路径 | 说明 | +|------|------|------| +| POST | `/task` | 提交任务(JSON) | +| POST | `/task/multipart` | 提交任务(带文件上传) | +| GET | `/task/{task_id}` | 获取任务详情 | +| GET | `/task/{task_id}/status` | 获取任务状态(简化版) | +| GET | `/tasks` | 获取任务列表 | +| POST | `/task/{task_id}/cancel` | 取消任务 | +| GET | `/capabilities` | 获取能力清单 | +| POST | `/callback` | 接收回调(调用方实现) | + +--- + +## 4. 任务提交 + +### 4.1 提交任务(JSON) + +**请求:** +```http +POST /api/v1/synapse/task +Content-Type: application/json +X-API-Key: your-api-key + +{ + "task_type": "text_generation", + "payload": { + "prompt": "写一首诗", + "style": "古典" + }, + "external_task_id": "my-task-001", + "priority": "normal", + "callback_url": "https://your-domain.com/callback", + "callback_token": "your-callback-token" +} +``` + +**请求字段说明:** + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `task_type` | string | 是 | 任务类型,如 `video_generation`, `image_generation` | +| `payload` | object | 是 | 任务参数,具体结构取决于 task_type | +| `external_task_id` | string | 否 | 调用方的任务 ID,用于关联 | +| `priority` | string | 否 | 优先级:`low`, `normal`, `high`, `urgent`,默认 `normal` | +| `callback_url` | string | 否 | 回调 URL,不提供则需轮询 | +| `callback_token` | string | 否 | 回调验证 token | + +**响应:** +```json +{ + "success": true, + "task_id": "task-abc123", + "status": "received", + "message": "任务已接收" +} +``` + +**响应字段说明:** + +| 字段 | 类型 | 说明 | +|------|------|------| +| `success` | bool | 是否成功 | +| `task_id` | string | 服务端生成的任务 ID | +| `status` | string | 初始状态,通常为 `received` | +| `message` | string | 提示信息 | +| `error` | string | 错误信息(失败时) | + +### 4.2 提交任务(Multipart 带文件) + +**请求:** +```http +POST /api/v1/synapse/task/multipart +Content-Type: multipart/form-data +X-API-Key: your-api-key + +------WebKitFormBoundary +Content-Disposition: form-data; name="task_type" + +image_generation + +------WebKitFormBoundary +Content-Disposition: form-data; name="payload" + +{"prompt":"一只猫","style":"写实"} + +------WebKitFormBoundary +Content-Disposition: form-data; name="priority" + +normal + +------WebKitFormBoundary +Content-Disposition: form-data; name="file"; filename="reference.jpg" +Content-Type: image/jpeg + +[二进制数据] + +------WebKitFormBoundary-- +``` + +**表单字段:** + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `task_type` | string | 是 | 任务类型 | +| `payload` | string(JSON) | 是 | 任务参数(JSON 字符串) | +| `external_task_id` | string | 否 | 外部任务 ID | +| `priority` | string | 否 | 优先级 | +| `callback_url` | string | 否 | 回调 URL | +| `callback_token` | string | 否 | 回调 token | +| `file` | file | 否 | 上传的文件(可多个) | + +**响应:** 同 JSON 提交方式 + +--- + +## 5. 任务查询 + +### 5.1 获取任务详情 + +**请求:** +```http +GET /api/v1/synapse/task/{task_id} +X-API-Key: your-api-key +``` + +**响应:** +```json +{ + "success": true, + "task": { + "id": "task-abc123", + "type": "text_generation", + "status": "completed", + "progress": 100, + "message": "任务已完成", + "created_at": "2026-01-01T00:00:00Z", + "updated_at": "2026-01-01T00:01:00Z", + "completed_at": "2026-01-01T00:01:00Z", + "eta": "2026-01-01T00:01:00Z", + "result": { + "text": "生成的文本...", + "metadata": { "tokens": 1024 } + }, + "error": null, + "external_task_id": "my-task-001" + } +} +``` + +**任务状态:** + +| 状态 | 说明 | +|------|------| +| `received` | 已接收 | +| `processing` | 处理中 | +| `completed` | 已完成 | +| `failed` | 已失败 | +| `cancelled` | 已取消 | + +### 5.2 获取任务状态(简化版) + +**请求:** +```http +GET /api/v1/synapse/task/{task_id}/status +X-API-Key: your-api-key +``` + +**响应:** +```json +{ + "success": true, + "task_id": "task-abc123", + "status": "processing", + "progress": 50 +} +``` + +### 5.3 获取任务列表 + +**请求:** +```http +GET /api/v1/synapse/tasks?status=processing&limit=20&offset=0 +X-API-Key: your-api-key +``` + +**查询参数:** + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `status` | string | 否 | 按状态过滤 | +| `limit` | int | 否 | 每页数量,默认 20 | +| `offset` | int | 否 | 偏移量,默认 0 | + +**响应:** +```json +{ + "success": true, + "tasks": [ + { + "id": "task-abc123", + "type": "text_generation", + "status": "completed", + "progress": 100, + "created_at": "2026-01-01T00:00:00Z", + "updated_at": "2026-01-01T00:01:00Z" + } + ], + "total": 1, + "limit": 20, + "offset": 0, + "has_more": false +} +``` + +--- + +## 6. 任务取消 + +**请求:** +```http +POST /api/v1/synapse/task/{task_id}/cancel +X-API-Key: your-api-key +``` + +**响应:** +```json +{ + "success": true, + "task_id": "task-abc123", + "status": "cancelled", + "message": "任务已取消" +} +``` + +--- + +## 7. 能力查询 + +**请求:** +```http +GET /api/v1/synapse/capabilities +X-API-Key: your-api-key +``` + +**响应:** +```json +{ + "success": true, + "capabilities": { + "agent_id": "my-agent", + "agent_name": "我的Agent", + "system_id": "my-system", + "protocol_version": "1.0.0", + "supported_task_types": [ + { + "type": "text_generation", + "name": "文本生成", + "description": "生成各种类型的文本内容", + "estimated_time": "30s", + "input_schema": "...", + "output_schema": "..." + } + ], + "supported_transport_modes": ["callback", "polling"], + "max_file_size": 104857600, + "max_concurrent_tasks": 10, + "support_progress_updates": true, + "support_streaming": false, + "support_hil": true, + "support_groups": true + } +} +``` + +--- + +## 8. 回调机制 + +如果调用方提供了 `callback_url`,服务端会在任务状态变化时主动回调。 + +### 8.1 回调请求 + +```http +POST {callback_url} +Content-Type: application/json +X-Callback-Token: {callback_token} + +{ + "task_id": "task-abc123", + "status": "completed", + "progress": 100, + "message": "任务已完成", + "result": { + "text": "生成的文本..." + }, + "error": null, + "timestamp": "2026-01-01T00:01:00Z" +} +``` + +### 8.2 回调类型 + +| 触发时机 | 说明 | +|---------|------| +| 任务开始处理 | `status=processing`, `progress=0` | +| 进度更新 | `status=processing`, `progress=N` | +| 任务完成 | `status=completed`, `progress=100`, 包含 result | +| 任务失败 | `status=failed`, 包含 error | +| 任务取消 | `status=cancelled` | + +### 8.3 回调响应 + +调用方应返回 2xx 状态码表示成功接收。如果返回非 2xx,服务端会重试(指数退避,最多 5 次)。 + +--- + +## 9. 错误处理 + +### 9.1 错误响应格式 + +```json +{ + "success": false, + "error": "invalid_task_type", + "message": "不支持的任务类型" +} +``` + +### 9.2 错误码列表 + +| 错误码 | HTTP 状态码 | 说明 | +|--------|------------|------| +| `unauthorized` | 401 | API Key 无效或缺失 | +| `invalid_request` | 400 | 请求格式无效 | +| `invalid_task_type` | 400 | 任务类型不支持 | +| `invalid_params` | 400 | 参数无效 | +| `task_not_found` | 404 | 任务不存在 | +| `task_already_completed` | 409 | 任务已完成,无法取消 | +| `file_too_large` | 413 | 文件过大 | +| `rate_limited` | 429 | 请求过于频繁 | +| `internal_error` | 500 | 服务内部错误 | +| `service_unavailable` | 503 | 服务不可用 | + +--- + +## 10. SDK 客户端接口 + +为方便调用方集成,提供 SDK 客户端。 + +### 10.1 SDK 初始化 + +```go +client := sdk.NewClient(sdk.ClientConfig{ + BaseURL: "https://agent-api.example.com", + APIKey: "your-api-key", + Timeout: 30 * time.Second, +}) +``` + +### 10.2 SDK 方法清单 + +| 方法 | 说明 | +|------|------| +| `SubmitTask(ctx, req)` | 提交任务(JSON) | +| `SubmitTaskWithFiles(ctx, req, files)` | 提交任务(带文件) | +| `GetTask(ctx, taskID)` | 获取任务详情 | +| `GetTaskStatus(ctx, taskID)` | 获取任务状态 | +| `ListTasks(ctx, status, limit, offset)` | 获取任务列表 | +| `CancelTask(ctx, taskID)` | 取消任务 | +| `GetCapabilities(ctx)` | 获取能力清单 | +| `WaitForTask(ctx, taskID, interval)` | 等待任务完成(轮询) | + +### 10.3 数据结构 + +```go +type TaskRequest struct { + TaskType string + Payload map[string]any + ExternalTaskID string + Priority string + CallbackURL string + CallbackToken string +} + +type TaskInfo struct { + ID string + Type string + Status string + Progress int + Message string + CreatedAt string + UpdatedAt string + CompletedAt string + ETA string + Result map[string]any + Error *TaskError + ExternalTaskID string +} +``` + +**完整 SDK 实现:** [sdk/client.go](../sdk/client.go) + +--- + +## 11. 参考实现 + +本协议的参考实现: + +| 模块 | 文件路径 | 说明 | +|------|---------|------| +| 服务端 | [externalapi/handler.go](../externalapi/handler.go) | External API Handler | +| 客户端 SDK | [sdk/client.go](../sdk/client.go) | Go 语言 SDK | + +--- + +## 附录 A:调用模式选择 + +### 回调模式 vs 轮询模式 + +| 对比项 | 回调模式 | 轮询模式 | +|--------|---------|---------| +| 实时性 | 高,状态变化即时通知 | 低,取决于轮询间隔 | +| 实现复杂度 | 调用方需提供公网可访问的回调接口 | 简单,只需调用 GET 接口 | +| 网络要求 | 调用方需要公网可达 | 只需调用方能访问服务端 | +| 适用场景 | 生产环境、需要实时通知 | 开发测试、内网环境 | + +### 选择建议 + +- **有公网服务器**:使用回调模式 +- **本地开发 / 内网环境**:使用轮询模式 +- **长时间任务**:建议回调模式,避免频繁轮询 +- **短任务(<10s)**:可直接同步等待或高频轮询 + +--- + +## 附录 B:从 A2A 协议到 P2A 协议的映射 + +| 灵隙概念 | P2A 对应 | 说明 | +|---------|---------|------| +| `p2p:task_request` | `POST /task` | 任务提交 | +| `p2p:task_status_update` | 回调 / GET /task | 状态更新 | +| `p2p:task_complete` | 回调(status=completed) | 任务完成 | +| `p2p:task_failed` | 回调(status=failed) | 任务失败 | +| `p2p:task_cancel` | `POST /task/{id}/cancel` | 任务取消 | +| `p2p:capability_query` | `GET /capabilities` | 能力查询 | +| Agent 身份 | API Key | 简化认证 | +| HMAC 签名 | Callback Token | 简化验证 | diff --git a/docs/05-sdk-implementation.md b/docs/05-sdk-implementation.md index 5235ed7..684a996 100644 --- a/docs/05-sdk-implementation.md +++ b/docs/05-sdk-implementation.md @@ -483,7 +483,7 @@ func main() { | 协议名称 | 协议文档 | SDK 包名 | 包路径 | |---------|---------|---------|--------| -| 灵隙原始协议(Synapse Raw Protocol) | [01-a2a-raw-protocol.md](./01-a2a-raw-protocol.md) | - | 纲领性文档 | +| 灵隙原始协议(Synapse Raw Protocol) | [01-synapse-raw-protocol.md](./01-synapse-raw-protocol.md) | - | 纲领性文档 | | A2A 协议 | [02-a2a-protocol.md](./02-a2a-protocol.md) | `a2a` | `sdk/a2a/` | | A2N 协议 | [03-a2n-protocol.md](./03-a2n-protocol.md) | `a2n` | `sdk/a2n/` | | P2A 协议 | [04-p2a-protocol.md](./04-p2a-protocol.md) | `p2a` | `sdk/p2a/` |