灵隙(synapse) v1.0.0 版本
This commit is contained in:
245
MIGRATION.md
245
MIGRATION.md
@@ -1,245 +0,0 @@
|
|||||||
# A2A 协议迁移说明
|
|
||||||
|
|
||||||
## 概述
|
|
||||||
|
|
||||||
本文档记录了从 `ai-video-factory` 项目中抽离 A2A(Agent-to-Agent)协议和 Group(群组)相关代码到独立模块的过程。
|
|
||||||
|
|
||||||
## 源项目信息
|
|
||||||
|
|
||||||
- **源项目**: `ai-video-factory`
|
|
||||||
- **源路径**: `ai-video-factory/a2aprotocol/`
|
|
||||||
- **目标项目**: `dp-headless`
|
|
||||||
- **目标路径**: `dp-headless/a2a/`
|
|
||||||
|
|
||||||
## 模块路径变更
|
|
||||||
|
|
||||||
| 项目 | 模块路径 |
|
|
||||||
|------|----------|
|
|
||||||
| 源 | `ai-video-factory/a2aprotocol/` |
|
|
||||||
| 目标 | `dp-headless/a2a/` |
|
|
||||||
|
|
||||||
所有 Go 文件中的 import 路径已从 `ai-video-factory/a2aprotocol/xxx` 更新为 `dp-headless/a2a/xxx`。
|
|
||||||
|
|
||||||
## 目录结构
|
|
||||||
|
|
||||||
```
|
|
||||||
a2a/
|
|
||||||
├── go.mod # Go 模块定义
|
|
||||||
├── proto/
|
|
||||||
│ └── a2a.proto # gRPC 协议定义
|
|
||||||
├── types/ # 核心类型定义
|
|
||||||
│ ├── types.go # 基础类型、消息类型、任务状态
|
|
||||||
│ ├── content.go # 内容类型(文本、图片、视频、音频等)
|
|
||||||
│ └── errors.go # 错误定义
|
|
||||||
├── p2p/ # P2P 协议
|
|
||||||
│ └── protocol.go # 点对点任务处理协议
|
|
||||||
├── group/ # 群组协议
|
|
||||||
│ └── protocol.go # 群组协作协议(创建、解散、任务拆分合并)
|
|
||||||
├── routing/ # 消息路由
|
|
||||||
│ └── router.go # 消息路由器(P2P/群组分发)
|
|
||||||
├── transport/ # 传输层
|
|
||||||
│ ├── transport.go # HTTP 传输实现
|
|
||||||
│ └── multipart_polling.go # 多部分文件传输和轮询客户端
|
|
||||||
├── capabilities/ # 能力发现
|
|
||||||
│ └── provider.go # Agent 能力提供者
|
|
||||||
├── externalapi/ # 外部 REST API
|
|
||||||
│ └── handler.go # 简化的 RESTful API 处理器
|
|
||||||
├── sdk/ # SDK
|
|
||||||
│ └── client.go # 外部调用者 SDK 客户端
|
|
||||||
├── grpcapi/ # gRPC API
|
|
||||||
│ ├── a2a.pb.go # gRPC 消息生成代码
|
|
||||||
│ ├── a2a_grpc.pb.go # gRPC 服务生成代码
|
|
||||||
│ ├── client.go # gRPC 客户端实现
|
|
||||||
│ └── server.go # gRPC 服务端实现
|
|
||||||
├── hil/ # 人机协同(HiL)
|
|
||||||
│ └── protocol.go # 人工介入任务处理协议
|
|
||||||
└── examples/ # 示例代码
|
|
||||||
└── main.go # 完整使用示例
|
|
||||||
```
|
|
||||||
|
|
||||||
## 迁移的文件清单
|
|
||||||
|
|
||||||
### types 包(3 个文件)
|
|
||||||
- `types/types.go` - 核心数据类型:AgentEndpoint、A2AMessage、TaskPayload、TaskStatus 等
|
|
||||||
- `types/content.go` - 内容类型:TextContent、ImageContent、VideoContent、AudioContent、FileContent
|
|
||||||
- `types/errors.go` - 错误定义:TaskError、错误码常量
|
|
||||||
|
|
||||||
### p2p 包(1 个文件)
|
|
||||||
- `p2p/protocol.go` - P2P 协议实现:任务提交、状态更新、结果回调、取消任务
|
|
||||||
|
|
||||||
### group 包(1 个文件)
|
|
||||||
- `group/protocol.go` - 群组协议实现:群组创建/解散、成员管理、任务拆分/合并、投票机制
|
|
||||||
|
|
||||||
### routing 包(1 个文件)
|
|
||||||
- `routing/router.go` - 消息路由器:根据消息类型分发到 P2P 或群组处理器
|
|
||||||
|
|
||||||
### transport 包(2 个文件)
|
|
||||||
- `transport/transport.go` - HTTP 传输:发送消息、处理回调、签名验证
|
|
||||||
- `transport/multipart_polling.go` - 多部分文件传输和轮询客户端
|
|
||||||
|
|
||||||
### capabilities 包(1 个文件)
|
|
||||||
- `capabilities/provider.go` - Agent 能力提供者:能力声明、能力查询
|
|
||||||
|
|
||||||
### externalapi 包(1 个文件)
|
|
||||||
- `externalapi/handler.go` - 外部 REST API:任务提交/查询/取消、能力查询
|
|
||||||
|
|
||||||
### sdk 包(1 个文件)
|
|
||||||
- `sdk/client.go` - SDK 客户端:封装 A2A 协议调用,简化外部集成
|
|
||||||
|
|
||||||
### grpcapi 包(4 个文件)
|
|
||||||
- `grpcapi/a2a.pb.go` - Protobuf 生成的消息类型
|
|
||||||
- `grpcapi/a2a_grpc.pb.go` - Protobuf 生成的 gRPC 服务接口
|
|
||||||
- `grpcapi/client.go` - gRPC 客户端实现
|
|
||||||
- `grpcapi/server.go` - gRPC 服务端实现
|
|
||||||
|
|
||||||
### hil 包(1 个文件)
|
|
||||||
- `hil/protocol.go` - 人机协同协议:人工决策请求/响应、任务挂起/恢复
|
|
||||||
|
|
||||||
### proto(1 个文件)
|
|
||||||
- `proto/a2a.proto` - gRPC 协议定义文件
|
|
||||||
|
|
||||||
### examples(1 个文件)
|
|
||||||
- `examples/main.go` - 完整使用示例
|
|
||||||
|
|
||||||
**总计:17 个 Go 源文件 + 1 个 proto 文件 + 1 个 go.mod**
|
|
||||||
|
|
||||||
## 核心功能
|
|
||||||
|
|
||||||
### 1. P2P 任务协议
|
|
||||||
- 任务提交与响应
|
|
||||||
- 任务状态查询与更新
|
|
||||||
- 任务取消
|
|
||||||
- 进度回调
|
|
||||||
- 信息缺失通知
|
|
||||||
|
|
||||||
### 2. 群组协作协议
|
|
||||||
- 群组创建与解散
|
|
||||||
- 成员加入与离开
|
|
||||||
- 任务拆分与分发
|
|
||||||
- 子任务结果收集
|
|
||||||
- 结果合并
|
|
||||||
- 投票机制(发起投票、提交投票、公布结果)
|
|
||||||
|
|
||||||
### 3. 传输层
|
|
||||||
- HTTP 回调模式
|
|
||||||
- 轮询模式
|
|
||||||
- 同步模式
|
|
||||||
- 混合模式
|
|
||||||
- HMAC 签名验证
|
|
||||||
- 多部分文件上传
|
|
||||||
|
|
||||||
### 4. 能力发现
|
|
||||||
- Agent 能力声明
|
|
||||||
- 能力查询接口
|
|
||||||
- 支持的任务类型
|
|
||||||
- 支持的传输模式
|
|
||||||
- 并发能力限制
|
|
||||||
|
|
||||||
### 5. 人机协同(HiL)
|
|
||||||
- 人工决策请求
|
|
||||||
- 决策响应
|
|
||||||
- 任务挂起与恢复
|
|
||||||
- 超时处理
|
|
||||||
|
|
||||||
### 6. gRPC 支持
|
|
||||||
- TaskService - 任务服务
|
|
||||||
- A2AMessageService - 消息服务
|
|
||||||
- CapabilitiesService - 能力服务
|
|
||||||
- GroupService - 群组服务
|
|
||||||
- HealthService - 健康检查
|
|
||||||
|
|
||||||
## 使用示例
|
|
||||||
|
|
||||||
### 快速开始
|
|
||||||
|
|
||||||
```go
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"dp-headless/a2a/capabilities"
|
|
||||||
"dp-headless/a2a/externalapi"
|
|
||||||
"dp-headless/a2a/group"
|
|
||||||
"dp-headless/a2a/p2p"
|
|
||||||
"dp-headless/a2a/routing"
|
|
||||||
"dp-headless/a2a/transport"
|
|
||||||
"dp-headless/a2a/types"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
// 1. 定义 Agent 端点
|
|
||||||
agentEndpoint := types.AgentEndpoint{
|
|
||||||
AgentID: "my-agent",
|
|
||||||
AgentName: "我的Agent",
|
|
||||||
SystemID: "my-system",
|
|
||||||
Endpoint: "http://localhost:8080/api/v1/a2a/callback",
|
|
||||||
Version: "1.0.0",
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 配置能力提供者
|
|
||||||
caps := &capabilities.AgentCapabilityProvider{
|
|
||||||
AgentID: agentEndpoint.AgentID,
|
|
||||||
AgentName: agentEndpoint.AgentName,
|
|
||||||
SystemID: agentEndpoint.SystemID,
|
|
||||||
SupportedTaskTypes: []capabilities.SupportedTaskType{
|
|
||||||
{Type: "text_generation", Name: "文本生成"},
|
|
||||||
},
|
|
||||||
SupportGroups: true,
|
|
||||||
SupportHiL: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. 创建 P2P 协议处理器
|
|
||||||
p2pProtocol := p2p.NewP2PProtocol(agentEndpoint, caps,
|
|
||||||
func(taskID string, taskType string, payload map[string]interface{}) (map[string]interface{}, error) {
|
|
||||||
// 处理任务逻辑
|
|
||||||
return map[string]interface{}{"result": "success"}, nil
|
|
||||||
})
|
|
||||||
|
|
||||||
// 4. 创建群组协议处理器
|
|
||||||
groupConfig := &group.GroupConfig{MaxGroupSize: 10}
|
|
||||||
groupProtocol := group.NewGroupProtocol(agentEndpoint, nil, groupConfig)
|
|
||||||
|
|
||||||
// 5. 配置消息路由
|
|
||||||
router := routing.NewMessageRouter(agentEndpoint)
|
|
||||||
router.RegisterP2PHandler(p2pProtocol)
|
|
||||||
router.RegisterGroupHandler(groupProtocol)
|
|
||||||
|
|
||||||
// 6. 启动 HTTP 服务
|
|
||||||
httpTransport := transport.NewHTTPTransport(agentEndpoint, nil, router)
|
|
||||||
extHandler := externalapi.NewExternalAPIHandler(p2pProtocol, caps, httpTransport)
|
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
|
||||||
extHandler.RegisterRoutes(mux, "/api/v1/a2a")
|
|
||||||
http.ListenAndServe(":8080", mux)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
完整示例请参考 `examples/main.go`。
|
|
||||||
|
|
||||||
## 依赖项
|
|
||||||
|
|
||||||
```
|
|
||||||
- github.com/golang/protobuf v1.5.4
|
|
||||||
- github.com/gorilla/websocket v1.5.3
|
|
||||||
- golang.org/x/image v0.42.0
|
|
||||||
- google.golang.org/grpc v1.68.0
|
|
||||||
- google.golang.org/protobuf v1.35.2
|
|
||||||
- modernc.org/sqlite v1.52.0
|
|
||||||
```
|
|
||||||
|
|
||||||
## 未迁移的内容
|
|
||||||
|
|
||||||
以下内容因与 ai-video-factory 业务逻辑强耦合,未包含在本次迁移中:
|
|
||||||
|
|
||||||
1. **旧版 A2A 实现**(`a2a.go` 和 `a2a_api.go`)- 基于 SQLite 的简单实现,与视频生成工作流深度绑定
|
|
||||||
2. **数据库集成** - 旧版的 SQLite 数据库层
|
|
||||||
3. **视频工作流集成** - 与 VideoCreationWorkflow 的集成代码
|
|
||||||
|
|
||||||
如需数据库持久化,建议基于现有的协议层自行实现存储适配层。
|
|
||||||
|
|
||||||
## 后续可扩展方向
|
|
||||||
|
|
||||||
1. 添加持久化存储接口(Memory/Redis/PostgreSQL 等)
|
|
||||||
2. 实现完整的 gRPC 网关
|
|
||||||
3. 添加更多传输协议支持(WebSocket、MQTT 等)
|
|
||||||
4. 增加单元测试和集成测试
|
|
||||||
5. 完善文档和示例
|
|
||||||
216
docs/v0/00-architecture.md
Normal file
216
docs/v0/00-architecture.md
Normal file
@@ -0,0 +1,216 @@
|
|||||||
|
# 灵隙 Synapse 协议栈架构说明
|
||||||
|
|
||||||
|
> **灵隙通万智,脉动定乾坤。**
|
||||||
|
>
|
||||||
|
> Synapse connects myriad wisdoms; the Meridian settles the cosmos.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 一、架构总览
|
||||||
|
|
||||||
|
灵隙协议栈采用 **分层 + 组件化** 设计,从下到上共分四层:
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────┐
|
||||||
|
│ 组合协议层 (Composite Protocols) │
|
||||||
|
│ ┌─────────┐ ┌─────────┐ ┌──────────┐ ┌─────────┐ │
|
||||||
|
│ │ A2N群组 │ │ 工作流 │ │ 联邦学习 │ │ ... │ │
|
||||||
|
│ └────┬────┘ └────┬────┘ └─────┬────┘ └────┬────┘ │
|
||||||
|
└───────┼─────────────┼──────────────┼──────────────┼──────┘
|
||||||
|
│ │ │ │
|
||||||
|
┌───────▼─────────────▼──────────────▼──────────────▼──────┐
|
||||||
|
│ 组件层 (Pluggable Components) │
|
||||||
|
│ │
|
||||||
|
│ ┌─────────────────────────────────────────────────┐ │
|
||||||
|
│ │ 灵脉 Meridian - 寻址与路由 │ │
|
||||||
|
│ │ 灵玺 Sigil - 身份与凭证 │ │
|
||||||
|
│ │ 灵鉴 Speculum - 共识与裁决 │ │
|
||||||
|
│ │ 灵泊 Harbor - 异步队列与暂存 │ │
|
||||||
|
│ │ 灵瞰 Panorama - 可观测与度量 │ │
|
||||||
|
│ │ 灵衡 Libra - 价值结算与激励 │ │
|
||||||
|
│ │ 灵枢 Pivot - 紧急制动与治理 │ │
|
||||||
|
│ └─────────────────────────────────────────────────┘ │
|
||||||
|
└──────────────────────────┬───────────────────────────────┘
|
||||||
|
│
|
||||||
|
┌──────────────────────────▼───────────────────────────────┐
|
||||||
|
│ 基础协议层 (Base Protocols) │
|
||||||
|
│ │
|
||||||
|
│ ┌─────────────────┐ ┌────────────────────────┐ │
|
||||||
|
│ │ P2A 协议 │ │ A2A 协议 │ │
|
||||||
|
│ │ 外部调用 → Agent│ │ Agent ↔ Agent (点对点)│ │
|
||||||
|
│ └─────────────────┘ └────────────────────────┘ │
|
||||||
|
└──────────────────────────┬───────────────────────────────┘
|
||||||
|
│
|
||||||
|
┌──────────────────────────▼───────────────────────────────┐
|
||||||
|
│ 传输层 (Transport Layer) │
|
||||||
|
│ HTTP / gRPC / WebSocket / ... │
|
||||||
|
└──────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、命名体系
|
||||||
|
|
||||||
|
### 核心命名
|
||||||
|
|
||||||
|
| 层级 | 英文 | 中文 | 释义 |
|
||||||
|
|------|------|------|------|
|
||||||
|
| 协议栈总名 | **Synapse** | **灵隙** | 突触,神经细胞间的连接缝隙。既有生物神经的精密感,又有"灵光一现的缝隙"的东方禅意。 |
|
||||||
|
|
||||||
|
### 七大组件
|
||||||
|
|
||||||
|
| 组件 | 英文代号 | 中文名 | 对应场景 | 释义 |
|
||||||
|
|------|----------|--------|----------|------|
|
||||||
|
| 寻址与路由层 | **Meridian** | **灵脉** (Líng Mài) | Agent 发现与拓扑连接 | 取中医"经脉"之意。Agent 之间虽有空隙(灵隙),但暗中有能量流动的轨迹(脉)。此层负责维护全局路由表,让新 Agent "通脉"入网,旧 Agent "断脉"离场。 |
|
||||||
|
| 身份与凭证层 | **Sigil** | **灵玺** (Líng Xǐ) | 防伪、授权与零信任 | 皇帝的玉玺是最高凭证。每个 Agent 的初始身份都需经过"铸玺"过程,每一次交互都要"验玺",确保穿透零信任边界后的每一次握手都正统且不可篡改。 |
|
||||||
|
| 共识与裁决层 | **Speculum** | **灵鉴** (Líng Jiàn) | 多 Agent 辩论、投票与冲突解决 | 古有"以史为鉴",今有"以智为鉴"。此层不是粗暴的少数服从多数,而是让各方 Agent 将推理过程"照"进公共镜面,通过对比逻辑链的严密性来达成共识。 |
|
||||||
|
| 异步队列与暂存层 | **Harbor** | **灵泊** (Líng Bó) | 离线缓冲、任务积压与重试 | "泊"为船舶停靠。数据包如远行之舟,遇风浪(网络抖动)时暂泊于此,待风平浪静(目标就绪)再启航。不丢包、不超时。 |
|
||||||
|
| 可观测与度量层 | **Panorama** | **灵瞰** (Líng Kàn) | 全链路追踪、日志与健康度 | 居高临下,俯瞰全局。此层不参与业务交互,却如"天眼"般记录每一帧交互的耗时、置信度与资源消耗,让黑盒群体智能变为白盒可解释的图景。 |
|
||||||
|
| 价值结算与激励层 | **Libra** | **灵衡** (Líng Héng) | Agent 间的资源兑换、Token 支付 | 权衡利弊,计量公平。此层负责将 Agent 间的"智力贡献"与"资源消耗"通证化,动态定价,让多智能体经济具备自驱的盈亏平衡。 |
|
||||||
|
| 紧急制动与治理层 | **Pivot** | **灵枢** (Líng Shū) | 协议升级、熔断与伦理闸门 | 取自《灵枢经》(黄帝内经下半部),讲的是针灸经络之枢纽。这是整个协议的"总闸"与"方向盘",不轻易触发,但触发时能以最小代价重置整个网络状态。 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
synapse/
|
||||||
|
│
|
||||||
|
├── types/ # 核心类型定义
|
||||||
|
│ ├── types.go # 消息结构、Agent端点、任务负载等
|
||||||
|
│ ├── errors.go # 错误码与错误类型
|
||||||
|
│ └── content.go # 内容格式定义
|
||||||
|
│
|
||||||
|
├── transport/ # 传输层
|
||||||
|
│ ├── transport.go # 传输接口与HTTP传输实现
|
||||||
|
│ └── multipart_polling.go # 多部分轮询传输
|
||||||
|
│
|
||||||
|
├── meridian/ # 灵脉 - 寻址与路由层
|
||||||
|
│ └── meridian.go # Agent注册发现、消息路由、拓扑管理
|
||||||
|
│
|
||||||
|
├── sigil/ # 灵玺 - 身份与凭证层
|
||||||
|
│ └── sigil.go # 身份管理、签名验证、授权令牌
|
||||||
|
│
|
||||||
|
├── p2p/ # A2A 协议 - Agent间点对点通信
|
||||||
|
│ └── protocol.go # P2P消息处理器、任务管理
|
||||||
|
│
|
||||||
|
├── externalapi/ # P2A 协议 - 外部调用API
|
||||||
|
│ └── handler.go # REST API处理器
|
||||||
|
│
|
||||||
|
├── group/ # A2N 协议 - 群组协作 (组合协议)
|
||||||
|
│ └── protocol.go # 群组管理、任务拆分合并、投票
|
||||||
|
│
|
||||||
|
├── speculum/ # 灵鉴 - 共识与裁决层
|
||||||
|
│ └── speculum.go # 共识引擎、仲裁机制、推理镜面
|
||||||
|
│
|
||||||
|
├── harbor/ # 灵泊 - 异步队列与暂存层
|
||||||
|
│ └── harbor.go # 消息队列、离线缓冲、重试管理
|
||||||
|
│
|
||||||
|
├── panorama/ # 灵瞰 - 可观测与度量层
|
||||||
|
│ └── panorama.go # 链路追踪、指标收集、健康检查
|
||||||
|
│
|
||||||
|
├── libra/ # 灵衡 - 价值结算与激励层
|
||||||
|
│ └── libra.go # 账本记账、定价引擎、结算系统
|
||||||
|
│
|
||||||
|
├── pivot/ # 灵枢 - 紧急制动与治理层
|
||||||
|
│ └── pivot.go # 熔断器、治理管理、协议升级
|
||||||
|
│
|
||||||
|
├── capabilities/ # 能力声明
|
||||||
|
│ └── provider.go # 能力提供器接口与标准接口
|
||||||
|
│
|
||||||
|
├── hil/ # 人工介入 (Human-in-the-Loop)
|
||||||
|
│ └── protocol.go # HiL协议处理
|
||||||
|
│
|
||||||
|
├── routing/ # 旧版路由(将迁移至 meridian)
|
||||||
|
│ └── router.go # 消息路由器(保留兼容)
|
||||||
|
│
|
||||||
|
├── grpcapi/ # gRPC API
|
||||||
|
│ ├── server.go # gRPC服务端
|
||||||
|
│ ├── client.go # gRPC客户端
|
||||||
|
│ ├── synapse.pb.go # Protobuf生成代码
|
||||||
|
│ └── synapse_grpc.pb.go # gRPC生成代码
|
||||||
|
│
|
||||||
|
├── proto/ # Protobuf定义
|
||||||
|
│ └── synapse.proto # 协议定义文件
|
||||||
|
│
|
||||||
|
├── sdk/ # SDK
|
||||||
|
│ ├── doc.go # SDK包文档
|
||||||
|
│ ├── p2p/ # A2A SDK - P2P点对点通信
|
||||||
|
│ │ └── client.go
|
||||||
|
│ ├── group/ # A2N SDK - 群组协作
|
||||||
|
│ │ └── client.go
|
||||||
|
│ └── caller/ # P2A SDK - 外部调用
|
||||||
|
│ └── client.go
|
||||||
|
│
|
||||||
|
├── docs/ # 协议文档
|
||||||
|
│ ├── 01-synapse-raw-protocol.md
|
||||||
|
│ ├── 02-p2p-protocol.md
|
||||||
|
│ ├── 03-group-protocol.md
|
||||||
|
│ ├── 04-caller-protocol.md
|
||||||
|
│ ├── 05-sdk-implementation.md
|
||||||
|
│ └── 06-solutions-whitepaper.md
|
||||||
|
│
|
||||||
|
├── examples/ # 示例代码
|
||||||
|
│ ├── p2p_demo/ # P2P通讯示例
|
||||||
|
│ └── group_demo/ # Group群组示例
|
||||||
|
│
|
||||||
|
├── go.mod
|
||||||
|
├── go.sum
|
||||||
|
└── MIGRATION.md
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、设计原则
|
||||||
|
|
||||||
|
### 1. 内核极简,组件扩展
|
||||||
|
|
||||||
|
- **基础协议层(P2A + A2A)** 是最小内核,只定义消息格式和基本交互
|
||||||
|
- **七大组件** 是可插拔能力,按需加载
|
||||||
|
- **组合协议层** 通过装配不同组件生成高级协议
|
||||||
|
|
||||||
|
### 2. 命名统一,东方美学
|
||||||
|
|
||||||
|
- 所有组件统一"灵"字前缀:灵脉、灵玺、灵鉴、灵泊、灵瞰、灵衡、灵枢
|
||||||
|
- 英文代号各有出处:Meridian(经脉)、Sigil(纹章)、Speculum(镜鉴)、Harbor(港湾)、Panorama(全景)、Libra(天平)、Pivot(枢轴)
|
||||||
|
|
||||||
|
### 3. 接口清晰,松耦合
|
||||||
|
|
||||||
|
每个组件都定义清晰的接口,组件之间通过接口交互,而非直接依赖。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、组合协议示例
|
||||||
|
|
||||||
|
### A2N 群组协议 = A2A + 灵鉴 + 灵脉 + 灵泊
|
||||||
|
|
||||||
|
```
|
||||||
|
A2N (群组协作)
|
||||||
|
├── A2A 协议 # 基础点对点通信
|
||||||
|
├── 灵鉴 Speculum # 投票与共识
|
||||||
|
├── 灵脉 Meridian # 成员发现与拓扑
|
||||||
|
├── 灵泊 Harbor # 消息队列与离线缓冲
|
||||||
|
└── 灵瞰 Panorama # (可选)可观测性
|
||||||
|
```
|
||||||
|
|
||||||
|
### 联邦学习协议 = A2A + 灵鉴 + 灵衡 + 灵枢
|
||||||
|
|
||||||
|
```
|
||||||
|
联邦学习
|
||||||
|
├── A2A 协议 # 基础通信
|
||||||
|
├── 灵鉴 Speculum # 模型聚合共识
|
||||||
|
├── 灵衡 Libra # 贡献度计量与激励
|
||||||
|
└── 灵枢 Pivot # 训练中止与治理
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 六、Slogan
|
||||||
|
|
||||||
|
> **灵隙通万智,脉动定乾坤。**
|
||||||
|
>
|
||||||
|
> (Synapse connects myriad wisdoms; the Meridian settles the cosmos.)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*灵隙 Synapse 协议栈 v1.0.0*
|
||||||
328
docs/v0/01-synapse-raw-protocol.md
Normal file
328
docs/v0/01-synapse-raw-protocol.md
Normal file
@@ -0,0 +1,328 @@
|
|||||||
|
# 灵隙原始协议(Synapse Raw Protocol)
|
||||||
|
|
||||||
|
> 版本:1.0.0
|
||||||
|
> 状态:草案
|
||||||
|
> 类型:纲领性文档
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 协议愿景
|
||||||
|
|
||||||
|
灵隙(Synapse,原 Agent-to-Agent)协议旨在定义一套通用的、可扩展的智能体间通信标准,使不同系统、不同厂商、不同能力的智能体能够在统一的协议框架下进行协作、交易与能力组合。
|
||||||
|
|
||||||
|
本协议是灵隙协议族(Synapse Protocol Suite)的原始纲领,定义核心设计理念、架构原则与术语体系,为所有衍生协议提供顶层指导。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 核心设计理念
|
||||||
|
|
||||||
|
### 2.1 去中心化对等(Peer-to-Peer)
|
||||||
|
- 所有 Agent 在协议层面地位平等,无中心化控制节点
|
||||||
|
- 每个 Agent 既是服务提供者,也是服务消费者
|
||||||
|
- Agent 间直接通信,不依赖中间 broker(传输层可选择不同实现)
|
||||||
|
|
||||||
|
### 2.2 能力驱动(Capability-Driven)
|
||||||
|
- 通信以能力为核心,而非以身份为核心
|
||||||
|
- Agent 声明自身能力,按需发现与调用
|
||||||
|
- 能力可组合、可分解、可升级
|
||||||
|
|
||||||
|
### 2.3 任务导向(Task-Oriented)
|
||||||
|
- 所有交互围绕"任务"展开
|
||||||
|
- 任务有明确的生命周期、状态机与超时机制
|
||||||
|
- 任务支持拆分、合并、委派与协作
|
||||||
|
|
||||||
|
### 2.4 人类可介入(Human-in-the-Loop)
|
||||||
|
- 协议原生支持人类介入决策
|
||||||
|
- Agent 可主动请求人类判断
|
||||||
|
- 人类决策优先于 Agent 自动决策
|
||||||
|
- 支持多级升级(escalation)机制
|
||||||
|
|
||||||
|
### 2.5 群组协作(Group Collaboration)
|
||||||
|
- 支持多 Agent 组成临时或永久群组
|
||||||
|
- 群组内有角色分工与权限控制
|
||||||
|
- 支持任务拆分-执行-合并的 MapReduce 模式
|
||||||
|
- 支持投票、共识等群体决策机制
|
||||||
|
|
||||||
|
### 2.6 传输无关(Transport Agnostic)
|
||||||
|
- 协议语义与底层传输分离
|
||||||
|
- 支持 HTTP/2、gRPC、WebSocket、消息队列等多种传输
|
||||||
|
- 支持回调(Callback)、轮询(Polling)、同步(Sync)、混合(Hybrid)等多种交互模式
|
||||||
|
|
||||||
|
### 2.7 安全可信(Secure & Trustworthy)
|
||||||
|
- 消息级签名与验证
|
||||||
|
- Agent 身份认证与信任等级
|
||||||
|
- 支持加密传输
|
||||||
|
- 可审计、可追溯
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 协议分层架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ 应用层 (Application) │
|
||||||
|
│ 业务逻辑、工作流、领域特定逻辑 │
|
||||||
|
├─────────────────────────────────────────┤
|
||||||
|
│ 协议层 (Protocol) │
|
||||||
|
├─────────────┬───────────────────────────┤
|
||||||
|
│ A2A 协议 │ A2N 组群协议 │ ← 本协议族
|
||||||
|
│ (P2P) │ (Group) │
|
||||||
|
├─────────────┴───────────────────────────┤
|
||||||
|
│ 传输层 (Transport) │
|
||||||
|
│ HTTP / gRPC / WebSocket / MQ ... │
|
||||||
|
├─────────────────────────────────────────┤
|
||||||
|
│ 网络层 (Network) │
|
||||||
|
│ TCP / UDP / QUIC ... │
|
||||||
|
└─────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.1 协议族构成
|
||||||
|
|
||||||
|
| 协议名称 | 缩写 | 描述 | 适用场景 |
|
||||||
|
|---------|------|------|---------|
|
||||||
|
| 灵隙原始协议(Synapse Raw Protocol) | A2A-Raw | 顶层纲领,定义理念、术语、原则 | 指导所有协议设计 |
|
||||||
|
| A2A 协议 | A2A-Base | 点对点任务协作协议 | 两个 Agent 间的任务交互 |
|
||||||
|
| A2N 组群协议 | A2N-Group | 多 Agent 群组协作协议 | 多个 Agent 协同完成任务 |
|
||||||
|
| P2A 调用协议 | P2A-Caller | 非 Agent 调用者接入协议 | 普通服务/前端调用 Agent 能力 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 核心概念与术语
|
||||||
|
|
||||||
|
### 4.1 Agent(智能体)
|
||||||
|
能够自主感知环境、做出决策并执行动作的计算实体。
|
||||||
|
|
||||||
|
**属性:**
|
||||||
|
- `agent_id`:Agent 唯一标识
|
||||||
|
- `system_id`:所属系统标识
|
||||||
|
- `endpoint`:通信端点地址
|
||||||
|
- `capabilities`:能力清单
|
||||||
|
- `trust_level`:信任等级
|
||||||
|
|
||||||
|
### 4.2 Task(任务)
|
||||||
|
Agent 间协作的基本单位,具有明确的输入、输出与生命周期。
|
||||||
|
|
||||||
|
**属性:**
|
||||||
|
- `task_id`:任务唯一标识
|
||||||
|
- `task_type`:任务类型
|
||||||
|
- `payload`:任务载荷
|
||||||
|
- `status`:任务状态
|
||||||
|
- `priority`:优先级
|
||||||
|
- `deadline`:截止时间
|
||||||
|
|
||||||
|
### 4.3 Message(消息)
|
||||||
|
Agent 间通信的基本单位。
|
||||||
|
|
||||||
|
**属性:**
|
||||||
|
- `message_id`:消息唯一标识
|
||||||
|
- `type`:消息类型
|
||||||
|
- `sender`:发送方
|
||||||
|
- `receiver`:接收方(P2P)
|
||||||
|
- `group_id`:群组标识(群组)
|
||||||
|
- `payload`:消息载荷
|
||||||
|
- `correlation_id`:关联标识(用于请求-响应关联)
|
||||||
|
- `timestamp`:时间戳
|
||||||
|
- `signature`:签名
|
||||||
|
|
||||||
|
### 4.4 Capability(能力)
|
||||||
|
Agent 能够执行的任务类型的声明。
|
||||||
|
|
||||||
|
**属性:**
|
||||||
|
- `type`:能力对应的任务类型
|
||||||
|
- `name`:能力名称
|
||||||
|
- `description`:能力描述
|
||||||
|
- `input_schema`:输入参数 schema
|
||||||
|
- `output_schema`:输出结果 schema
|
||||||
|
- `estimated_time`:预估耗时
|
||||||
|
|
||||||
|
### 4.5 Group(群组)
|
||||||
|
由多个 Agent 组成的协作单元。
|
||||||
|
|
||||||
|
**属性:**
|
||||||
|
- `group_id`:群组唯一标识
|
||||||
|
- `name`:群组名称
|
||||||
|
- `topology`:拓扑结构
|
||||||
|
- `members`:成员列表
|
||||||
|
- `roles`:角色定义
|
||||||
|
- `status`:群组状态
|
||||||
|
|
||||||
|
### 4.6 Human-in-the-Loop(人在回路)
|
||||||
|
在 Agent 协作过程中,人类可介入进行决策的机制。
|
||||||
|
|
||||||
|
**关键概念:**
|
||||||
|
- `escalation`:升级(将问题提交给人类)
|
||||||
|
- `decision`:决策(人类做出的判断)
|
||||||
|
- `resume`:恢复(人类决策后继续执行)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 设计原则
|
||||||
|
|
||||||
|
### 5.1 简约性(Simplicity)
|
||||||
|
- 核心机制保持简单
|
||||||
|
- 复杂功能通过组合基础机制实现
|
||||||
|
- 可选功能通过能力声明来协商
|
||||||
|
|
||||||
|
### 5.2 可扩展性(Extensibility)
|
||||||
|
- 消息类型可扩展
|
||||||
|
- 能力类型可扩展
|
||||||
|
- 传输方式可扩展
|
||||||
|
- 通过版本号与能力协商保证向后兼容
|
||||||
|
|
||||||
|
### 5.3 容错性(Fault Tolerance)
|
||||||
|
- 网络不可靠是常态
|
||||||
|
- 消息可能丢失、重复、延迟
|
||||||
|
- Agent 可能故障、离线
|
||||||
|
- 协议必须有重试、超时、降级机制
|
||||||
|
|
||||||
|
### 5.4 可观测性(Observability)
|
||||||
|
- 所有交互可追踪
|
||||||
|
- 任务状态可查询
|
||||||
|
- 支持日志、指标、链路追踪
|
||||||
|
|
||||||
|
### 5.5 互操作性(Interoperability)
|
||||||
|
- 不同语言、不同框架的 Agent 可互操作
|
||||||
|
- 协议规范优先于具体实现
|
||||||
|
- 提供标准测试用例验证兼容性
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 消息模型总则
|
||||||
|
|
||||||
|
### 6.1 统一消息信封
|
||||||
|
所有协议共享统一的消息信封结构,具体载荷由消息类型决定。
|
||||||
|
|
||||||
|
```
|
||||||
|
UnifiedSynapseMessage
|
||||||
|
├── id // 消息ID
|
||||||
|
├── version // 协议版本
|
||||||
|
├── type // 消息类型
|
||||||
|
├── sender // 发送方 AgentEndpoint
|
||||||
|
├── receiver? // 接收方(P2P 时)
|
||||||
|
├── group_id? // 群组ID(群组时)
|
||||||
|
├── correlation_id // 关联ID
|
||||||
|
├── reply_to? // 回复的消息ID
|
||||||
|
├── payload // 消息载荷(JSON)
|
||||||
|
├── priority? // 优先级
|
||||||
|
├── signature? // 签名
|
||||||
|
├── timestamp // 发送时间
|
||||||
|
└── expires_at? // 过期时间
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 消息命名规范
|
||||||
|
- 使用 `领域:动作` 格式
|
||||||
|
- 全小写,用下划线分隔
|
||||||
|
- 示例:`p2p:task_request`, `group:create`, `hil:decision`
|
||||||
|
|
||||||
|
### 6.3 请求-响应模式
|
||||||
|
- 请求消息必须携带唯一 `id`
|
||||||
|
- 响应消息通过 `reply_to` 关联请求
|
||||||
|
- 支持 ACK/NACK 机制
|
||||||
|
- 超时未收到响应应重试或报错
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 任务生命周期总则
|
||||||
|
|
||||||
|
### 7.1 状态机
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────┐
|
||||||
|
│ pending │ 待确认
|
||||||
|
└────┬─────┘
|
||||||
|
│ 确认/拒绝
|
||||||
|
┌─────┴──────┐
|
||||||
|
▼ ▼
|
||||||
|
┌─────────┐ ┌──────────┐
|
||||||
|
│confirmed│ │ rejected │ 已拒绝(终态)
|
||||||
|
└────┬────┘ └──────────┘
|
||||||
|
│ 开始执行
|
||||||
|
▼
|
||||||
|
┌──────────┐
|
||||||
|
│executing │ 执行中
|
||||||
|
└────┬─────┘
|
||||||
|
│ 信息缺失
|
||||||
|
┌────▼─────┐
|
||||||
|
│info_needed│ 需要信息
|
||||||
|
└────┬─────┘
|
||||||
|
│ 信息补充
|
||||||
|
▼
|
||||||
|
回到 executing
|
||||||
|
│
|
||||||
|
├──────────────┐
|
||||||
|
│ 需人类决策 │
|
||||||
|
▼ ▼
|
||||||
|
┌──────────┐ ┌───────────┐
|
||||||
|
│need_human│ │ 各种终态 │
|
||||||
|
└────┬─────┘ └───────────┘
|
||||||
|
│ 人类决策
|
||||||
|
▼
|
||||||
|
回到 executing
|
||||||
|
│
|
||||||
|
┌────┴────┬─────────┐
|
||||||
|
▼ ▼ ▼
|
||||||
|
completed failed cancelled
|
||||||
|
(完成) (失败) (取消)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.2 终态
|
||||||
|
- `completed`:成功完成
|
||||||
|
- `failed`:执行失败
|
||||||
|
- `cancelled`:被取消
|
||||||
|
- `rejected`:被拒绝
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 安全模型总则
|
||||||
|
|
||||||
|
### 8.1 身份认证
|
||||||
|
- 每个 Agent 有唯一身份
|
||||||
|
- 支持 HMAC、JWT、OAuth2 等多种认证方式
|
||||||
|
- 信任等级机制
|
||||||
|
|
||||||
|
### 8.2 消息完整性
|
||||||
|
- 消息签名机制
|
||||||
|
- 防止篡改与伪造
|
||||||
|
|
||||||
|
### 8.3 机密性
|
||||||
|
- 支持端到端加密
|
||||||
|
- 敏感载荷加密传输
|
||||||
|
|
||||||
|
### 8.4 访问控制
|
||||||
|
- 基于信任等级的权限控制
|
||||||
|
- 群组内基于角色的权限控制
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 非目标
|
||||||
|
|
||||||
|
以下内容**不在**本原始协议的讨论范围内:
|
||||||
|
|
||||||
|
1. **具体传输协议的实现细节** - 由各传输层实现定义
|
||||||
|
2. **特定领域的任务类型** - 由应用层或领域扩展定义
|
||||||
|
3. **Agent 内部实现架构** - 仅定义对外接口与行为
|
||||||
|
4. **具体编程语言绑定** - 语言无关,可多语言实现
|
||||||
|
5. **UI/UX 设计** - 人机界面不在协议范围内
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. 参考实现
|
||||||
|
|
||||||
|
本协议族的参考实现位于:`dp-headless/synapse/`
|
||||||
|
|
||||||
|
| 模块 | 对应协议 | 文件路径 |
|
||||||
|
|------|---------|---------|
|
||||||
|
| types 包 | 公共类型定义 | `types/` |
|
||||||
|
| p2p 包 | A2A 协议 | `p2p/` |
|
||||||
|
| group 包 | A2N 组群协议 | `group/` |
|
||||||
|
| externalapi 包 | P2A 调用协议 | `externalapi/` |
|
||||||
|
| sdk 包 | P2A 客户端 SDK | `sdk/` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 附录 A:协议演进
|
||||||
|
|
||||||
|
本原始协议作为顶层指导,保持相对稳定。各具体协议可独立版本化演进,但需遵循本协议定义的核心原则。
|
||||||
|
|
||||||
|
**版本历史:**
|
||||||
|
- v1.0.0:初始版本,定义核心概念与设计原则
|
||||||
465
docs/v0/02-p2p-protocol.md
Normal file
465
docs/v0/02-p2p-protocol.md
Normal file
@@ -0,0 +1,465 @@
|
|||||||
|
# A2A 协议(Agent-to-Agent Protocol)
|
||||||
|
|
||||||
|
> 版本:1.0.0
|
||||||
|
> 状态:草案
|
||||||
|
> 类型:实现规范
|
||||||
|
> 基于:[灵隙原始协议(Synapse Raw Protocol) v1.0.0](./01-a2a-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-a2a-raw-protocol.md#44-capability能力)
|
||||||
545
docs/v0/03-group-protocol.md
Normal file
545
docs/v0/03-group-protocol.md
Normal file
@@ -0,0 +1,545 @@
|
|||||||
|
# A2N 协议(Agent-to-N Protocol)
|
||||||
|
|
||||||
|
> 版本:1.0.0
|
||||||
|
> 状态:草案
|
||||||
|
> 类型:实现规范
|
||||||
|
> 基于:[灵隙原始协议(Synapse Raw Protocol) v1.0.0](./01-a2a-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` 字段标识群组上下文
|
||||||
503
docs/v0/04-caller-protocol.md
Normal file
503
docs/v0/04-caller-protocol.md
Normal file
@@ -0,0 +1,503 @@
|
|||||||
|
# P2A 协议(Person/Program-to-Agent Protocol)
|
||||||
|
|
||||||
|
> 版本:1.0.0
|
||||||
|
> 状态:草案
|
||||||
|
> 类型:实现规范
|
||||||
|
> 基于:[灵隙原始协议(Synapse Raw Protocol) v1.0.0](./01-a2a-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 | 简化验证 |
|
||||||
519
docs/v0/05-sdk-implementation.md
Normal file
519
docs/v0/05-sdk-implementation.md
Normal file
@@ -0,0 +1,519 @@
|
|||||||
|
# SDK 实现说明
|
||||||
|
|
||||||
|
> 版本:1.0.0
|
||||||
|
> 更新日期:2026-06-27
|
||||||
|
> 协议版本:1.0.0
|
||||||
|
> 关联协议:
|
||||||
|
> - [A2A 协议](./02-a2a-protocol.md)
|
||||||
|
> - [A2N 协议](./03-a2n-protocol.md)
|
||||||
|
> - [P2A 协议](./04-p2a-protocol.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 概述
|
||||||
|
|
||||||
|
SDK 按照灵隙协议族(Synapse Protocol Suite)的三个子协议进行了模块化设计,分为三个子包,命名与协议名保持一致:
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ SDK (sdk/) │
|
||||||
|
├──────────────┬───────────────────┬───────────────────────────┤
|
||||||
|
│ sdk/p2a │ sdk/a2a │ sdk/a2n │
|
||||||
|
│ P2A 协议 │ A2A 协议 │ A2N 协议 │
|
||||||
|
│ (外部调用) │ (Agent间通信) │ (群组协作) │
|
||||||
|
│ ✅ 完整实现 │ ✅ 完整实现 │ ✅ 完整实现 │
|
||||||
|
└──────────────┴───────────────────┴───────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. SDK 目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
sdk/
|
||||||
|
├── doc.go # SDK 包文档(使用说明)
|
||||||
|
├── p2a/
|
||||||
|
│ └── client.go # P2A 协议 - 外部调用客户端
|
||||||
|
├── a2a/
|
||||||
|
│ └── client.go # A2A 协议 - Agent间通信客户端
|
||||||
|
└── a2n/
|
||||||
|
└── client.go # A2N 协议 - 群组协作客户端
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 第一部分:sdk/p2a - P2A 协议
|
||||||
|
|
||||||
|
**协议对应**:[P2A 协议](./04-p2a-protocol.md)
|
||||||
|
**版本**:1.0.0
|
||||||
|
**用途**:非 Agent 调用方(前端、后端服务、第三方应用)通过 REST API 调用 Agent 能力
|
||||||
|
|
||||||
|
### 3.1 实现对应关系
|
||||||
|
|
||||||
|
| P2A 协议功能 | SDK 方法 | 位置 |
|
||||||
|
|-------------|---------|------|
|
||||||
|
| 认证方式 | `setHeaders()` | [sdk/p2a/client.go](../sdk/p2a/client.go) |
|
||||||
|
| 提交任务(JSON) | `SubmitTask()` | [sdk/p2a/client.go](../sdk/p2a/client.go) |
|
||||||
|
| 提交任务(Multipart) | `SubmitTaskWithFiles()` | [sdk/p2a/client.go](../sdk/p2a/client.go) |
|
||||||
|
| 获取任务详情 | `GetTask()` | [sdk/p2a/client.go](../sdk/p2a/client.go) |
|
||||||
|
| 获取任务状态(简化版) | `GetTaskStatus()` | [sdk/p2a/client.go](../sdk/p2a/client.go) |
|
||||||
|
| 获取任务列表 | `ListTasks()` | [sdk/p2a/client.go](../sdk/p2a/client.go) |
|
||||||
|
| 取消任务 | `CancelTask()` | [sdk/p2a/client.go](../sdk/p2a/client.go) |
|
||||||
|
| 能力查询 | `GetCapabilities()` | [sdk/p2a/client.go](../sdk/p2a/client.go) |
|
||||||
|
| 回调验证 | `VerifyCallback()` | [sdk/p2a/client.go](../sdk/p2a/client.go) |
|
||||||
|
| 轮询等待 | `WaitForTask()` | [sdk/p2a/client.go](../sdk/p2a/client.go) |
|
||||||
|
|
||||||
|
### 3.2 核心数据结构
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Client 客户端
|
||||||
|
type Client struct {
|
||||||
|
baseURL string
|
||||||
|
apiKey string
|
||||||
|
httpClient *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
// 配置
|
||||||
|
type ClientConfig struct {
|
||||||
|
BaseURL string
|
||||||
|
APIKey string
|
||||||
|
Timeout time.Duration
|
||||||
|
MaxRetries int
|
||||||
|
}
|
||||||
|
|
||||||
|
// 任务请求
|
||||||
|
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
|
||||||
|
Result map[string]any
|
||||||
|
Error *TaskError
|
||||||
|
}
|
||||||
|
|
||||||
|
// 文件上传参数
|
||||||
|
type FileParam struct {
|
||||||
|
FieldName string
|
||||||
|
Filename string
|
||||||
|
Data []byte
|
||||||
|
MimeType string
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 使用示例
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "dp-headless/synapse/sdk/p2a"
|
||||||
|
|
||||||
|
client := p2a.NewClient(p2a.ClientConfig{
|
||||||
|
BaseURL: "https://agent-api.example.com",
|
||||||
|
APIKey: "your-api-key",
|
||||||
|
})
|
||||||
|
|
||||||
|
// 提交任务并等待完成
|
||||||
|
taskInfo, err := client.CreateAndWait(ctx, "text_generation", map[string]any{
|
||||||
|
"prompt": "写一首诗",
|
||||||
|
"style": "古典",
|
||||||
|
}, 5*time.Second)
|
||||||
|
|
||||||
|
// 使用回调模式
|
||||||
|
resp, err := client.CreateWithCallback(ctx, "image_generation", payload,
|
||||||
|
"https://your-domain.com/callback",
|
||||||
|
"callback-token",
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 第二部分:sdk/a2a - A2A 协议
|
||||||
|
|
||||||
|
**协议对应**:[A2A 协议](./02-a2a-protocol.md)
|
||||||
|
**版本**:1.0.0
|
||||||
|
**用途**:Agent 之间的点对点通信,包含消息发送、签名验证、回调处理
|
||||||
|
|
||||||
|
### 4.1 实现对应关系
|
||||||
|
|
||||||
|
| A2A 协议功能 | SDK 方法 | 位置 |
|
||||||
|
|------------|---------|------|
|
||||||
|
| 发送任务请求 | `SendTaskRequest()` | [sdk/a2a/client.go](../sdk/a2a/client.go) |
|
||||||
|
| 发送任务取消 | `SendTaskCancel()` | [sdk/a2a/client.go](../sdk/a2a/client.go) |
|
||||||
|
| 发送人类决策 | `SendHumanDecision()` | [sdk/a2a/client.go](../sdk/a2a/client.go) |
|
||||||
|
| 查询能力 | `SendCapabilityQuery()` | [sdk/a2a/client.go](../sdk/a2a/client.go) |
|
||||||
|
| 消息签名 | `signMessage()` | [sdk/a2a/client.go](../sdk/a2a/client.go) |
|
||||||
|
| 签名验证 | `verifySignature()` | [sdk/a2a/client.go](../sdk/a2a/client.go) |
|
||||||
|
| 任务状态管理 | `GetTaskState()`, `ListTasks()` | [sdk/a2a/client.go](../sdk/a2a/client.go) |
|
||||||
|
| 等待任务完成 | `WaitForTask()` | [sdk/a2a/client.go](../sdk/a2a/client.go) |
|
||||||
|
| 回调服务 | `startCallbackServer()` | [sdk/a2a/client.go](../sdk/a2a/client.go) |
|
||||||
|
|
||||||
|
### 4.2 核心数据结构
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Client A2A客户端
|
||||||
|
type Client struct {
|
||||||
|
agentEndpoint types.AgentEndpoint
|
||||||
|
authSecret string
|
||||||
|
callbackHandler MessageCallbackHandler
|
||||||
|
tasks map[string]*A2ATaskState
|
||||||
|
}
|
||||||
|
|
||||||
|
// 配置
|
||||||
|
type ClientConfig struct {
|
||||||
|
AgentEndpoint types.AgentEndpoint
|
||||||
|
AuthSecret string
|
||||||
|
CallbackPort int
|
||||||
|
Timeout time.Duration
|
||||||
|
MaxRetries int
|
||||||
|
}
|
||||||
|
|
||||||
|
// 消息回调处理器接口
|
||||||
|
type MessageCallbackHandler interface {
|
||||||
|
HandleTaskRequest(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error)
|
||||||
|
HandleTaskStatusUpdate(ctx context.Context, msg *types.UnifiedSynapseMessage) error
|
||||||
|
HandleTaskComplete(ctx context.Context, msg *types.UnifiedSynapseMessage) error
|
||||||
|
HandleTaskFailed(ctx context.Context, msg *types.UnifiedSynapseMessage) error
|
||||||
|
HandleNeedHuman(ctx context.Context, msg *types.UnifiedSynapseMessage) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// 任务状态
|
||||||
|
type A2ATaskState struct {
|
||||||
|
TaskID string
|
||||||
|
Status types.P2PTaskStatus
|
||||||
|
Progress int
|
||||||
|
Message string
|
||||||
|
Result any
|
||||||
|
Error *types.SynapseError
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 使用示例
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "dp-headless/synapse/sdk/a2a"
|
||||||
|
|
||||||
|
a2aClient, err := a2a.NewClient(&a2a.ClientConfig{
|
||||||
|
AgentEndpoint: types.AgentEndpoint{
|
||||||
|
AgentID: "my-agent",
|
||||||
|
AgentName: "我的Agent",
|
||||||
|
SystemID: "my-system",
|
||||||
|
Endpoint: "http://localhost:8080/synapse/callback",
|
||||||
|
},
|
||||||
|
AuthSecret: "my-hmac-secret",
|
||||||
|
CallbackPort: 8080,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 设置消息处理器
|
||||||
|
a2aClient.SetMessageHandler(&myHandler{})
|
||||||
|
|
||||||
|
// 发送任务请求给其他Agent
|
||||||
|
taskID, err := a2aClient.SendTaskRequest(ctx, targetAgent, "video_generation", map[string]any{
|
||||||
|
"prompt": "生成一段视频",
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 第三部分:sdk/a2n - A2N 协议
|
||||||
|
|
||||||
|
**协议对应**:[A2N 协议](./03-a2n-protocol.md)
|
||||||
|
**版本**:1.0.0
|
||||||
|
**用途**:多 Agent 群组协作,包含群组管理、任务拆分合并、投票、升级
|
||||||
|
|
||||||
|
### 5.1 实现对应关系
|
||||||
|
|
||||||
|
| A2N 协议功能 | SDK 方法 | 位置 |
|
||||||
|
|------------|---------|------|
|
||||||
|
| 创建群组 | `CreateGroup()` | [sdk/a2n/client.go](../sdk/a2n/client.go) |
|
||||||
|
| 加入群组 | `JoinGroup()` | [sdk/a2n/client.go](../sdk/a2n/client.go) |
|
||||||
|
| 离开群组 | `LeaveGroup()` | [sdk/a2n/client.go](../sdk/a2n/client.go) |
|
||||||
|
| 解散群组 | `DisbandGroup()` | [sdk/a2n/client.go](../sdk/a2n/client.go) |
|
||||||
|
| 提交群组任务 | `SubmitGroupTask()` | [sdk/a2n/client.go](../sdk/a2n/client.go) |
|
||||||
|
| 发送子任务结果 | `SendSubtaskResult()` | [sdk/a2n/client.go](../sdk/a2n/client.go) |
|
||||||
|
| 发起投票 | `InitiateVote()` | [sdk/a2n/client.go](../sdk/a2n/client.go) |
|
||||||
|
| 提交投票 | `SubmitVote()` | [sdk/a2n/client.go](../sdk/a2n/client.go) |
|
||||||
|
| 广播消息 | `Broadcast()` | [sdk/a2n/client.go](../sdk/a2n/client.go) |
|
||||||
|
| 升级到人类 | `EscalateToHuman()` | [sdk/a2n/client.go](../sdk/a2n/client.go) |
|
||||||
|
|
||||||
|
### 5.2 核心数据结构
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Client A2N客户端
|
||||||
|
type Client struct {
|
||||||
|
a2aClient *a2a.Client
|
||||||
|
groups map[string]*GroupState
|
||||||
|
eventHandler GroupEventHandler
|
||||||
|
}
|
||||||
|
|
||||||
|
// 配置
|
||||||
|
type ClientConfig struct {
|
||||||
|
A2AClient *a2a.Client
|
||||||
|
EventHandler GroupEventHandler
|
||||||
|
}
|
||||||
|
|
||||||
|
// 群组状态
|
||||||
|
type GroupState struct {
|
||||||
|
GroupID string
|
||||||
|
Name string
|
||||||
|
Topology types.GroupTopology
|
||||||
|
Status types.GroupStatus
|
||||||
|
Members []types.GroupMember
|
||||||
|
Role string // "coordinator" | "worker"
|
||||||
|
}
|
||||||
|
|
||||||
|
// 群组事件处理器接口
|
||||||
|
type GroupEventHandler interface {
|
||||||
|
OnGroupCreated(ctx context.Context, groupID string) error
|
||||||
|
OnGroupDisbanded(ctx context.Context, groupID string) error
|
||||||
|
OnMemberJoined(ctx context.Context, groupID string, member types.GroupMember) error
|
||||||
|
OnMemberLeft(ctx context.Context, groupID string, agentID string) error
|
||||||
|
OnTaskSplit(ctx context.Context, groupID string, originalTaskID string, subtasks []types.Subtask) error
|
||||||
|
OnSubtaskProgress(ctx context.Context, groupID string, subtaskID string, progress int) error
|
||||||
|
OnTaskMerged(ctx context.Context, groupID string, originalTaskID string, result any) error
|
||||||
|
OnVoteInitiated(ctx context.Context, groupID string, vote types.GroupVotePayload) error
|
||||||
|
OnVoteResult(ctx context.Context, groupID string, voteID string, option string, passed bool) error
|
||||||
|
OnEscalation(ctx context.Context, groupID string, escalationID string, level int) error
|
||||||
|
OnBroadcast(ctx context.Context, groupID string, sender types.AgentEndpoint, message []byte) error
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.3 使用示例
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"dp-headless/synapse/sdk/a2n"
|
||||||
|
"dp-headless/synapse/sdk/a2a"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 创建A2A客户端
|
||||||
|
a2aClient, _ := a2a.NewClient(&a2a.ClientConfig{
|
||||||
|
AgentEndpoint: myEndpoint,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 创建A2N客户端
|
||||||
|
a2nClient, err := a2n.NewClient(&a2n.ClientConfig{
|
||||||
|
A2AClient: a2aClient,
|
||||||
|
EventHandler: &myGroupHandler{},
|
||||||
|
})
|
||||||
|
|
||||||
|
// 创建群组
|
||||||
|
group, err := a2nClient.CreateGroup(ctx, "视频制作组", types.GroupTopologyStar, nil, members)
|
||||||
|
|
||||||
|
// 作为Coordinator,提交任务
|
||||||
|
subtasks, err := a2nClient.SubmitGroupTask(ctx, group.GroupID, "video_generation",
|
||||||
|
map[string]any{"script": "..."},
|
||||||
|
types.MergeAllSuccess,
|
||||||
|
)
|
||||||
|
|
||||||
|
// 发起投票
|
||||||
|
voteID, err := a2nClient.InitiateVote(ctx, group.GroupID,
|
||||||
|
"选择哪个方案?",
|
||||||
|
[]string{"方案A", "方案B"},
|
||||||
|
voterIDs,
|
||||||
|
0.5,
|
||||||
|
5*time.Minute,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. SDK 架构总览
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ SDK (dp-headless/synapse/sdk) │
|
||||||
|
├─────────────────────────────────────────────────────────────┤
|
||||||
|
│ doc.go │
|
||||||
|
│ ├── 包文档和使用说明 │
|
||||||
|
│ └── 指向各子包的链接 │
|
||||||
|
├────────────────┬────────────────┬─────────────────────────┤
|
||||||
|
│ sdk/p2a │ sdk/a2a │ sdk/a2n │
|
||||||
|
│ │ │ │
|
||||||
|
│ P2A协议 │ 灵隙协议 │ A2N协议 │
|
||||||
|
│ │ │ │
|
||||||
|
│ ├── Client │ ├── Client │ ├── Client │
|
||||||
|
│ ├── 配置 │ ├── 配置 │ ├── 配置 │
|
||||||
|
│ ├── 任务操作 │ ├── 消息发送 │ ├── 群组管理 │
|
||||||
|
│ ├── 能力查询 │ ├── 任务状态 │ ├── 任务协作 │
|
||||||
|
│ └── 回调验证 │ ├── 回调服务 │ ├── 投票 │
|
||||||
|
│ │ └── 签名 │ └── 升级 │
|
||||||
|
└────────────────┴────────────────┴─────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 快速开始
|
||||||
|
|
||||||
|
### 7.1 P2A 调用(外部调用者)
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"dp-headless/synapse/sdk/p2a"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
client := p2a.NewClient(p2a.ClientConfig{
|
||||||
|
BaseURL: "https://agent.example.com",
|
||||||
|
APIKey: "your-api-key",
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// 方式1: 轮询等待
|
||||||
|
result, err := client.CreateAndWait(ctx, "text_generation", map[string]any{
|
||||||
|
"prompt": "写一首诗",
|
||||||
|
}, 5*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Error:", err)
|
||||||
|
}
|
||||||
|
fmt.Printf("Result: %v\n", result.Result)
|
||||||
|
|
||||||
|
// 方式2: 回调模式
|
||||||
|
resp, err := client.CreateWithCallback(ctx, "image_generation",
|
||||||
|
map[string]any{"prompt": "一只猫"},
|
||||||
|
"https://your-domain.com/callback",
|
||||||
|
"token",
|
||||||
|
)
|
||||||
|
fmt.Printf("Task ID: %s\n", resp.TaskID)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.2 灵隙 通信(Agent 间)
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"dp-headless/synapse/sdk/a2a"
|
||||||
|
"dp-headless/synapse/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
client, _ := a2a.NewClient(&a2a.ClientConfig{
|
||||||
|
AgentEndpoint: types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
AgentName: "Agent 001",
|
||||||
|
SystemID: "my-system",
|
||||||
|
Endpoint: "http://localhost:8080/synapse/callback",
|
||||||
|
},
|
||||||
|
AuthSecret: "secret-key",
|
||||||
|
CallbackPort: 8080,
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
target := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-002",
|
||||||
|
Endpoint: "http://agent-002:8080/synapse/callback",
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送任务请求
|
||||||
|
taskID, err := client.SendTaskRequest(ctx, target, "data_analysis", map[string]any{
|
||||||
|
"dataset": "sales.csv",
|
||||||
|
})
|
||||||
|
fmt.Printf("Task ID: %s\n", taskID)
|
||||||
|
|
||||||
|
// 等待完成
|
||||||
|
state, err := client.WaitForTask(ctx, taskID, 5*time.Minute)
|
||||||
|
fmt.Printf("Status: %s\n", state.Status)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.3 A2N 群组协作
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"dp-headless/synapse/sdk/a2n"
|
||||||
|
"dp-headless/synapse/sdk/a2a"
|
||||||
|
"dp-headless/synapse/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
a2aClient, _ := a2a.NewClient(&a2a.ClientConfig{
|
||||||
|
AgentEndpoint: myEndpoint,
|
||||||
|
})
|
||||||
|
|
||||||
|
a2nClient, _ := a2n.NewClient(&a2n.ClientConfig{
|
||||||
|
A2AClient: a2aClient,
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// 创建群组
|
||||||
|
group, _ := a2nClient.CreateGroup(ctx, "协作组", types.GroupTopologyStar, nil, []types.AgentEndpoint{
|
||||||
|
{AgentID: "member-1", Endpoint: "http://member-1:8080"},
|
||||||
|
{AgentID: "member-2", Endpoint: "http://member-2:8080"},
|
||||||
|
})
|
||||||
|
|
||||||
|
fmt.Printf("Group ID: %s\n", group.GroupID)
|
||||||
|
|
||||||
|
// 提交任务
|
||||||
|
subtasks, _ := a2nClient.SubmitGroupTask(ctx, group.GroupID, "video_generation",
|
||||||
|
map[string]any{"script": "..."},
|
||||||
|
types.MergeAllSuccess,
|
||||||
|
)
|
||||||
|
|
||||||
|
fmt.Printf("Split into %d subtasks\n", len(subtasks))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 协议与包名对应关系
|
||||||
|
|
||||||
|
| 协议名称 | 协议文档 | SDK 包名 | 包路径 |
|
||||||
|
|---------|---------|---------|--------|
|
||||||
|
| 灵隙原始协议(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/` |
|
||||||
|
|
||||||
|
**所有协议版本:1.0.0**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 扩展建议
|
||||||
|
|
||||||
|
| 优先级 | 扩展项 | 说明 |
|
||||||
|
|-------|-------|------|
|
||||||
|
| 高 | gRPC 传输 | 添加 gRPC 协议支持 |
|
||||||
|
| 高 | WebSocket | 添加 WebSocket 流式传输 |
|
||||||
|
| 中 | 批量操作 | 批量任务提交、批量查询 |
|
||||||
|
| 中 | 指标监控 | 内置指标收集 |
|
||||||
|
| 低 | 多语言 SDK | Python、JavaScript 等 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 附录:相关文件索引
|
||||||
|
|
||||||
|
| 文件路径 | 说明 |
|
||||||
|
|---------|------|
|
||||||
|
| [sdk/doc.go](../sdk/doc.go) | SDK 包文档 |
|
||||||
|
| [sdk/p2a/client.go](../sdk/p2a/client.go) | P2A 客户端实现 |
|
||||||
|
| [sdk/a2a/client.go](../sdk/a2a/client.go) | A2A 客户端实现 |
|
||||||
|
| [sdk/a2n/client.go](../sdk/a2n/client.go) | A2N 客户端实现 |
|
||||||
|
| [externalapi/handler.go](../externalapi/handler.go) | P2A 协议服务端实现 |
|
||||||
|
| [p2p/protocol.go](../p2p/protocol.go) | A2A 协议核心实现 |
|
||||||
|
| [group/protocol.go](../group/protocol.go) | A2N 协议核心实现 |
|
||||||
|
| [types/types.go](../types/types.go) | 公共类型定义 |
|
||||||
|
| [transport/transport.go](../transport/transport.go) | HTTP 传输层实现 |
|
||||||
1307
docs/v0/06-implementation-details.md
Normal file
1307
docs/v0/06-implementation-details.md
Normal file
File diff suppressed because it is too large
Load Diff
777
docs/v0/06-solutions-whitepaper.md
Normal file
777
docs/v0/06-solutions-whitepaper.md
Normal file
@@ -0,0 +1,777 @@
|
|||||||
|
# 灵隙协议族(Synapse Protocol Suite) - 解决方案白皮书
|
||||||
|
|
||||||
|
> 版本:1.0.0
|
||||||
|
> 日期:2026-06-27
|
||||||
|
> 状态:草案
|
||||||
|
> 前置阅读:[灵隙原始协议(Synapse Raw Protocol)](./01-synapse-raw-protocol.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 目录
|
||||||
|
|
||||||
|
1. [概述](#1-概述)
|
||||||
|
2. [方案一:Agent 发现与广播机制](#2-方案一agent-发现与广播机制)
|
||||||
|
3. [方案二:身份认证与信任体系](#3-方案二身份认证与信任体系)
|
||||||
|
4. [方案三:协议缺失内容补全](#4-方案三协议缺失内容补全)
|
||||||
|
5. [分阶段实施路线图](#5-分阶段实施路线图)
|
||||||
|
6. [技术选型建议](#6-技术选型建议)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 概述
|
||||||
|
|
||||||
|
### 1.1 背景
|
||||||
|
|
||||||
|
当前灵隙协议族(Synapse Protocol Suite)定义了 Agent 之间"怎么说话"(消息格式、任务流程),但缺少:
|
||||||
|
|
||||||
|
- **怎么找到对方** — Agent 发现与广播机制
|
||||||
|
- **怎么相信对方** — 身份认证与信任体系
|
||||||
|
- **怎么规模化协作** — 路由、调度、激励等基础设施
|
||||||
|
|
||||||
|
本文档针对上述问题给出完整的解决方案。
|
||||||
|
|
||||||
|
### 1.2 设计原则
|
||||||
|
|
||||||
|
| 原则 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| **渐进式** | 从简单到复杂,每阶段都可用 |
|
||||||
|
| **可插拔** | 组件可替换,不绑定具体实现 |
|
||||||
|
| **传输无关** | 不依赖特定底层网络 |
|
||||||
|
| **安全优先** | 身份认证是基础设施,不是可选功能 |
|
||||||
|
| **向后兼容** | 不破坏现有协议,增量扩展 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 方案一:Agent 发现与广播机制
|
||||||
|
|
||||||
|
### 2.1 整体架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────────────┐
|
||||||
|
│ Agent 发现与广播层 │
|
||||||
|
├─────────────────────┬─────────────────────┬─────────────────────────┤
|
||||||
|
│ 集中式目录服务 │ 分布式 Gossip │ 组播/广播 │
|
||||||
|
│ (Directory) │ (Gossip) │ (Multicast) │
|
||||||
|
│ ┌───────────────┐ │ ┌───────────────┐ │ ┌────────────────┐ │
|
||||||
|
│ │ 注册/注销 │ │ │ 消息泛洪 │ │ │ 子网内广播 │ │
|
||||||
|
│ │ 能力索引 │ │ │ 状态同步 │ │ │ 邻居发现 │ │
|
||||||
|
│ │ 名字解析 │ │ │ 节点发现 │ │ │ 本地心跳 │ │
|
||||||
|
│ └───────────────┘ │ └───────────────┘ │ └────────────────┘ │
|
||||||
|
└─────────────────────┴─────────────────────┴─────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 模式一:集中式目录服务(推荐首选)
|
||||||
|
|
||||||
|
#### 2.2.1 架构说明
|
||||||
|
|
||||||
|
引入 **Agent Directory Service(ADS)** 作为中心化的 Agent 目录服务,类似 DNS。
|
||||||
|
|
||||||
|
```
|
||||||
|
Agent A ──注册──▶ ┌─────────────┐ ◀──注册── Agent B
|
||||||
|
│ Directory │
|
||||||
|
Agent C ──查询──▶ │ Service │ ◀──心跳── Agent D
|
||||||
|
└─────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
能力索引
|
||||||
|
在线状态
|
||||||
|
端点地址
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.2.2 核心接口
|
||||||
|
|
||||||
|
**注册协议(Agent → Directory):**
|
||||||
|
|
||||||
|
| 操作 | 消息类型 | 说明 |
|
||||||
|
|------|---------|------|
|
||||||
|
| 注册 | `dir:register` | Agent 上线时注册自身信息 |
|
||||||
|
| 注销 | `dir:unregister` | Agent 下线时注销 |
|
||||||
|
| 心跳 | `dir:heartbeat` | 定期上报存活状态 |
|
||||||
|
| 更新能力 | `dir:update_capabilities` | 能力变化时更新 |
|
||||||
|
|
||||||
|
**查询协议(Agent → Directory):**
|
||||||
|
|
||||||
|
| 操作 | 消息类型 | 说明 |
|
||||||
|
|------|---------|------|
|
||||||
|
| 按 ID 查询 | `dir:query_by_id` | 根据 AgentID 查端点 |
|
||||||
|
| 按能力查询 | `dir:query_by_capability` | 找具备某能力的 Agent |
|
||||||
|
| 列表查询 | `dir:list` | 分页列出所有 Agent |
|
||||||
|
| 批量查询 | `dir:batch_query` | 批量查询多个 Agent |
|
||||||
|
|
||||||
|
#### 2.2.3 注册数据结构
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"agent_id": "agent-001",
|
||||||
|
"agent_name": "视频生成Agent",
|
||||||
|
"system_id": "video-system",
|
||||||
|
"endpoint": "https://agent-001.example.com/synapse/callback",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"capabilities": [
|
||||||
|
{
|
||||||
|
"type": "video_generation",
|
||||||
|
"name": "视频生成",
|
||||||
|
"description": "根据脚本生成视频",
|
||||||
|
"max_concurrent": 10,
|
||||||
|
"avg_latency_ms": 5000
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"transports": ["http", "grpc"],
|
||||||
|
"status": "online",
|
||||||
|
"last_heartbeat": "2026-06-27T10:00:00Z",
|
||||||
|
"trust_score": 85,
|
||||||
|
"public_key": "-----BEGIN PUBLIC KEY-----\n..."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.2.4 优缺点
|
||||||
|
|
||||||
|
| 优点 | 缺点 |
|
||||||
|
|------|------|
|
||||||
|
| 查询效率高(O(1)) | 单点故障风险 |
|
||||||
|
| 支持复杂查询(按能力、按系统等) | 中心节点需信任 |
|
||||||
|
| 易于管理和监控 | 扩展性有上限 |
|
||||||
|
| 实现简单 | 存在注册/注销时序问题 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.3 模式二:分布式 Gossip 协议(可选扩展)
|
||||||
|
|
||||||
|
#### 2.3.1 架构说明
|
||||||
|
|
||||||
|
无中心节点,Agent 之间通过 Gossip 协议(epidemic protocol)扩散状态信息,类似比特币网络的节点发现。
|
||||||
|
|
||||||
|
```
|
||||||
|
Agent A ──gossip──▶ Agent B ──gossip──▶ Agent D
|
||||||
|
│ │
|
||||||
|
└──gossip──▶ Agent C ──gossip──▶ Agent E
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.3.2 核心机制
|
||||||
|
|
||||||
|
| 机制 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| **Peer Sampling** | 每个 Agent 维护一个部分视图(partial view) |
|
||||||
|
| **Active Push** | 定期随机选几个节点推送本地状态 |
|
||||||
|
| **Passive Pull** | 收到推送后,有概率回传自身状态 |
|
||||||
|
| **TTL** | 消息有存活跳数,防止无限扩散 |
|
||||||
|
| **Deduplication** | 消息 ID 去重,避免重复处理 |
|
||||||
|
|
||||||
|
#### 2.3.3 Gossip 消息格式
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "gossip:state",
|
||||||
|
"from": "agent-001",
|
||||||
|
"view": [
|
||||||
|
{"agent_id": "agent-002", "endpoint": "...", "capabilities": [...], "timestamp": "..."},
|
||||||
|
{"agent_id": "agent-003", "endpoint": "...", "capabilities": [...], "timestamp": "..."},
|
||||||
|
{"agent_id": "agent-004", "endpoint": "...", "capabilities": [...], "timestamp": "..."}
|
||||||
|
],
|
||||||
|
"ttl": 5,
|
||||||
|
"msg_id": "msg-xxx"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.3.4 优缺点
|
||||||
|
|
||||||
|
| 优点 | 缺点 |
|
||||||
|
|------|------|
|
||||||
|
| 完全去中心化 | 查询效率低(需本地构建视图) |
|
||||||
|
| 容错性强 | 状态最终一致,有延迟 |
|
||||||
|
| 可无限扩展 | 实现复杂度高 |
|
||||||
|
| 无单点故障 | 网络流量大 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.4 模式三:本地组播/邻居发现(局域网场景)
|
||||||
|
|
||||||
|
适用于同一内网/集群内的 Agent 快速发现。
|
||||||
|
|
||||||
|
#### 2.4.1 机制
|
||||||
|
|
||||||
|
| 机制 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| **UDP 组播** | 定期在组播地址发送广播 |
|
||||||
|
| **mDNS/DNS-SD** | 类似 Apple Bonjour 的服务发现 |
|
||||||
|
| **ARP/NDP** | 链路层发现(不推荐) |
|
||||||
|
|
||||||
|
#### 2.4.2 适用场景
|
||||||
|
|
||||||
|
- 边缘计算集群
|
||||||
|
- 同一机房内的 Agent 集群
|
||||||
|
- 本地开发测试环境
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.5 广播机制设计
|
||||||
|
|
||||||
|
#### 2.5.1 广播类型
|
||||||
|
|
||||||
|
| 广播范围 | 消息类型前缀 | 说明 |
|
||||||
|
|---------|-------------|------|
|
||||||
|
| 全网广播 | `global:` | 所有在线 Agent |
|
||||||
|
| 系统广播 | `system:` | 同一 system_id 内 |
|
||||||
|
| 群组广播 | `group:` | 同一群组内(已有) |
|
||||||
|
| 能力组广播 | `cap:` | 具备某能力的 Agent |
|
||||||
|
|
||||||
|
#### 2.5.2 广播实现
|
||||||
|
|
||||||
|
**集中式模式下:**
|
||||||
|
- 由 Directory Service 转发广播消息
|
||||||
|
- 支持按条件过滤(按能力、按系统等)
|
||||||
|
|
||||||
|
**分布式模式下:**
|
||||||
|
- 通过 Gossip 协议泛洪
|
||||||
|
- TTL 控制扩散范围
|
||||||
|
- 消息 ID 去重
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.6 心跳与存活检测
|
||||||
|
|
||||||
|
#### 2.6.1 心跳机制
|
||||||
|
|
||||||
|
```
|
||||||
|
Agent ───heartbeat──▶ Directory
|
||||||
|
(每30秒)
|
||||||
|
|
||||||
|
Directory 判定离线:
|
||||||
|
- 连续 3 次未收到心跳 → 标记为 offline
|
||||||
|
- 离线 24 小时 → 自动注销
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.6.2 主动探测
|
||||||
|
|
||||||
|
```
|
||||||
|
Directory ───ping──▶ Agent
|
||||||
|
◀──pong──
|
||||||
|
```
|
||||||
|
|
||||||
|
用于验证 Agent 是否真的在线(防止心跳伪造)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 方案二:身份认证与信任体系
|
||||||
|
|
||||||
|
### 3.1 三层身份架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────┐
|
||||||
|
│ Layer 3: 信任评分 (Trust Score) │
|
||||||
|
│ 声誉系统、历史行为、第三方评价 │
|
||||||
|
├─────────────────────────────────────────────────┤
|
||||||
|
│ Layer 2: 身份验证 (Authentication) │
|
||||||
|
│ 签名验证、证书校验、DID 验证 │
|
||||||
|
├─────────────────────────────────────────────────┤
|
||||||
|
│ Layer 1: 身份标识 (Identity) │
|
||||||
|
│ AgentID + 公钥 / 证书 / DID │
|
||||||
|
└─────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 Layer 1:身份标识方案
|
||||||
|
|
||||||
|
#### 3.2.1 方案 A:公钥身份(推荐基础版)
|
||||||
|
|
||||||
|
**核心思想**:AgentID = 公钥哈希(类似比特币地址)
|
||||||
|
|
||||||
|
```
|
||||||
|
AgentID = base58(sha256(public_key)[:20])
|
||||||
|
例:agent-1A2B3C4D5E6F...
|
||||||
|
```
|
||||||
|
|
||||||
|
**优点:**
|
||||||
|
- 自包含,不需要中心 CA
|
||||||
|
- 公钥可验证身份
|
||||||
|
- 实现简单
|
||||||
|
|
||||||
|
**缺点:**
|
||||||
|
- 身份无法撤销(私钥泄露 = 身份被盗)
|
||||||
|
- 没有人类可读的名字
|
||||||
|
- 无法关联真实世界身份
|
||||||
|
|
||||||
|
**适用场景**:内部系统、测试环境、信任度要求不高的场景
|
||||||
|
|
||||||
|
#### 3.2.2 方案 B:PKI 证书体系
|
||||||
|
|
||||||
|
**核心思想**:引入 CA(Certificate Authority)颁发证书
|
||||||
|
|
||||||
|
```
|
||||||
|
CA 根证书
|
||||||
|
├── 系统A证书
|
||||||
|
│ ├── Agent-001 证书
|
||||||
|
│ └── Agent-002 证书
|
||||||
|
└── 系统B证书
|
||||||
|
└── Agent-003 证书
|
||||||
|
```
|
||||||
|
|
||||||
|
**优点:**
|
||||||
|
- 成熟的工业标准
|
||||||
|
- 支持证书撤销(CRL/OCSP)
|
||||||
|
- 有层级信任关系
|
||||||
|
|
||||||
|
**缺点:**
|
||||||
|
- 需要信任中心化 CA
|
||||||
|
- 证书管理复杂
|
||||||
|
- 跨 CA 互操作需要桥接
|
||||||
|
|
||||||
|
**适用场景**:企业内部、有明确信任中心的场景
|
||||||
|
|
||||||
|
#### 3.2.3 方案 C:区块链 DID(去中心化身份)
|
||||||
|
|
||||||
|
**核心思想**:身份上链,链上存公钥和属性,类似 W3C DID 标准。
|
||||||
|
|
||||||
|
```
|
||||||
|
链上存储:
|
||||||
|
DID → {
|
||||||
|
"publicKey": "...",
|
||||||
|
"controller": "...",
|
||||||
|
"authentication": [...],
|
||||||
|
"service": [...],
|
||||||
|
"revoked": false,
|
||||||
|
"timestamp": "..."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**三种实现路径:**
|
||||||
|
|
||||||
|
| 路径 | 说明 | 适用场景 |
|
||||||
|
|------|------|---------|
|
||||||
|
| **公链 DID** | 使用以太坊/Solana 等公链 | 开放生态、跨组织协作 |
|
||||||
|
| **联盟链 DID** | 多机构共建联盟链 | 行业联盟、政企合作 |
|
||||||
|
| **私有链 DID** | 单组织内部链 | 企业内部、对性能要求高 |
|
||||||
|
|
||||||
|
**优点:**
|
||||||
|
- 去中心化,无单点故障
|
||||||
|
- 身份可验证、可追溯
|
||||||
|
- 支持跨系统互认
|
||||||
|
- 不可篡改的身份历史
|
||||||
|
|
||||||
|
**缺点:**
|
||||||
|
- 链上操作有延迟
|
||||||
|
- 需要支付 Gas 费(公链)
|
||||||
|
- 实现复杂度高
|
||||||
|
- 隐私保护需额外设计
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.3 Layer 2:身份验证方案
|
||||||
|
|
||||||
|
#### 3.3.1 消息签名验证
|
||||||
|
|
||||||
|
所有灵隙消息必须签名,签名方式:
|
||||||
|
|
||||||
|
```
|
||||||
|
签名内容 = SHA256(message_id + sender + receiver + payload + timestamp)
|
||||||
|
签名 = Sign(private_key, 签名内容)
|
||||||
|
验证 = Verify(public_key, 签名内容, 签名)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3.3.2 签名放置位置
|
||||||
|
|
||||||
|
| 位置 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 消息体内 | `signature` 字段 |
|
||||||
|
| HTTP Header | `X-Synapse-Signature` |
|
||||||
|
| gRPC Metadata | `x-synapse-signature` |
|
||||||
|
|
||||||
|
#### 3.3.3 防重放攻击
|
||||||
|
|
||||||
|
```
|
||||||
|
每个消息有唯一 message_id + timestamp
|
||||||
|
接收方维护已处理 message_id 缓存(如最近 1 小时)
|
||||||
|
timestamp 与本地时间差超过 5 分钟 → 拒绝
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.4 Layer 3:信任评分体系
|
||||||
|
|
||||||
|
#### 3.4.1 信任分维度
|
||||||
|
|
||||||
|
| 维度 | 权重 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| 任务完成率 | 30% | 历史任务成功 / 总任务数 |
|
||||||
|
| 任务质量 | 25% | 结果评分、返工率 |
|
||||||
|
| 响应速度 | 15% | 平均响应时间 |
|
||||||
|
| 在线稳定性 | 15% | 在线时长 / 总时长 |
|
||||||
|
| 历史信誉 | 15% | 其他 Agent 的评价 |
|
||||||
|
|
||||||
|
#### 3.4.2 信任分计算
|
||||||
|
|
||||||
|
```
|
||||||
|
trust_score = Σ(维度_i × 权重_i)
|
||||||
|
|
||||||
|
范围:0 - 100
|
||||||
|
等级:
|
||||||
|
90-100 S 级 高度可信
|
||||||
|
75-89 A 级 可信
|
||||||
|
60-74 B 级 一般可信
|
||||||
|
40-59 C 级 谨慎使用
|
||||||
|
0-39 D 级 不可信
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3.4.3 信任传递
|
||||||
|
|
||||||
|
```
|
||||||
|
A 信任 B(评分 90)
|
||||||
|
B 信任 C(评分 85)
|
||||||
|
A 对 C 的初始信任 = 90 × 85% × 衰减因子 = 约 68
|
||||||
|
```
|
||||||
|
|
||||||
|
**注意**:信任传递有衰减,防止信任污染。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.5 区块链适用性决策树
|
||||||
|
|
||||||
|
```
|
||||||
|
是否需要跨组织协作?
|
||||||
|
├── 否 → 用 PKI 或公钥身份(简单高效)
|
||||||
|
└── 是 → 是否有共同信任的中心机构?
|
||||||
|
├── 是 → 用 PKI 体系(成熟可靠)
|
||||||
|
└── 否 → 是否需要不可篡改的审计?
|
||||||
|
├── 是 → 考虑联盟链 DID
|
||||||
|
└── 否 → 公钥身份 + 声誉系统可能够用
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 方案三:协议缺失内容补全
|
||||||
|
|
||||||
|
### 4.1 第一优先级补全(核心基础设施)
|
||||||
|
|
||||||
|
#### 4.1.1 Agent 发现协议(ADS - Agent Discovery Service)
|
||||||
|
|
||||||
|
**新增消息类型:**
|
||||||
|
|
||||||
|
| 消息类型 | 方向 | 说明 |
|
||||||
|
|---------|------|------|
|
||||||
|
| `dir:register` | Agent → Directory | 注册 Agent |
|
||||||
|
| `dir:unregister` | Agent → Directory | 注销 Agent |
|
||||||
|
| `dir:heartbeat` | Agent → Directory | 心跳 |
|
||||||
|
| `dir:update_capabilities` | Agent → Directory | 更新能力 |
|
||||||
|
| `dir:query_by_id` | Agent → Directory | 按 ID 查询 |
|
||||||
|
| `dir:query_by_capability` | Agent → Directory | 按能力查询 |
|
||||||
|
| `dir:list` | Agent → Directory | 列表查询 |
|
||||||
|
| `dir:query_result` | Directory → Agent | 查询结果 |
|
||||||
|
|
||||||
|
**新增数据结构:** `AgentDirectoryEntry`, `CapabilityIndex`, `QueryFilter`
|
||||||
|
|
||||||
|
#### 4.1.2 身份认证规范
|
||||||
|
|
||||||
|
**新增消息类型:**
|
||||||
|
|
||||||
|
| 消息类型 | 说明 |
|
||||||
|
|---------|------|
|
||||||
|
| `auth:challenge` | 身份挑战 |
|
||||||
|
| `auth:response` | 挑战响应 |
|
||||||
|
| `auth:cert_exchange` | 证书交换 |
|
||||||
|
|
||||||
|
**新增内容:**
|
||||||
|
- 标准签名算法列表(Ed25519, ECDSA P-256, RSA 2048)
|
||||||
|
- 消息签名格式规范
|
||||||
|
- 防重放攻击机制
|
||||||
|
- 身份验证流程规范
|
||||||
|
|
||||||
|
#### 4.1.3 心跳与存活检测
|
||||||
|
|
||||||
|
**新增消息类型:**
|
||||||
|
|
||||||
|
| 消息类型 | 说明 |
|
||||||
|
|---------|------|
|
||||||
|
| `net:ping` | 存活探测 |
|
||||||
|
| `net:pong` | 存活响应 |
|
||||||
|
| `net:offline_notify` | 下线通知 |
|
||||||
|
|
||||||
|
**规范内容:**
|
||||||
|
- 心跳间隔(默认 30 秒)
|
||||||
|
- 超时判定(连续 3 次未收到 → 离线)
|
||||||
|
- 离线通知机制
|
||||||
|
|
||||||
|
#### 4.1.4 统一错误码体系
|
||||||
|
|
||||||
|
**错误分类:**
|
||||||
|
|
||||||
|
| 错误码前缀 | 类别 | 示例 |
|
||||||
|
|-----------|------|------|
|
||||||
|
| `msg_` | 消息层 | msg_invalid_format, msg_signature_invalid |
|
||||||
|
| `auth_` | 认证层 | auth_failed, auth_expired, auth_forbidden |
|
||||||
|
| `task_` | 任务层 | task_not_found, task_timeout, task_cancelled |
|
||||||
|
| `cap_` | 能力层 | cap_lacking, cap_busy, cap_not_supported |
|
||||||
|
| `group_` | 群组层 | group_not_found, group_full, group_permission_denied |
|
||||||
|
| `dir_` | 目录层 | dir_agent_not_found, dir_query_failed |
|
||||||
|
| `net_` | 网络层 | net_timeout, net_offline, net_unreachable |
|
||||||
|
| `sys_` | 系统层 | sys_internal_error, sys_not_implemented |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.2 第二优先级补全(重要功能)
|
||||||
|
|
||||||
|
#### 4.2.1 能力匹配与任务路由
|
||||||
|
|
||||||
|
**功能:**
|
||||||
|
- 智能选择最合适的 Agent 执行任务
|
||||||
|
- 支持负载均衡(按并发数、响应速度、信任分)
|
||||||
|
- 支持任务失败自动重试/转发
|
||||||
|
|
||||||
|
**新增消息类型:**
|
||||||
|
- `router:submit_task` - 提交给路由器自动选择执行者
|
||||||
|
- `router:forward` - 任务转发
|
||||||
|
|
||||||
|
#### 4.2.2 全网广播协议
|
||||||
|
|
||||||
|
**新增消息类型:**
|
||||||
|
|
||||||
|
| 消息类型 | 说明 |
|
||||||
|
|---------|------|
|
||||||
|
| `global:broadcast` | 全网广播 |
|
||||||
|
| `system:broadcast` | 系统内广播 |
|
||||||
|
| `cap:broadcast` | 能力组广播 |
|
||||||
|
|
||||||
|
**规范内容:**
|
||||||
|
- 广播范围定义
|
||||||
|
- TTL 与去重机制
|
||||||
|
- 广播风暴防护
|
||||||
|
|
||||||
|
#### 4.2.3 版本协商机制
|
||||||
|
|
||||||
|
**功能:**
|
||||||
|
- Agent 之间协商使用的协议版本
|
||||||
|
- 向后兼容处理
|
||||||
|
- 能力降级策略
|
||||||
|
|
||||||
|
**新增消息类型:**
|
||||||
|
- `meta:version_query` - 查询支持的版本
|
||||||
|
- `meta:version_negotiate` - 版本协商
|
||||||
|
|
||||||
|
#### 4.2.4 幂等性保证
|
||||||
|
|
||||||
|
**规范内容:**
|
||||||
|
- 幂等键(Idempotency Key)机制
|
||||||
|
- 重复消息处理规范
|
||||||
|
- 任务级幂等 vs 消息级幂等
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.3 第三优先级补全(增强功能)
|
||||||
|
|
||||||
|
#### 4.3.1 流式输出协议
|
||||||
|
|
||||||
|
**功能:**
|
||||||
|
- 长任务实时进度推送
|
||||||
|
- 生成式 AI 的 token 流式输出
|
||||||
|
- WebSocket/SSE 传输支持
|
||||||
|
|
||||||
|
#### 4.3.2 批量任务协议
|
||||||
|
|
||||||
|
**功能:**
|
||||||
|
- 一次性提交多个同类型任务
|
||||||
|
- 批量状态查询
|
||||||
|
- 批量结果收集
|
||||||
|
|
||||||
|
#### 4.3.3 支付与激励机制
|
||||||
|
|
||||||
|
**功能:**
|
||||||
|
- 任务定价与结算
|
||||||
|
- Token 或积分系统
|
||||||
|
- 智能合约自动结算(区块链场景)
|
||||||
|
|
||||||
|
#### 4.3.4 群组发现协议
|
||||||
|
|
||||||
|
**功能:**
|
||||||
|
- 按主题/任务类型查找群组
|
||||||
|
- 推荐加入合适的群组
|
||||||
|
- 群组热度/活跃度排名
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.4 安全相关补全
|
||||||
|
|
||||||
|
#### 4.4.1 端到端加密
|
||||||
|
|
||||||
|
**规范内容:**
|
||||||
|
- 密钥协商(ECDH)
|
||||||
|
- 对称加密载荷(AES-GCM)
|
||||||
|
- 前向保密(PFS)
|
||||||
|
|
||||||
|
#### 4.4.2 权限委托
|
||||||
|
|
||||||
|
**功能:**
|
||||||
|
- Agent A 委托 Agent B 代表自己执行任务
|
||||||
|
- 委托令牌(Delegation Token)
|
||||||
|
- 委托范围与时效控制
|
||||||
|
|
||||||
|
#### 4.4.3 审计日志标准
|
||||||
|
|
||||||
|
**规范内容:**
|
||||||
|
- 统一审计日志格式
|
||||||
|
- 关键操作必须记录
|
||||||
|
- 日志完整性保护(哈希链)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 分阶段实施路线图
|
||||||
|
|
||||||
|
### 5.1 Phase 0:基础版(MVP) - 预计 2 周
|
||||||
|
|
||||||
|
**目标**:协议可用,能跑通基本流程
|
||||||
|
|
||||||
|
**内容:**
|
||||||
|
- [x] 灵隙点对点任务协议(已完成)
|
||||||
|
- [x] A2N 群组协作协议(已完成)
|
||||||
|
- [x] P2A 外部调用协议(已完成)
|
||||||
|
- [x] 三套协议的 SDK 实现(已完成)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.2 Phase 1:发现与身份 - 预计 4 周
|
||||||
|
|
||||||
|
**目标**:Agent 能互相找到对方,能验证对方身份
|
||||||
|
|
||||||
|
**新增协议模块:**
|
||||||
|
|
||||||
|
| 模块 | 说明 | 优先级 |
|
||||||
|
|------|------|--------|
|
||||||
|
| Agent 目录服务协议 | 集中式 ADS | P0 |
|
||||||
|
| 公钥身份规范 | Ed25519 签名验证 | P0 |
|
||||||
|
| 心跳与存活检测 | 30 秒心跳,3 次超时判定离线 | P0 |
|
||||||
|
| 统一错误码体系 | 8 大类错误码 | P0 |
|
||||||
|
| 防重放攻击 | message_id + timestamp | P0 |
|
||||||
|
|
||||||
|
**输出物:**
|
||||||
|
- 新协议文档:`06-agent-discovery.md`
|
||||||
|
- 新协议文档:`07-authentication.md`
|
||||||
|
- 代码:`discovery/` 包(目录服务客户端)
|
||||||
|
- 代码:`auth/` 包(签名验证工具)
|
||||||
|
- 更新 types 包:新增消息类型和错误码
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.3 Phase 2:路由与广播 - 预计 4 周
|
||||||
|
|
||||||
|
**目标**:支持智能任务路由和全网广播
|
||||||
|
|
||||||
|
**新增协议模块:**
|
||||||
|
|
||||||
|
| 模块 | 说明 | 优先级 |
|
||||||
|
|------|------|--------|
|
||||||
|
| 任务路由协议 | 按能力 + 负载 + 信任分选择执行者 | P1 |
|
||||||
|
| 全网广播协议 | 基于目录服务的广播转发 | P1 |
|
||||||
|
| 版本协商机制 | 协议版本兼容 | P1 |
|
||||||
|
| 幂等性保证 | 幂等键 + 去重 | P1 |
|
||||||
|
|
||||||
|
**输出物:**
|
||||||
|
- 新协议文档:`08-routing-and-broadcast.md`
|
||||||
|
- 代码:`routing/` 包增强(增加能力路由)
|
||||||
|
- 更新目录服务:支持广播转发
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.4 Phase 3:信任与激励 - 预计 6 周
|
||||||
|
|
||||||
|
**目标**:建立信任体系,支持规模化协作
|
||||||
|
|
||||||
|
**新增协议模块:**
|
||||||
|
|
||||||
|
| 模块 | 说明 | 优先级 |
|
||||||
|
|------|------|--------|
|
||||||
|
| 信任评分体系 | 5 维度信任分计算 | P2 |
|
||||||
|
| 流式输出协议 | WebSocket/SSE 流式进度 | P2 |
|
||||||
|
| 批量任务协议 | 批量提交/查询/收集 | P2 |
|
||||||
|
| 群组发现协议 | 群组搜索与推荐 | P2 |
|
||||||
|
| SLA 协议 | 服务等级承诺 | P3 |
|
||||||
|
|
||||||
|
**输出物:**
|
||||||
|
- 新协议文档:`09-trust-and-reputation.md`
|
||||||
|
- 代码:`trust/` 包(信任评分引擎)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.5 Phase 4:高级特性 - 预计 8 周+
|
||||||
|
|
||||||
|
**目标**:企业级、生产级完整功能
|
||||||
|
|
||||||
|
**新增协议模块:**
|
||||||
|
|
||||||
|
| 模块 | 说明 | 优先级 |
|
||||||
|
|------|------|--------|
|
||||||
|
| 端到端加密 | ECDH + AES-GCM | P3 |
|
||||||
|
| 权限委托 | 委托令牌机制 | P3 |
|
||||||
|
| 支付与激励 | Token/积分系统 | P3 |
|
||||||
|
| 区块链 DID 集成 | 可选模块 | P4 |
|
||||||
|
| 审计日志标准 | 统一审计格式 | P3 |
|
||||||
|
| Gossip 协议 | 分布式发现(可选) | P4 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 技术选型建议
|
||||||
|
|
||||||
|
### 6.1 目录服务存储选型
|
||||||
|
|
||||||
|
| 方案 | 适用场景 | 优点 | 缺点 |
|
||||||
|
|------|---------|------|------|
|
||||||
|
| **Redis** | 中小规模 | 高性能,支持 TTL | 数据量受限 |
|
||||||
|
| **PostgreSQL** | 中大规模 | 复杂查询,持久化 | 需运维 |
|
||||||
|
| **Elasticsearch** | 大规模 + 全文检索 | 强大的搜索能力 | 运维复杂 |
|
||||||
|
|
||||||
|
**推荐**:先用 Redis(简单快),规模大了再迁 PostgreSQL。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 6.2 签名算法选型
|
||||||
|
|
||||||
|
| 算法 | 安全性 | 性能 | 密钥长度 | 推荐度 |
|
||||||
|
|------|--------|------|---------|--------|
|
||||||
|
| Ed25519 | 高 | 快 | 256 位 | ⭐⭐⭐⭐⭐ 首选 |
|
||||||
|
| ECDSA P-256 | 高 | 中 | 256 位 | ⭐⭐⭐⭐ 兼容 |
|
||||||
|
| RSA 2048 | 中 | 慢 | 2048 位 | ⭐⭐ 仅兼容 |
|
||||||
|
|
||||||
|
**推荐**:默认 Ed25519,需要兼容旧系统时支持 ECDSA。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 6.3 区块链选型(如果需要)
|
||||||
|
|
||||||
|
| 场景 | 推荐方案 | 说明 |
|
||||||
|
|------|---------|------|
|
||||||
|
| 企业内部 | **私有链(Hyperledger Fabric)** | 可控,高性能,无 Gas 费 |
|
||||||
|
| 行业联盟 | **联盟链(FISCO BCOS / ChainMaker)** | 多机构共建,合规 |
|
||||||
|
| 开放生态 | **公链(以太坊 / Solana)** | 完全开放,需 Gas 费 |
|
||||||
|
| 简单原型 | **模拟链(数据库模拟)** | 先验证逻辑,再上真链 |
|
||||||
|
|
||||||
|
**推荐**:90% 的场景用不到真区块链,先用数据库模拟验证业务逻辑。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 总结与建议
|
||||||
|
|
||||||
|
### 7.1 核心建议
|
||||||
|
|
||||||
|
1. **先集中后分布**:先用集中式目录服务,简单高效;规模大了再考虑分布式
|
||||||
|
2. **先公钥后区块链**:先用公钥身份解决 80% 的问题,真的需要了再上链
|
||||||
|
3. **先 MVP 后完善**:先跑通核心流程,再逐步加高级功能
|
||||||
|
4. **标准接口可替换**:目录服务、身份系统都做成可插拔的,方便未来升级
|
||||||
|
|
||||||
|
### 7.2 下一步行动
|
||||||
|
|
||||||
|
| 序号 | 行动 | 负责人 | 产出 |
|
||||||
|
|------|------|--------|------|
|
||||||
|
| 1 | 评审本方案,确认 Phase 1 范围 | 架构组 | 确认后的方案 |
|
||||||
|
| 2 | 设计目录服务 API 详细规范 | 协议组 | `06-agent-discovery.md` |
|
||||||
|
| 3 | 设计身份认证详细规范 | 协议组 | `07-authentication.md` |
|
||||||
|
| 4 | 实现目录服务原型 | 开发组 | 可运行的 ADS 服务 |
|
||||||
|
| 5 | 更新 SDK 支持发现和认证 | 开发组 | 新版 SDK |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 附录:相关文档索引
|
||||||
|
|
||||||
|
| 文档 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| [01-synapse-raw-protocol.md](./01-synapse-raw-protocol.md) | 灵隙原始协议(Synapse Raw Protocol)(纲领) |
|
||||||
|
| [02-a2a-protocol.md](./02-a2a-protocol.md) | A2A 协议(P2P 任务) |
|
||||||
|
| [03-a2n-protocol.md](./03-a2n-protocol.md) | A2N 协议(群组协作) |
|
||||||
|
| [04-p2a-protocol.md](./04-p2a-protocol.md) | P2A 协议(外部调用) |
|
||||||
|
| [05-sdk-implementation.md](./05-sdk-implementation.md) | SDK 实现说明 |
|
||||||
|
| **本文档** | **解决方案白皮书** |
|
||||||
113
docs/v1/00-index.md
Normal file
113
docs/v1/00-index.md
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
# 灵隙 Synapse 协议栈 v1
|
||||||
|
|
||||||
|
> 版本:1.0.0
|
||||||
|
> 更新日期:2026-06-27
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 协议结构
|
||||||
|
|
||||||
|
本版本协议按抽象层设计,只定义"实现什么功能"和"数据格式",不涉及具体实现细节。
|
||||||
|
|
||||||
|
```
|
||||||
|
docs/v1/
|
||||||
|
├── 00-index.md # 本文件(协议索引)
|
||||||
|
├── 01-raw-protocol.md # 原始协议(基础层)
|
||||||
|
├── 02-a2a-protocol.md # A2A 协议(点对点)
|
||||||
|
├── 03-a2n-protocol.md # A2N 协议(群组协作)
|
||||||
|
└── 04-p2a-protocol.md # P2A 协议(外部调用)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 协议概览
|
||||||
|
|
||||||
|
### 层级关系
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────┐
|
||||||
|
│ P2A 协议(外部调用入口) │
|
||||||
|
│ 04-p2a-protocol.md │
|
||||||
|
└─────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
│ 封装
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────┐
|
||||||
|
│ A2A 协议(点对点任务协作) │
|
||||||
|
│ 02-a2a-protocol.md │
|
||||||
|
└─────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
│ 复用单播
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────┐
|
||||||
|
│ A2N 协议(群组协作) │
|
||||||
|
│ 03-a2n-protocol.md │
|
||||||
|
└─────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
│ 继承
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────┐
|
||||||
|
│ 原始协议(公共基础) │
|
||||||
|
│ 01-raw-protocol.md │
|
||||||
|
│ - 统一消息信封 │
|
||||||
|
│ - 身份标识 │
|
||||||
|
│ - 签名机制 │
|
||||||
|
│ - 时间格式 │
|
||||||
|
└─────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 协议对比
|
||||||
|
|
||||||
|
| 协议 | 代号 | 参与方 | 核心功能 |
|
||||||
|
|------|------|--------|---------|
|
||||||
|
| 原始协议 | Raw | - | 消息信封、身份、签名 |
|
||||||
|
| A2A 协议 | P2P | Agent ↔ Agent | 任务提交、进度同步、信息补全、HiL |
|
||||||
|
| A2N 协议 | Group | 1 Coordinator + N Worker | 群组管理、任务拆分合并、投票共识 |
|
||||||
|
| P2A 协议 | Caller | 外部 → Agent | REST API、回调/轮询 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 消息类型前缀
|
||||||
|
|
||||||
|
| 前缀 | 协议 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `p2p:` | A2A | 点对点消息(17 种) |
|
||||||
|
| `group:` | A2N | 群组内消息(20+ 种) |
|
||||||
|
| `inter_group:` | A2N | 跨群组消息(升级) |
|
||||||
|
| `caller:` | P2A | 外部调用消息(内部转换) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 与 v0 版本的差异
|
||||||
|
|
||||||
|
| 对比项 | v0 版本 | v1 版本 |
|
||||||
|
|--------|---------|---------|
|
||||||
|
| 内容定位 | 混合抽象层和实现层 | 纯抽象层 |
|
||||||
|
| 数据格式 | 嵌入大量 JSON 示例 | 表格化字段定义 |
|
||||||
|
| 实现细节 | 包含 Go struct、算法实现 | 仅定义接口要求 |
|
||||||
|
| 七大组件 | 无协议规范 | 待补充独立文档 |
|
||||||
|
| 文件数量 | 8 个 | 4 个核心协议 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 后续补充
|
||||||
|
|
||||||
|
以下内容待补充为独立实现文档(不属于协议抽象层):
|
||||||
|
|
||||||
|
- 七大组件详细规范(灵脉、灵玺、灵鉴、灵泊、灵瞰、灵衡、灵枢)
|
||||||
|
- 内容类型系统(TextContent、FileContent 等)
|
||||||
|
- 能力声明系统
|
||||||
|
- gRPC 传输协议
|
||||||
|
- HiL 三级升级机制
|
||||||
|
- 数字分段错误码完整定义
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 版本历史
|
||||||
|
|
||||||
|
| 版本 | 日期 | 变更说明 |
|
||||||
|
|------|------|---------|
|
||||||
|
| v1.0.0 | 2026-06-27 | 重构为抽象层协议,分离实现细节 |
|
||||||
|
| v0.x | 2026-06-27 | 初始版本(混合抽象层与实现层) |
|
||||||
160
docs/v1/01-raw-protocol.md
Normal file
160
docs/v1/01-raw-protocol.md
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
# 灵隙原始协议(Synapse Raw Protocol)
|
||||||
|
|
||||||
|
> 版本:1.0.0
|
||||||
|
> 状态:规范
|
||||||
|
> 层级:基础层
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 定位
|
||||||
|
|
||||||
|
原始协议定义灵隙协议栈的公共基础,为所有子协议(A2A、A2N、P2A)提供统一的消息信封、身份标识、时间格式和签名机制。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 功能定义
|
||||||
|
|
||||||
|
### 2.1 核心功能
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 统一消息信封 | 所有协议共用的消息格式 |
|
||||||
|
| 身份标识 | Agent 端点定义 |
|
||||||
|
| 时间戳 | 统一时间格式(RFC3339) |
|
||||||
|
| 消息签名 | HMAC 签名验证机制 |
|
||||||
|
| 关联机制 | correlation_id / reply_to 消息关联 |
|
||||||
|
| 协议版本 | 版本标识与兼容性 |
|
||||||
|
|
||||||
|
### 2.2 扩展功能
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 会话关联 | conversation_id 多轮对话关联 |
|
||||||
|
| 消息存活 | TTL 消息过期机制 |
|
||||||
|
| 广播标识 | broadcast 广播消息标记 |
|
||||||
|
| 加密标识 | encrypt 消息加密标记 |
|
||||||
|
| 签名算法 | signature_algorithm 签名算法声明 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 数据格式定义
|
||||||
|
|
||||||
|
### 3.1 统一消息信封
|
||||||
|
|
||||||
|
所有协议消息必须使用统一信封格式:
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `id` | string | ✓ | 消息唯一标识(UUID) |
|
||||||
|
| `version` | string | ✓ | 协议版本(如 "1.0.0") |
|
||||||
|
| `type` | string | ✓ | 消息类型(格式:`协议:类型`,如 `p2p:task_request`) |
|
||||||
|
| `sender` | AgentEndpoint | ✓ | 发送方端点 |
|
||||||
|
| `receiver` | AgentEndpoint | - | 接收方端点(广播时可为空) |
|
||||||
|
| `payload` | object | ✓ | 消息载荷(具体结构由消息类型定义) |
|
||||||
|
| `timestamp` | string | ✓ | 时间戳(RFC3339 格式) |
|
||||||
|
|
||||||
|
### 3.2 关联字段
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `correlation_id` | string | - | 关联 ID(用于请求-响应关联) |
|
||||||
|
| `reply_to` | string | - | 回复的消息 ID |
|
||||||
|
| `group_id` | string | - | 群组 ID(群组消息必填) |
|
||||||
|
|
||||||
|
### 3.3 安全字段
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `signature` | string | - | HMAC 签名(签名算法由 signature_algorithm 指定) |
|
||||||
|
| `signature_algorithm` | string | - | 签名算法(默认 "HMAC-SHA256") |
|
||||||
|
|
||||||
|
### 3.4 扩展字段
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `conversation_id` | string | 会话 ID(多轮对话关联) |
|
||||||
|
| `ttl` | integer | 消息存活时间(秒) |
|
||||||
|
| `broadcast` | boolean | 是否广播消息 |
|
||||||
|
| `encrypt` | boolean | payload 是否加密 |
|
||||||
|
|
||||||
|
### 3.5 Agent 端点
|
||||||
|
|
||||||
|
Agent 身份标识结构:
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `agent_id` | string | ✓ | Agent 唯一标识 |
|
||||||
|
| `agent_name` | string | - | Agent 名称 |
|
||||||
|
| `system_id` | string | ✓ | 所属系统标识 |
|
||||||
|
| `endpoint` | string | ✓ | 回调端点 URL |
|
||||||
|
| `version` | string | - | Agent 版本 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 签名机制
|
||||||
|
|
||||||
|
### 4.1 签名算法
|
||||||
|
|
||||||
|
支持算法:
|
||||||
|
- `HMAC-SHA256`(默认)
|
||||||
|
- `HMAC-SHA512`
|
||||||
|
|
||||||
|
### 4.2 签名内容
|
||||||
|
|
||||||
|
签名内容为以下字段的拼接(UTF-8 编码):
|
||||||
|
|
||||||
|
```
|
||||||
|
signature_content = sender_id | receiver_id | timestamp | payload_json
|
||||||
|
```
|
||||||
|
|
||||||
|
分隔符:`|`(竖线)
|
||||||
|
|
||||||
|
### 4.3 签名验证
|
||||||
|
|
||||||
|
接收方必须:
|
||||||
|
1. 提取 sender 的认证密钥
|
||||||
|
2. 使用相同算法重新计算签名
|
||||||
|
3. 比对签名是否一致
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 协议类型前缀
|
||||||
|
|
||||||
|
| 前缀 | 协议 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `p2p:` | A2A 协议 | 点对点消息 |
|
||||||
|
| `group:` | A2N 协议 | 群组内消息 |
|
||||||
|
| `inter_group:` | A2N 协议 | 跨群组消息 |
|
||||||
|
| `caller:` | P2A 协议 | 外部调用消息 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 消息类型命名规范
|
||||||
|
|
||||||
|
格式:`协议前缀:消息类型`
|
||||||
|
|
||||||
|
示例:
|
||||||
|
- `p2p:task_request` - A2A 协议的任务请求
|
||||||
|
- `group:vote` - A2N 协议的投票消息
|
||||||
|
- `inter_group:escalate` - A2N 协议的跨群组升级
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 时间格式
|
||||||
|
|
||||||
|
所有时间字段使用 RFC3339 格式:
|
||||||
|
|
||||||
|
```
|
||||||
|
2026-06-27T15:30:00Z
|
||||||
|
2026-06-27T15:30:00+08:00
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 版本兼容性
|
||||||
|
|
||||||
|
- 主版本号变更:不兼容
|
||||||
|
- 次版本号变更:新增功能,向后兼容
|
||||||
|
- 修订号变更:修复问题,完全兼容
|
||||||
|
|
||||||
|
Agent 必须在消息中声明自己使用的版本,接收方据此判断兼容性。
|
||||||
354
docs/v1/02-a2a-protocol.md
Normal file
354
docs/v1/02-a2a-protocol.md
Normal file
@@ -0,0 +1,354 @@
|
|||||||
|
# A2A 协议(Agent-to-Agent Protocol)
|
||||||
|
|
||||||
|
> 版本:1.0.0
|
||||||
|
> 状态:规范
|
||||||
|
> 层级:子协议层
|
||||||
|
> 基于:[灵隙原始协议](01-raw-protocol.md)
|
||||||
|
> 前缀:`p2p:`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 定位
|
||||||
|
|
||||||
|
A2A 协议定义两个 Agent 之间进行点对点任务协作的规范,包括任务提交、进度同步、信息补全、人类介入、能力发现等核心交互。
|
||||||
|
|
||||||
|
**适用场景**:
|
||||||
|
- 单个任务请求与响应
|
||||||
|
- 任务状态实时同步
|
||||||
|
- 任务取消
|
||||||
|
- 信息补全交互
|
||||||
|
- 人类介入决策
|
||||||
|
|
||||||
|
**非适用场景**:
|
||||||
|
- 多 Agent 群组协作(参见 A2N 协议)
|
||||||
|
- 非 Agent 调用方接入(参见 P2A 协议)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 功能定义
|
||||||
|
|
||||||
|
### 2.1 任务管理
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 任务提交 | 请求方向执行方提交任务 |
|
||||||
|
| 任务确认 | 执行方接受任务 |
|
||||||
|
| 任务拒绝 | 执行方拒绝任务(附带原因) |
|
||||||
|
| 任务取消 | 请求方中途取消任务 |
|
||||||
|
| 任务进度 | 执行方实时上报进度 |
|
||||||
|
| 任务完成 | 执行方上报成功结果 |
|
||||||
|
| 任务失败 | 执行方上报失败原因 |
|
||||||
|
|
||||||
|
### 2.2 信息补全
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 信息请求 | 执行方发现缺少必要信息时请求补充 |
|
||||||
|
| 信息提供 | 请求方提供补充信息 |
|
||||||
|
|
||||||
|
### 2.3 人类介入(HiL)
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| HiL 请求 | 执行方请求人类决策 |
|
||||||
|
| HiL 响应 | 请求方返回人类决策结果 |
|
||||||
|
|
||||||
|
### 2.4 能力发现
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 能力查询 | 查询对方支持的任务类型和能力 |
|
||||||
|
| 能力响应 | 返回能力清单 |
|
||||||
|
|
||||||
|
### 2.5 保活与确认
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 心跳 | 双向心跳保活 |
|
||||||
|
| ACK | 任务级确认 |
|
||||||
|
| 消息 ACK | 消息级确认 |
|
||||||
|
| 消息 NACK | 消息级否定确认(附带错误) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 消息类型定义
|
||||||
|
|
||||||
|
所有消息类型前缀:`p2p:`
|
||||||
|
|
||||||
|
### 3.1 任务类消息
|
||||||
|
|
||||||
|
| 消息类型 | 方向 | 说明 |
|
||||||
|
|---------|------|------|
|
||||||
|
| `p2p:task_request` | 请求方 → 执行方 | 提交任务请求 |
|
||||||
|
| `p2p:task_confirm` | 执行方 → 请求方 | 确认接受任务 |
|
||||||
|
| `p2p:task_reject` | 执行方 → 请求方 | 拒绝任务 |
|
||||||
|
| `p2p:task_status_update` | 执行方 → 请求方 | 任务进度更新 |
|
||||||
|
| `p2p:task_complete` | 执行方 → 请求方 | 任务完成 |
|
||||||
|
| `p2p:task_failed` | 执行方 → 请求方 | 任务失败 |
|
||||||
|
| `p2p:task_cancel` | 请求方 → 执行方 | 取消任务 |
|
||||||
|
| `p2p:task_ack` | 双向 | 任务级确认 |
|
||||||
|
|
||||||
|
### 3.2 信息类消息
|
||||||
|
|
||||||
|
| 消息类型 | 方向 | 说明 |
|
||||||
|
|---------|------|------|
|
||||||
|
| `p2p:task_need_info` | 执行方 → 请求方 | 请求补充信息 |
|
||||||
|
| `p2p:task_info_provided` | 请求方 → 执行方 | 提供补充信息 |
|
||||||
|
|
||||||
|
### 3.3 HiL 类消息
|
||||||
|
|
||||||
|
| 消息类型 | 方向 | 说明 |
|
||||||
|
|---------|------|------|
|
||||||
|
| `p2p:task_need_human` | 执行方 → 请求方 | 请求人类介入 |
|
||||||
|
| `p2p:human_decision` | 请求方 → 执行方 | 人类决策结果 |
|
||||||
|
|
||||||
|
### 3.4 能力类消息
|
||||||
|
|
||||||
|
| 消息类型 | 方向 | 说明 |
|
||||||
|
|---------|------|------|
|
||||||
|
| `p2p:capability_query` | 双向 | 查询对方能力 |
|
||||||
|
| `p2p:capability_response` | 双向 | 返回能力清单 |
|
||||||
|
|
||||||
|
### 3.5 保活与确认类消息
|
||||||
|
|
||||||
|
| 消息类型 | 方向 | 说明 |
|
||||||
|
|---------|------|------|
|
||||||
|
| `p2p:heartbeat` | 双向 | 心跳保活 |
|
||||||
|
| `p2p:ack` | 双向 | 通用确认 |
|
||||||
|
| `p2p:nack` | 双向 | 通用否定确认 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 任务状态机
|
||||||
|
|
||||||
|
### 4.1 状态定义
|
||||||
|
|
||||||
|
| 状态 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| `idle` | 空闲(初始状态) |
|
||||||
|
| `pending` | 待确认(已发送请求) |
|
||||||
|
| `confirmed` | 已确认(执行方接受) |
|
||||||
|
| `executing` | 执行中 |
|
||||||
|
| `info_needed` | 需要信息 |
|
||||||
|
| `info_provided` | 信息已提供 |
|
||||||
|
| `need_human` | 需要人类介入 |
|
||||||
|
| `human_deciding` | 人类决策中 |
|
||||||
|
| `human_approved` | 人类已批准 |
|
||||||
|
| `human_rejected` | 人类已拒绝 |
|
||||||
|
| `completed` | 已完成(终态) |
|
||||||
|
| `failed` | 已失败(终态) |
|
||||||
|
| `cancelled` | 已取消(终态) |
|
||||||
|
| `rejected` | 已拒绝(终态) |
|
||||||
|
|
||||||
|
### 4.2 状态流转
|
||||||
|
|
||||||
|
请求方视角:
|
||||||
|
|
||||||
|
```
|
||||||
|
idle → pending → confirmed → executing → completed
|
||||||
|
↓ ↓ → failed
|
||||||
|
rejected info_needed → cancelled
|
||||||
|
↑↓
|
||||||
|
info_provided
|
||||||
|
↓
|
||||||
|
need_human
|
||||||
|
↑↓
|
||||||
|
human_deciding
|
||||||
|
↓
|
||||||
|
human_approved / human_rejected
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 交互流程
|
||||||
|
|
||||||
|
### 5.1 正常任务流程
|
||||||
|
|
||||||
|
```
|
||||||
|
请求方 执行方
|
||||||
|
| |
|
||||||
|
|---- p2p:task_request ------------>| 提交任务
|
||||||
|
| |
|
||||||
|
|<--- p2p:task_confirm -------------| 确认接受
|
||||||
|
| |
|
||||||
|
|<--- p2p:task_status_update (多次) --| 进度更新
|
||||||
|
| |
|
||||||
|
|<--- p2p:task_complete ------------| 完成通知
|
||||||
|
| |
|
||||||
|
|---- p2p:task_ack ---------------->| 确认收到
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 信息补全流程
|
||||||
|
|
||||||
|
```
|
||||||
|
请求方 执行方
|
||||||
|
| |
|
||||||
|
|---- p2p:task_request ------------>|
|
||||||
|
| |
|
||||||
|
|<--- p2p:task_need_info -----------| 发现信息缺失
|
||||||
|
| |
|
||||||
|
|---- p2p:task_info_provided ------->| 补充信息
|
||||||
|
| |
|
||||||
|
|<--- p2p:task_status_update -------| 继续执行
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.3 人类介入流程
|
||||||
|
|
||||||
|
```
|
||||||
|
请求方 执行方
|
||||||
|
| |
|
||||||
|
|---- p2p:task_request ------------>|
|
||||||
|
| |
|
||||||
|
|<--- p2p:task_need_human ----------| 需要人类决策
|
||||||
|
| |
|
||||||
|
| [人类做出决策] |
|
||||||
|
| |
|
||||||
|
|---- p2p:human_decision ---------->| 决策结果
|
||||||
|
| |
|
||||||
|
|<--- p2p:task_status_update -------| 继续执行
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.4 任务取消流程
|
||||||
|
|
||||||
|
```
|
||||||
|
请求方 执行方
|
||||||
|
| |
|
||||||
|
|---- p2p:task_request ------------>|
|
||||||
|
| |
|
||||||
|
|---- p2p:task_cancel ------------->| 取消任务
|
||||||
|
| |
|
||||||
|
|<--- p2p:task_ack -----------------| 确认取消
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.5 任务拒绝流程
|
||||||
|
|
||||||
|
```
|
||||||
|
请求方 执行方
|
||||||
|
| |
|
||||||
|
|---- p2p:task_request ------------>|
|
||||||
|
| |
|
||||||
|
|<--- p2p:task_reject --------------| 拒绝(附带原因)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 载荷结构定义
|
||||||
|
|
||||||
|
### 6.1 task_request 载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `task_id` | string | ✓ | 任务唯一标识(请求方生成) |
|
||||||
|
| `task_type` | string | ✓ | 任务类型 |
|
||||||
|
| `payload` | object | ✓ | 任务参数(结构由 task_type 决定) |
|
||||||
|
| `priority` | string | - | 优先级:`low`/`normal`/`high`/`urgent` |
|
||||||
|
| `transport_preferences` | object | - | 传输偏好(回调/轮询等) |
|
||||||
|
|
||||||
|
### 6.2 task_confirm 载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `task_id` | string | ✓ | 任务标识 |
|
||||||
|
| `estimated_time` | string | - | 预估耗时(如 "30s-2min") |
|
||||||
|
|
||||||
|
### 6.3 task_reject 载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `task_id` | string | ✓ | 任务标识 |
|
||||||
|
| `reason` | object | ✓ | 拒绝原因(含错误码和描述) |
|
||||||
|
|
||||||
|
### 6.4 task_status_update 载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `task_id` | string | ✓ | 任务标识 |
|
||||||
|
| `status` | string | ✓ | 当前状态 |
|
||||||
|
| `progress` | integer | - | 进度百分比(0-100) |
|
||||||
|
| `message` | string | - | 状态说明 |
|
||||||
|
| `eta` | string | - | 预估完成时间 |
|
||||||
|
|
||||||
|
### 6.5 task_complete 载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `task_id` | string | ✓ | 任务标识 |
|
||||||
|
| `result` | object | ✓ | 任务结果(结构由 task_type 决定) |
|
||||||
|
| `summary` | string | - | 结果摘要 |
|
||||||
|
| `metadata` | object | - | 结果元数据 |
|
||||||
|
|
||||||
|
### 6.6 task_failed 载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `task_id` | string | ✓ | 任务标识 |
|
||||||
|
| `error` | object | ✓ | 错误信息(错误码 + 描述 + 详情) |
|
||||||
|
|
||||||
|
### 6.7 task_need_info 载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `task_id` | string | ✓ | 任务标识 |
|
||||||
|
| `missing_fields` | array | ✓ | 缺失的字段列表 |
|
||||||
|
| `reason` | string | ✓ | 缺失原因 |
|
||||||
|
|
||||||
|
### 6.8 task_info_provided 载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `task_id` | string | ✓ | 任务标识 |
|
||||||
|
| `provided_info` | object | ✓ | 补充的信息 |
|
||||||
|
|
||||||
|
### 6.9 task_need_human 载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `task_id` | string | ✓ | 任务标识 |
|
||||||
|
| `escalation_level` | integer | ✓ | 升级级别(1/2/3) |
|
||||||
|
| `reason` | object | ✓ | 介入原因 |
|
||||||
|
| `options` | array | - | 可选方案列表 |
|
||||||
|
| `suggested_value` | object | - | Agent 建议值 |
|
||||||
|
|
||||||
|
### 6.10 human_decision 载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `task_id` | string | ✓ | 任务标识 |
|
||||||
|
| `decision` | object | ✓ | 决策内容 |
|
||||||
|
| `decided_by` | object | ✓ | 决策者信息(用户 ID + 角色) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 错误处理
|
||||||
|
|
||||||
|
参见数字分段错误码系统(1000-9999):
|
||||||
|
|
||||||
|
| 分段 | 类别 |
|
||||||
|
|------|------|
|
||||||
|
| 1000-1999 | 系统错误 |
|
||||||
|
| 2000-2999 | 任务错误 |
|
||||||
|
| 3000-3999 | 信息错误 |
|
||||||
|
| 4000-4999 | 能力错误 |
|
||||||
|
| 5000-5999 | 安全错误 |
|
||||||
|
| 6000-6999 | 通信错误 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 接口要求
|
||||||
|
|
||||||
|
Agent 实现 A2A 协议时必须提供:
|
||||||
|
|
||||||
|
| 接口 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 消息处理器 | 接收并处理 p2p:* 类型消息 |
|
||||||
|
| 任务处理器 | 执行具体任务逻辑 |
|
||||||
|
| 回调发送器 | 发送进度、完成、失败等回调 |
|
||||||
|
| 状态查询 | 支持任务状态查询 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 与其他协议的关系
|
||||||
|
|
||||||
|
- **依赖原始协议**:使用统一消息信封、签名机制
|
||||||
|
- **被 A2N 协议依赖**:群组内单播通信复用 A2A
|
||||||
|
- **被 P2A 协议封装**:外部调用最终转换为 A2A 消息
|
||||||
395
docs/v1/03-a2n-protocol.md
Normal file
395
docs/v1/03-a2n-protocol.md
Normal file
@@ -0,0 +1,395 @@
|
|||||||
|
# A2N 协议(Agent-to-N Protocol)
|
||||||
|
|
||||||
|
> 版本:1.0.0
|
||||||
|
> 状态:规范
|
||||||
|
> 层级:子协议层
|
||||||
|
> 基于:[灵隙原始协议](01-raw-protocol.md)、[A2A 协议](02-a2a-protocol.md)
|
||||||
|
> 前缀:`group:` / `inter_group:`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 定位
|
||||||
|
|
||||||
|
A2N 协议定义多个 Agent 组成群组进行协同工作的规范,包括群组管理、任务拆分与合并、群体决策、角色与权限、升级机制等。
|
||||||
|
|
||||||
|
**适用场景**:
|
||||||
|
- 复杂任务的拆分与并行执行(MapReduce 模式)
|
||||||
|
- 多 Agent 协同完成单一目标
|
||||||
|
- 群体投票与共识决策
|
||||||
|
- 临时或永久的 Agent 工作组
|
||||||
|
- 分级升级机制
|
||||||
|
|
||||||
|
**依赖关系**:
|
||||||
|
- 群组内成员间的单播通信复用 A2A 协议
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 功能定义
|
||||||
|
|
||||||
|
### 2.1 群组管理
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 群组创建 | Coordinator 创建群组,定义拓扑结构 |
|
||||||
|
| 群组解散 | Coordinator 解散群组 |
|
||||||
|
| 加入群组 | Agent 主动申请加入 |
|
||||||
|
| 离开群组 | 成员主动离开 |
|
||||||
|
| 邀请加入 | Coordinator 或成员邀请其他 Agent |
|
||||||
|
| 接受邀请 | 被邀请者接受邀请 |
|
||||||
|
| 拒绝邀请 | 被邀请者拒绝邀请 |
|
||||||
|
| 成员更新通知 | 成员变动时广播通知 |
|
||||||
|
| 角色变更 | Coordinator 调整成员角色 |
|
||||||
|
| 群组冻结 | 暂停群组活动 |
|
||||||
|
| 群组解冻 | 恢复群组活动 |
|
||||||
|
|
||||||
|
### 2.2 群组通信
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 广播 | 发送给所有成员 |
|
||||||
|
| 组播 | 发送给指定成员列表 |
|
||||||
|
| 单播 | 群内点对点(复用 A2A) |
|
||||||
|
| 消息中继 | 通过其他成员转发消息 |
|
||||||
|
|
||||||
|
### 2.3 任务协作
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 任务拆分 | Coordinator 将大任务拆分为子任务 |
|
||||||
|
| 任务分配 | 子任务分配给指定 Worker |
|
||||||
|
| 子任务进度 | Worker 上报子任务进度 |
|
||||||
|
| 结果合并 | Coordinator 合并子任务结果 |
|
||||||
|
|
||||||
|
### 2.4 共识投票
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 发起投票 | Coordinator 或 Reviewer 发起投票 |
|
||||||
|
| 提交投票 | 成员提交选项及理由 |
|
||||||
|
| 达成共识 | 公布投票结果 |
|
||||||
|
|
||||||
|
### 2.5 升级机制
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 共识僵局升级 | 投票无法达成共识时升级给人类 |
|
||||||
|
| 子任务阻塞升级 | 子任务阻塞时升级给人类 |
|
||||||
|
| 跨群组升级 | 升级到更高层级群组 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 消息类型定义
|
||||||
|
|
||||||
|
### 3.1 群组管理消息(前缀 `group:`)
|
||||||
|
|
||||||
|
| 消息类型 | 说明 |
|
||||||
|
|---------|------|
|
||||||
|
| `group:create` | 创建群组 |
|
||||||
|
| `group:disband` | 解散群组 |
|
||||||
|
| `group:join` | 加入群组 |
|
||||||
|
| `group:leave` | 离开群组 |
|
||||||
|
| `group:invite` | 邀请加入 |
|
||||||
|
| `group:accept_invite` | 接受邀请 |
|
||||||
|
| `group:reject_invite` | 拒绝邀请 |
|
||||||
|
| `group:member_update` | 成员更新通知 |
|
||||||
|
| `group:role_change` | 角色变更 |
|
||||||
|
|
||||||
|
### 3.2 群组通信消息(前缀 `group:`)
|
||||||
|
|
||||||
|
| 消息类型 | 说明 |
|
||||||
|
|---------|------|
|
||||||
|
| `group:broadcast` | 广播(所有成员) |
|
||||||
|
| `group:multicast` | 组播(指定成员) |
|
||||||
|
| `group:direct` | 群内单播 |
|
||||||
|
| `group:relay` | 消息中继 |
|
||||||
|
|
||||||
|
### 3.3 任务协作消息(前缀 `group:`)
|
||||||
|
|
||||||
|
| 消息类型 | 说明 |
|
||||||
|
|---------|------|
|
||||||
|
| `group:task_split` | 任务拆分 |
|
||||||
|
| `group:task_assign` | 任务分配 |
|
||||||
|
| `group:task_merge` | 结果合并 |
|
||||||
|
| `group:task_progress` | 子任务进度 |
|
||||||
|
|
||||||
|
### 3.4 共识投票消息(前缀 `group:`)
|
||||||
|
|
||||||
|
| 消息类型 | 说明 |
|
||||||
|
|---------|------|
|
||||||
|
| `group:vote` | 发起投票 |
|
||||||
|
| `group:vote_submit` | 提交投票 |
|
||||||
|
| `group:consensus` | 达成共识 |
|
||||||
|
|
||||||
|
### 3.5 HiL 升级消息(前缀 `group:` / `inter_group:`)
|
||||||
|
|
||||||
|
| 消息类型 | 说明 |
|
||||||
|
|---------|------|
|
||||||
|
| `group:consensus_escalate` | 共识僵局升级给人类 |
|
||||||
|
| `group:subtask_escalate` | 子任务阻塞升级给人类 |
|
||||||
|
| `group:human_decision` | 人类决策结果 |
|
||||||
|
| `inter_group:escalate` | 跨群组升级 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 核心概念定义
|
||||||
|
|
||||||
|
### 4.1 群组拓扑结构
|
||||||
|
|
||||||
|
| 拓扑类型 | 说明 | 适用场景 |
|
||||||
|
|---------|------|---------|
|
||||||
|
| `star` | 星型,中心 coordinator 协调 | 简单任务分发 |
|
||||||
|
| `mesh` | 网状,成员间可直接通信 | 对等协作 |
|
||||||
|
| `chain` | 链式,流水线模式 | 顺序处理 |
|
||||||
|
| `hierarchical` | 层级型,多层管理 | 大型复杂任务 |
|
||||||
|
| `fullmesh` | 全连接网状 | 高可靠协作 |
|
||||||
|
|
||||||
|
### 4.2 成员角色
|
||||||
|
|
||||||
|
| 角色 | 说明 | 权限 |
|
||||||
|
|------|------|------|
|
||||||
|
| `coordinator` | 协调者 | 创建/解散群组、任务拆分、发起投票、角色变更 |
|
||||||
|
| `worker` | 工作者 | 执行子任务、提交结果、投票 |
|
||||||
|
| `reviewer` | 审核者 | 审核结果、发起投票、升级请求 |
|
||||||
|
| `observer` | 观察者 | 只读,查看进度 |
|
||||||
|
|
||||||
|
### 4.3 群组状态
|
||||||
|
|
||||||
|
| 状态 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| `creating` | 创建中 |
|
||||||
|
| `active` | 活跃 |
|
||||||
|
| `frozen` | 冻结(不可执行新任务) |
|
||||||
|
| `disbanded` | 已解散(终态) |
|
||||||
|
|
||||||
|
### 4.4 合并策略
|
||||||
|
|
||||||
|
| 策略 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| `first_success` | 首个成功结果即返回 |
|
||||||
|
| `majority` | 多数结果合并 |
|
||||||
|
| `weighted` | 按权重加权合并 |
|
||||||
|
| `custom` | 自定义合并逻辑 |
|
||||||
|
|
||||||
|
### 4.5 共识类型
|
||||||
|
|
||||||
|
| 类型 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| `majority` | 多数投票(>50%) |
|
||||||
|
| `supermajority` | 绝对多数(>67%) |
|
||||||
|
| `unanimity` | 一致同意(100%) |
|
||||||
|
| `weighted` | 加权投票 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 群组生命周期
|
||||||
|
|
||||||
|
### 5.1 状态流转
|
||||||
|
|
||||||
|
```
|
||||||
|
creating → active → frozen → disbanded
|
||||||
|
↑ ↓
|
||||||
|
└─────────┘
|
||||||
|
解冻
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 群组创建流程
|
||||||
|
|
||||||
|
```
|
||||||
|
创建者(Coordinator) 被邀请成员
|
||||||
|
| |
|
||||||
|
|---- group:invite ---------------->| 发送邀请
|
||||||
|
| |
|
||||||
|
|<--- group:accept_invite ----------| 接受邀请
|
||||||
|
| |
|
||||||
|
|---- group:member_update --------->| 通知成员更新
|
||||||
|
| |
|
||||||
|
[群组状态变为 active] |
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.3 群组解散流程
|
||||||
|
|
||||||
|
```
|
||||||
|
Coordinator 所有成员
|
||||||
|
| |
|
||||||
|
|---- group:disband --------------->| 通知解散
|
||||||
|
| |
|
||||||
|
[群组状态变为 disbanded] |
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 任务协作流程
|
||||||
|
|
||||||
|
### 6.1 MapReduce 模式
|
||||||
|
|
||||||
|
```
|
||||||
|
Coordinator
|
||||||
|
│
|
||||||
|
group:task_split(拆分任务)
|
||||||
|
│
|
||||||
|
┌─────────────────┼─────────────────┐
|
||||||
|
▼ ▼ ▼
|
||||||
|
Worker1 Worker2 Worker3
|
||||||
|
│ │ │
|
||||||
|
│ 执行子任务 │ 执行子任务 │ 执行子任务
|
||||||
|
│ │ │
|
||||||
|
▼ ▼ ▼
|
||||||
|
子任务结果 子任务结果 子任务结果
|
||||||
|
└─────────────────┼─────────────────┘
|
||||||
|
│
|
||||||
|
group:task_merge(合并结果)
|
||||||
|
▼
|
||||||
|
最终结果
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 流程步骤
|
||||||
|
|
||||||
|
1. **任务拆分阶段**
|
||||||
|
- Coordinator 接收原始任务
|
||||||
|
- 将任务拆分为多个子任务
|
||||||
|
- 为每个子任务指定执行的 Worker
|
||||||
|
- 定义合并策略
|
||||||
|
|
||||||
|
2. **并行执行阶段**
|
||||||
|
- 各 Worker 并行执行子任务
|
||||||
|
- 定期上报进度
|
||||||
|
- 子任务完成后上报结果
|
||||||
|
|
||||||
|
3. **结果合并阶段**
|
||||||
|
- Coordinator 收集所有子任务结果
|
||||||
|
- 按合并策略合并结果
|
||||||
|
- 返回最终结果
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 共识投票流程
|
||||||
|
|
||||||
|
```
|
||||||
|
发起者(vote发起) 所有成员
|
||||||
|
| |
|
||||||
|
|---- group:vote ------------------>| 发起投票
|
||||||
|
| |
|
||||||
|
|<--- group:vote_submit (各成员) ---| 提交投票
|
||||||
|
| |
|
||||||
|
|---- group:consensus ------------->| 公布结果
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 载荷结构定义
|
||||||
|
|
||||||
|
### 8.1 群组创建载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `group_id` | string | ✓ | 群组唯一标识 |
|
||||||
|
| `group_name` | string | - | 群组名称 |
|
||||||
|
| `topology` | string | ✓ | 拓扑结构 |
|
||||||
|
| `config` | object | - | 群组配置 |
|
||||||
|
|
||||||
|
### 8.2 群组配置
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `max_members` | integer | 最大成员数 |
|
||||||
|
| `vote_threshold` | float | 投票阈值 |
|
||||||
|
| `default_consensus_type` | string | 默认共识类型 |
|
||||||
|
|
||||||
|
### 8.3 子任务结构
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `subtask_id` | string | ✓ | 子任务标识 |
|
||||||
|
| `description` | string | ✓ | 子任务描述 |
|
||||||
|
| `assigned_to` | string | ✓ | 执行者 Agent ID |
|
||||||
|
| `dependencies` | array | - | 依赖的子任务 ID 列表 |
|
||||||
|
| `status` | string | ✓ | 子任务状态 |
|
||||||
|
| `payload` | object | ✓ | 子任务参数 |
|
||||||
|
|
||||||
|
### 8.4 投票载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `vote_id` | string | ✓ | 投票标识 |
|
||||||
|
| `question` | string | ✓ | 投票问题 |
|
||||||
|
| `options` | array | ✓ | 选项列表 |
|
||||||
|
| `consensus_type` | string | ✓ | 共识类型 |
|
||||||
|
| `deadline` | string | - | 截止时间 |
|
||||||
|
|
||||||
|
### 8.5 投票提交载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `vote_id` | string | ✓ | 投票标识 |
|
||||||
|
| `voter_id` | string | ✓ | 投票者 ID |
|
||||||
|
| `option_id` | string | ✓ | 选择的选项 |
|
||||||
|
| `reasoning` | string | - | 投票理由 |
|
||||||
|
|
||||||
|
### 8.6 共识结果载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `vote_id` | string | ✓ | 投票标识 |
|
||||||
|
| `winner` | string | ✓ | 获胜选项 |
|
||||||
|
| `vote_counts` | object | ✓ | 各选项票数 |
|
||||||
|
| `passed` | boolean | ✓ | 是否通过阈值 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 升级机制
|
||||||
|
|
||||||
|
### 9.1 升级场景
|
||||||
|
|
||||||
|
| 场景 | 消息类型 | 说明 |
|
||||||
|
|------|---------|------|
|
||||||
|
| 共识僵局 | `group:consensus_escalate` | 投票超时未达成共识 |
|
||||||
|
| 子任务阻塞 | `group:subtask_escalate` | 子任务执行受阻 |
|
||||||
|
| 跨群组 | `inter_group:escalate` | 升级到上级群组 |
|
||||||
|
|
||||||
|
### 9.2 升级载荷
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `escalation_id` | string | ✓ | 升级标识 |
|
||||||
|
| `escalation_type` | string | ✓ | 升级类型 |
|
||||||
|
| `escalation_level` | integer | ✓ | 升级级别(1/2/3) |
|
||||||
|
| `context` | object | ✓ | 升级上下文 |
|
||||||
|
| `options` | array | - | 可选方案 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. 错误处理
|
||||||
|
|
||||||
|
群组错误码分段:7000-7999
|
||||||
|
|
||||||
|
| 错误码 | 名称 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| 7001 | 群组不存在 | |
|
||||||
|
| 7002 | 群组未激活 | |
|
||||||
|
| 7003 | 成员不存在 | |
|
||||||
|
| 7004 | 不是群组成员 | |
|
||||||
|
| 7005 | 未达成共识 | |
|
||||||
|
| 7006 | 角色不存在 | |
|
||||||
|
| 7007 | 已是成员 | |
|
||||||
|
| 7008 | 群组已满 | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. 接口要求
|
||||||
|
|
||||||
|
Agent 实现 A2N 协议时必须提供:
|
||||||
|
|
||||||
|
| 接口 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 群组管理处理器 | 处理群组创建、加入、离开等 |
|
||||||
|
| 子任务处理器 | 执行分配的子任务 |
|
||||||
|
| 投票处理器 | 处理投票相关消息 |
|
||||||
|
| 升级处理器 | 处理升级请求 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. 与其他协议的关系
|
||||||
|
|
||||||
|
- **依赖原始协议**:使用统一消息信封
|
||||||
|
- **依赖 A2A 协议**:群内单播通信复用 A2A
|
||||||
|
- **被 P2A 协议封装**:外部调用可触发群组任务
|
||||||
335
docs/v1/04-p2a-protocol.md
Normal file
335
docs/v1/04-p2a-protocol.md
Normal file
@@ -0,0 +1,335 @@
|
|||||||
|
# P2A 协议(Person/Program-to-Agent Protocol)
|
||||||
|
|
||||||
|
> 版本:1.0.0
|
||||||
|
> 状态:规范
|
||||||
|
> 层级:子协议层
|
||||||
|
> 基于:[灵隙原始协议](01-raw-protocol.md)
|
||||||
|
> 前缀:`caller:`(内部转换)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 定位
|
||||||
|
|
||||||
|
P2A 协议定义**非 Agent 调用方**(如普通后端服务、前端应用、第三方系统、人类用户)如何调用 Agent 能力的规范。
|
||||||
|
|
||||||
|
本协议将 A2A 协议的复杂性封装起来,提供简洁的 RESTful API,使调用方无需了解 A2A 协议细节即可使用 Agent 能力。
|
||||||
|
|
||||||
|
**适用场景**:
|
||||||
|
- 前端应用直接调用 Agent 能力
|
||||||
|
- 后端业务系统集成 Agent 服务
|
||||||
|
- 第三方开发者通过 API 接入
|
||||||
|
- 无需实现完整 A2A 协议的调用方
|
||||||
|
|
||||||
|
**设计原则**:
|
||||||
|
- **简单易用**:标准 RESTful API,JSON 格式
|
||||||
|
- **两种模式**:回调模式 + 轮询模式,调用方按需选择
|
||||||
|
- **认证简单**:API Key 认证,无需 HMAC 签名
|
||||||
|
- **文件支持**:支持 multipart/form-data 上传文件
|
||||||
|
- **错误友好**:清晰的错误码和错误信息
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 功能定义
|
||||||
|
|
||||||
|
### 2.1 任务提交
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| JSON 提交 | application/json 格式提交任务 |
|
||||||
|
| Multipart 提交 | 带文件上传的任务提交 |
|
||||||
|
|
||||||
|
### 2.2 任务查询
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 任务详情 | 获取完整任务信息(含结果) |
|
||||||
|
| 任务状态 | 简化版状态查询 |
|
||||||
|
| 任务列表 | 分页查询任务列表 |
|
||||||
|
|
||||||
|
### 2.3 任务控制
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 任务取消 | 取消正在执行的任务 |
|
||||||
|
|
||||||
|
### 2.4 能力查询
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 能力清单 | 获取 Agent 支持的任务类型 |
|
||||||
|
|
||||||
|
### 2.5 通知机制
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 回调通知 | 任务完成后主动回调调用方 |
|
||||||
|
| 轮询查询 | 调用方主动查询状态 |
|
||||||
|
|
||||||
|
### 2.6 认证
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| API Key 认证 | X-API-Key 头部认证 |
|
||||||
|
| 回调验证 | 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` | 获取能力清单 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 任务状态定义
|
||||||
|
|
||||||
|
P2A 协议使用简化状态(5 种):
|
||||||
|
|
||||||
|
| 状态 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| `received` | 已接收 |
|
||||||
|
| `processing` | 处理中 |
|
||||||
|
| `completed` | 已完成(终态) |
|
||||||
|
| `failed` | 已失败(终态) |
|
||||||
|
| `cancelled` | 已取消(终态) |
|
||||||
|
|
||||||
|
状态流转:
|
||||||
|
|
||||||
|
```
|
||||||
|
received → processing → completed
|
||||||
|
→ failed
|
||||||
|
→ cancelled
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 认证方式
|
||||||
|
|
||||||
|
### 5.1 API Key 认证
|
||||||
|
|
||||||
|
传递方式:
|
||||||
|
- HTTP Header:`X-API-Key: {api_key}`
|
||||||
|
- URL Query:`?api_key={api_key}`
|
||||||
|
|
||||||
|
如果服务端未配置 API Key,则跳过认证。
|
||||||
|
|
||||||
|
### 5.2 回调验证(可选)
|
||||||
|
|
||||||
|
如果调用方提供了 `callback_token`,则服务端在回调时会在 Header 中带上 `X-Callback-Token`,用于调用方验证回调来源。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 请求结构定义
|
||||||
|
|
||||||
|
### 6.1 任务提交请求(JSON)
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `task_type` | string | ✓ | 任务类型(如 `text_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 |
|
||||||
|
|
||||||
|
### 6.2 任务提交请求(Multipart)
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|:----:|------|
|
||||||
|
| `task_type` | string | ✓ | 任务类型 |
|
||||||
|
| `payload` | string(JSON) | ✓ | 任务参数(JSON 字符串) |
|
||||||
|
| `external_task_id` | string | - | 外部任务 ID |
|
||||||
|
| `priority` | string | - | 优先级 |
|
||||||
|
| `callback_url` | string | - | 回调 URL |
|
||||||
|
| `callback_token` | string | - | 回调 token |
|
||||||
|
| `file` | file | - | 上传的文件(可多个) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 响应结构定义
|
||||||
|
|
||||||
|
### 7.1 任务提交响应
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `success` | boolean | 是否成功 |
|
||||||
|
| `task_id` | string | 服务端生成的任务 ID |
|
||||||
|
| `status` | string | 初始状态(通常为 `received`) |
|
||||||
|
| `message` | string | 提示信息 |
|
||||||
|
| `error` | object | 错误信息(失败时) |
|
||||||
|
|
||||||
|
### 7.2 任务详情响应
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `success` | boolean | 是否成功 |
|
||||||
|
| `task` | object | 任务详情 |
|
||||||
|
| `error` | object | 错误信息 |
|
||||||
|
|
||||||
|
### 7.3 任务详情结构
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `id` | string | 任务 ID |
|
||||||
|
| `type` | string | 任务类型 |
|
||||||
|
| `status` | string | 任务状态 |
|
||||||
|
| `progress` | integer | 进度百分比(0-100) |
|
||||||
|
| `message` | string | 状态说明 |
|
||||||
|
| `created_at` | string | 创建时间(RFC3339) |
|
||||||
|
| `updated_at` | string | 更新时间(RFC3339) |
|
||||||
|
| `completed_at` | string | 完成时间(RFC3339) |
|
||||||
|
| `eta` | string | 预估完成时间 |
|
||||||
|
| `result` | object | 任务结果(结构由 task_type 决定) |
|
||||||
|
| `error` | object | 错误信息 |
|
||||||
|
|
||||||
|
### 7.4 任务列表响应
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `success` | boolean | 是否成功 |
|
||||||
|
| `tasks` | array | 任务列表 |
|
||||||
|
| `total` | integer | 总数 |
|
||||||
|
| `limit` | integer | 每页数量 |
|
||||||
|
| `offset` | integer | 偏移量 |
|
||||||
|
| `has_more` | boolean | 是否有更多 |
|
||||||
|
|
||||||
|
### 7.5 能力清单响应
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `agent_id` | string | Agent 唯一标识 |
|
||||||
|
| `agent_name` | string | Agent 名称 |
|
||||||
|
| `protocol_version` | string | 协议版本 |
|
||||||
|
| `supported_task_types` | array | 支持的任务类型列表 |
|
||||||
|
| `supported_content_types` | array | 支持的内容类型 |
|
||||||
|
| `max_file_size` | integer | 最大文件大小(字节) |
|
||||||
|
| `max_concurrent_tasks` | integer | 最大并发任务数 |
|
||||||
|
| `max_task_duration` | integer | 最大任务时长(秒) |
|
||||||
|
| `support_progress_updates` | boolean | 是否支持进度更新 |
|
||||||
|
| `support_streaming` | boolean | 是否支持流式传输 |
|
||||||
|
| `support_hil` | boolean | 是否支持人类介入 |
|
||||||
|
| `support_groups` | boolean | 是否支持群组协作 |
|
||||||
|
|
||||||
|
### 7.6 任务类型能力
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `type` | string | 任务类型标识 |
|
||||||
|
| `name` | string | 任务类型名称 |
|
||||||
|
| `description` | string | 描述 |
|
||||||
|
| `estimated_time` | string | 预估耗时(如 "30s-2min") |
|
||||||
|
| `input_schema` | string | 输入 Schema |
|
||||||
|
| `output_schema` | string | 输出 Schema |
|
||||||
|
| `capabilities` | array | 所需能力列表 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 回调结构定义
|
||||||
|
|
||||||
|
### 8.1 回调请求
|
||||||
|
|
||||||
|
当任务完成时,服务端向调用方提供的 `callback_url` 发送回调:
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `task_id` | string | 任务 ID |
|
||||||
|
| `external_task_id` | string | 外部任务 ID(如有) |
|
||||||
|
| `status` | string | 任务状态 |
|
||||||
|
| `progress` | integer | 进度 |
|
||||||
|
| `result` | object | 任务结果 |
|
||||||
|
| `error` | object | 错误信息 |
|
||||||
|
| `timestamp` | string | 时间戳(RFC3339) |
|
||||||
|
|
||||||
|
### 8.2 回调 Header
|
||||||
|
|
||||||
|
| Header | 说明 |
|
||||||
|
|--------|------|
|
||||||
|
| `X-Callback-Token` | 回调验证 token(如调用方提供了 callback_token) |
|
||||||
|
| `Content-Type` | `application/json` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 错误响应结构
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `success` | boolean | false |
|
||||||
|
| `error` | object | 错误详情 |
|
||||||
|
|
||||||
|
错误详情结构:
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `code` | integer | 数字错误码 |
|
||||||
|
| `category` | string | 错误类别 |
|
||||||
|
| `message` | string | 错误描述 |
|
||||||
|
| `details` | object | 详细信息 |
|
||||||
|
| `retry_after` | integer | 重试等待时间(秒) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. 传输模式
|
||||||
|
|
||||||
|
### 10.1 回调模式
|
||||||
|
|
||||||
|
调用方提供 `callback_url`:
|
||||||
|
- 任务状态变化时主动回调
|
||||||
|
- 无需轮询
|
||||||
|
- 适用于实时性要求高的场景
|
||||||
|
|
||||||
|
### 10.2 轮询模式
|
||||||
|
|
||||||
|
调用方不提供 `callback_url`:
|
||||||
|
- 需主动调用 `/task/{task_id}/status` 查询
|
||||||
|
- 适用于无法接收回调的场景
|
||||||
|
- 推荐轮询间隔:5-10 秒
|
||||||
|
|
||||||
|
### 10.3 混合模式
|
||||||
|
|
||||||
|
调用方提供 `callback_url`,同时支持轮询:
|
||||||
|
- 回调为主,轮询兜底
|
||||||
|
- 适用于高可靠性场景
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. 与 A2A 协议的关系
|
||||||
|
|
||||||
|
```
|
||||||
|
外部调用方 ──P2A REST API──▶ External API Layer ──A2A 消息──▶ Agent
|
||||||
|
```
|
||||||
|
|
||||||
|
P2A 协议是 A2A 协议的"简化入口":
|
||||||
|
|
||||||
|
| P2A API | A2A 消息映射 |
|
||||||
|
|---------|-------------|
|
||||||
|
| POST `/task` | `p2p:task_request` |
|
||||||
|
| GET `/task/{id}` | 内部状态查询 |
|
||||||
|
| POST `/task/{id}/cancel` | `p2p:task_cancel` |
|
||||||
|
| GET `/capabilities` | `p2p:capability_query` + `p2p:capability_response` |
|
||||||
|
| 回调发送 | `p2p:task_complete` / `p2p:task_failed` 等 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. 接口要求
|
||||||
|
|
||||||
|
实现 P2A 协议的服务端必须提供:
|
||||||
|
|
||||||
|
| 接口 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 任务接收端点 | 接收任务提交请求 |
|
||||||
|
| 任务查询端点 | 提供任务状态和结果查询 |
|
||||||
|
| 任务取消端点 | 支持任务取消 |
|
||||||
|
| 能力查询端点 | 提供能力清单 |
|
||||||
|
| 回调发送器 | 支持向调用方回调 |
|
||||||
|
| A2A 转换器 | 将 P2A 请求转换为 A2A 消息 |
|
||||||
898
docs/v1/05-identity-protocol-draft.md
Normal file
898
docs/v1/05-identity-protocol-draft.md
Normal file
@@ -0,0 +1,898 @@
|
|||||||
|
# 灵隙协议补充草案:去中心化身份与寻址
|
||||||
|
|
||||||
|
> 版本:0.1(草案)
|
||||||
|
> 状态:草案
|
||||||
|
> 层级:基础设施层
|
||||||
|
> 依赖:[灵隙原始协议](01-raw-protocol.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 摘要
|
||||||
|
|
||||||
|
本草案定义了灵隙协议栈中去中心化场景下的 Agent 身份认证与发现机制,解决无中心化目录时的 AgentID 唯一性和可验证性问题。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 背景与目标
|
||||||
|
|
||||||
|
### 1.1 问题陈述
|
||||||
|
|
||||||
|
现有协议假设存在中心化的注册表(如灵脉 Meridian),但在以下场景中:
|
||||||
|
- 临时 P2P 网络
|
||||||
|
- 跨组织协作
|
||||||
|
- 离线/断网环境
|
||||||
|
- 边缘计算场景
|
||||||
|
|
||||||
|
中心化注册不可用,需要去中心化的身份认证与发现机制。
|
||||||
|
|
||||||
|
### 1.2 设计目标
|
||||||
|
|
||||||
|
| 目标 | 说明 |
|
||||||
|
|-----|------|
|
||||||
|
| 身份可验证 | AgentID 无法伪造或冒用 |
|
||||||
|
| 去中心化 | 无需中心化注册表 |
|
||||||
|
| 高可用 | 无单点故障 |
|
||||||
|
| 可扩展 | 支持大规模 Agent 网络 |
|
||||||
|
| 可读性 | 支持人类可读别名(可选) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. AgentID 生成规则
|
||||||
|
|
||||||
|
### 2.1 ID 结构
|
||||||
|
|
||||||
|
AgentID 由三部分组成:
|
||||||
|
|
||||||
|
```
|
||||||
|
AgentID = {namespace}:{key_hash}:{alias}
|
||||||
|
|
||||||
|
示例:
|
||||||
|
synapse:7hJ4x9K2mNpQ:llm-agent-01
|
||||||
|
synapse:3kM8nP5qRsTu:image-gen
|
||||||
|
did:synapse:abc123def456:chat-bot
|
||||||
|
```
|
||||||
|
|
||||||
|
| 部分 | 格式 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| namespace | string | 命名空间(如 `synapse`) |
|
||||||
|
| key_hash | base58 | 公钥哈希的前 16 字节 |
|
||||||
|
| alias | string(可选) | 人类可读别名 |
|
||||||
|
|
||||||
|
### 2.2 生成算法
|
||||||
|
|
||||||
|
```go
|
||||||
|
func GenerateAgentID(privateKey []byte, namespace string, alias string) string {
|
||||||
|
// 1. 从私钥派生公钥
|
||||||
|
publicKey := crypto.GeneratePublicKey(privateKey)
|
||||||
|
|
||||||
|
// 2. 计算公钥哈希
|
||||||
|
hash := sha3.Sum256(publicKey)
|
||||||
|
|
||||||
|
// 3. 取前 16 字节,Base58 编码
|
||||||
|
keyHash := base58.Encode(hash[:16])
|
||||||
|
|
||||||
|
// 4. 组装完整 ID
|
||||||
|
if alias != "" {
|
||||||
|
return fmt.Sprintf("%s:%s:%s", namespace, keyHash, alias)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%s:%s", namespace, keyHash)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 ID 特性
|
||||||
|
|
||||||
|
| 特性 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 唯一性 | 相同公钥 → 相同 key_hash → 相同 AgentID |
|
||||||
|
| 不可伪造 | 无法在没有私钥的情况下生成有效 AgentID |
|
||||||
|
| 可验证 | 任何人都可以用公钥验证 AgentID 真实性 |
|
||||||
|
| 不可预测 | 私钥随机生成,key_hash 不可预测 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 身份认证机制
|
||||||
|
|
||||||
|
### 3.1 自我认证原理
|
||||||
|
|
||||||
|
```
|
||||||
|
验证方程:
|
||||||
|
Verify(AgentID, PublicKey) = true/false
|
||||||
|
|
||||||
|
其中:
|
||||||
|
AgentID.key_hash = Base58(SHA256(PublicKey)[:16])
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 签名验证流程
|
||||||
|
|
||||||
|
```
|
||||||
|
发送方:
|
||||||
|
1. 用私钥对消息签名
|
||||||
|
2. 发送 (Message, Signature, PublicKey, AgentID)
|
||||||
|
|
||||||
|
接收方:
|
||||||
|
1. 用 PublicKey 重新计算 AgentID.key_hash
|
||||||
|
2. 与消息中的 AgentID.key_hash 比较
|
||||||
|
3. 如匹配,用公钥验证签名
|
||||||
|
4. 如签名有效,确认消息来源
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 消息签名格式
|
||||||
|
|
||||||
|
```go
|
||||||
|
type SignedMessage struct {
|
||||||
|
Message *UnifiedSynapseMessage // 原始消息
|
||||||
|
Signature []byte // 签名
|
||||||
|
PublicKey []byte // 公钥
|
||||||
|
AgentID string // Agent 标识
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
签名内容:
|
||||||
|
|
||||||
|
```
|
||||||
|
signature_content =
|
||||||
|
sender.agent_id |
|
||||||
|
sender.endpoint |
|
||||||
|
timestamp |
|
||||||
|
sha256(payload)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.4 签名算法
|
||||||
|
|
||||||
|
| 算法 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| Ed25519 | 默认,高效且安全 |
|
||||||
|
| ECDSA-P256 | 兼容性选项 |
|
||||||
|
| RSA-2048 | 遗留系统兼容 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 分布式发现协议
|
||||||
|
|
||||||
|
### 4.1 发现机制选择
|
||||||
|
|
||||||
|
| 场景 | 推荐机制 |
|
||||||
|
|------|---------|
|
||||||
|
| 小规模(<100 Agent) | 广播查询 |
|
||||||
|
| 中规模(100-10000) | 分层 DHT |
|
||||||
|
| 大规模(>10000) | 完整 Kademlia |
|
||||||
|
|
||||||
|
### 4.2 广播查询协议
|
||||||
|
|
||||||
|
适用于小型网络,无需复杂路由:
|
||||||
|
|
||||||
|
```
|
||||||
|
Agent A 想知道 Agent B 的 Endpoint:
|
||||||
|
|
||||||
|
1. A 广播查询请求:
|
||||||
|
{
|
||||||
|
type: "agent_lookup",
|
||||||
|
target_id: "B's AgentID",
|
||||||
|
requester_id: "A's AgentID"
|
||||||
|
}
|
||||||
|
|
||||||
|
2. 知道 B 的节点响应:
|
||||||
|
{
|
||||||
|
type: "agent_lookup_response",
|
||||||
|
target_id: "B's AgentID",
|
||||||
|
endpoint: "http://B:8080",
|
||||||
|
signature: "B's signature"
|
||||||
|
}
|
||||||
|
|
||||||
|
3. A 收到响应后,用 B 的公钥验证签名
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 分层 DHT 协议
|
||||||
|
|
||||||
|
适用于中等规模网络:
|
||||||
|
|
||||||
|
```
|
||||||
|
层级结构:
|
||||||
|
Level 0: 本地网络(局域网/子网)
|
||||||
|
Level 1: 组织内网络
|
||||||
|
Level 2: 跨组织网络
|
||||||
|
Level 3: 全局网络
|
||||||
|
|
||||||
|
查询流程:
|
||||||
|
1. 先在本地查询
|
||||||
|
2. 本地未找到,查询上一层
|
||||||
|
3. 直到找到或返回"未找到"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.4 DHT 消息类型
|
||||||
|
|
||||||
|
| 消息类型 | 说明 |
|
||||||
|
|---------|------|
|
||||||
|
| `dht:ping` | 节点存活探测 |
|
||||||
|
| `dht:store` | 存储 Agent 记录 |
|
||||||
|
| `dht:find_node` | 查找附近节点 |
|
||||||
|
| `dht:find_value` | 查找 Agent 记录 |
|
||||||
|
| `dht:notify` | 通知记录更新 |
|
||||||
|
|
||||||
|
### 4.5 Agent 记录结构
|
||||||
|
|
||||||
|
```go
|
||||||
|
type AgentRecord struct {
|
||||||
|
AgentID string // Agent 唯一标识
|
||||||
|
Alias string // 人类可读别名(可选)
|
||||||
|
Endpoint string // 网络地址
|
||||||
|
PublicKey []byte // 公钥
|
||||||
|
TTL int64 // 记录有效期(秒)
|
||||||
|
Version uint64 // 版本号(递增)
|
||||||
|
Signature []byte // Agent 对以上字段的签名
|
||||||
|
Timestamp int64 // 发布时间戳
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
签名内容:
|
||||||
|
|
||||||
|
```
|
||||||
|
record_signature_content =
|
||||||
|
agent_id | alias | endpoint | public_key | ttl | version | timestamp
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4.1 区块链发现方案
|
||||||
|
|
||||||
|
区块链提供了强信任的去中心化注册与发现机制,适合高价值、高安全要求的场景。
|
||||||
|
|
||||||
|
### 4.1.1 链上 Agent 注册表(智能合约)
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────┐
|
||||||
|
│ Blockchain │
|
||||||
|
│ ┌─────────────────────────────────────────────────┐ │
|
||||||
|
│ │ AgentRegistry Contract │ │
|
||||||
|
│ │ ┌─────────────────────────────────────────┐ │ │
|
||||||
|
│ │ │ mapping(agentID => AgentRecord) │ │ │
|
||||||
|
│ │ │ - agentID: bytes32 │ │ │
|
||||||
|
│ │ │ - endpoint: string │ │ │
|
||||||
|
│ │ │ - publicKey: bytes │ │ │
|
||||||
|
│ │ │ - stake: uint256 │ │ │
|
||||||
|
│ │ │ - lastHeartbeat: uint256 │ │ │
|
||||||
|
│ │ │ - status: AgentStatus │ │ │
|
||||||
|
│ │ └─────────────────────────────────────────┘ │ │
|
||||||
|
│ └─────────────────────────────────────────────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────┘
|
||||||
|
▲ 注册 ▲ 查询
|
||||||
|
│ │
|
||||||
|
┌────┴────┐ ┌────┴────┐
|
||||||
|
│ Agent A │ │ Agent B │
|
||||||
|
└─────────┘ └─────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**核心思想**:
|
||||||
|
- Agent 在区块链智能合约中注册身份
|
||||||
|
- 注册需要质押一定数量的代币作为保证金
|
||||||
|
- 心跳通过交易上链更新
|
||||||
|
- 查询通过调用合约 `lookup` 方法
|
||||||
|
- 所有注册信息不可篡改
|
||||||
|
|
||||||
|
### 4.1.2 智能合约实现
|
||||||
|
|
||||||
|
```solidity
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
pragma solidity ^0.8.19;
|
||||||
|
|
||||||
|
contract AgentRegistry {
|
||||||
|
// Agent 状态
|
||||||
|
enum AgentStatus { None, Registered, Active, Suspended, Revoked }
|
||||||
|
|
||||||
|
// Agent 记录
|
||||||
|
struct AgentRecord {
|
||||||
|
bytes32 agentID; // Agent 标识(公钥哈希)
|
||||||
|
string endpoint; // 网络地址
|
||||||
|
bytes publicKey; // 公钥
|
||||||
|
uint256 stake; // 质押金额
|
||||||
|
uint256 lastHeartbeat; // 最后心跳时间
|
||||||
|
uint256 registerTime; // 注册时间
|
||||||
|
AgentStatus status; // 状态
|
||||||
|
bytes signature; // Agent 签名
|
||||||
|
}
|
||||||
|
|
||||||
|
// 配置
|
||||||
|
uint256 public registrationStake = 0.01 ether; // 注册押金
|
||||||
|
uint256 public heartbeatInterval = 1 hours; // 心跳间隔
|
||||||
|
uint256 public stakeAmount = 0.1 ether; // 质押要求
|
||||||
|
|
||||||
|
// 状态变量
|
||||||
|
mapping(bytes32 => AgentRecord) public agents;
|
||||||
|
mapping(address => bytes32) public addressToAgentID;
|
||||||
|
|
||||||
|
// 事件
|
||||||
|
event AgentRegistered(bytes32 indexed agentID, address indexed owner);
|
||||||
|
event AgentHeartbeat(bytes32 indexed agentID);
|
||||||
|
event AgentRevoked(bytes32 indexed agentID);
|
||||||
|
event AgentEndpointUpdated(bytes32 indexed agentID, string endpoint);
|
||||||
|
|
||||||
|
// 注册 Agent
|
||||||
|
function register(
|
||||||
|
bytes32 _agentID,
|
||||||
|
string memory _endpoint,
|
||||||
|
bytes memory _publicKey,
|
||||||
|
bytes memory _signature
|
||||||
|
) external payable {
|
||||||
|
require(msg.value >= registrationStake, "Insufficient stake");
|
||||||
|
require(agents[_agentID].status == AgentStatus.None, "Already registered");
|
||||||
|
|
||||||
|
// 验证签名:AgentID = keccak256(publicKey)
|
||||||
|
bytes32 derivedID = keccak256(_publicKey);
|
||||||
|
require(derivedID == _agentID, "AgentID does not match public key");
|
||||||
|
|
||||||
|
// 验证签名内容
|
||||||
|
bytes32 messageHash = keccak256(
|
||||||
|
abi.encodePacked(_agentID, _endpoint, msg.sender, block.timestamp)
|
||||||
|
);
|
||||||
|
require(
|
||||||
|
verifySignature(messageHash, _signature, _publicKey),
|
||||||
|
"Invalid signature"
|
||||||
|
);
|
||||||
|
|
||||||
|
agents[_agentID] = AgentRecord({
|
||||||
|
agentID: _agentID,
|
||||||
|
endpoint: _endpoint,
|
||||||
|
publicKey: _publicKey,
|
||||||
|
stake: msg.value,
|
||||||
|
lastHeartbeat: block.timestamp,
|
||||||
|
registerTime: block.timestamp,
|
||||||
|
status: AgentStatus.Registered,
|
||||||
|
signature: _signature
|
||||||
|
});
|
||||||
|
|
||||||
|
addressToAgentID[msg.sender] = _agentID;
|
||||||
|
emit AgentRegistered(_agentID, msg.sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 心跳保活(可更新 Endpoint)
|
||||||
|
function heartbeat(
|
||||||
|
bytes32 _agentID,
|
||||||
|
string memory _newEndpoint,
|
||||||
|
bytes memory _signature
|
||||||
|
) external {
|
||||||
|
AgentRecord storage agent = agents[_agentID];
|
||||||
|
require(agent.status != AgentStatus.None, "Not registered");
|
||||||
|
|
||||||
|
// 验证签名
|
||||||
|
bytes32 messageHash = keccak256(
|
||||||
|
abi.encodePacked(_agentID, block.timestamp, _newEndpoint)
|
||||||
|
);
|
||||||
|
require(
|
||||||
|
verifySignature(messageHash, _signature, agent.publicKey),
|
||||||
|
"Invalid signature"
|
||||||
|
);
|
||||||
|
|
||||||
|
// 更新 Endpoint(如有变化)
|
||||||
|
if (bytes(_newEndpoint).length > 0 &&
|
||||||
|
keccak256(abi.encodePacked(_newEndpoint)) !=
|
||||||
|
keccak256(abi.encodePacked(agent.endpoint))) {
|
||||||
|
agent.endpoint = _newEndpoint;
|
||||||
|
emit AgentEndpointUpdated(_agentID, _newEndpoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
agent.lastHeartbeat = block.timestamp;
|
||||||
|
emit AgentHeartbeat(_agentID);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询 Agent 信息
|
||||||
|
function lookup(bytes32 _agentID) external view returns (AgentRecord memory) {
|
||||||
|
return agents[_agentID];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证 Agent 是否活跃
|
||||||
|
function isActive(bytes32 _agentID) external view returns (bool) {
|
||||||
|
AgentRecord memory agent = agents[_agentID];
|
||||||
|
if (agent.status == AgentStatus.None || agent.status == AgentStatus.Revoked) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// 检查心跳是否过期(3倍心跳间隔)
|
||||||
|
if (block.timestamp - agent.lastHeartbeat > heartbeatInterval * 3) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 追加质押
|
||||||
|
function stakeMore(bytes32 _agentID) external payable {
|
||||||
|
AgentRecord storage agent = agents[_agentID];
|
||||||
|
require(agent.status != AgentStatus.None, "Not registered");
|
||||||
|
agent.stake += msg.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 注销 Agent(可取回质押)
|
||||||
|
function revoke(bytes32 _agentID) external {
|
||||||
|
AgentRecord storage agent = agents[_agentID];
|
||||||
|
require(agent.status != AgentStatus.None, "Not registered");
|
||||||
|
require(agent.status != AgentStatus.Revoked, "Already revoked");
|
||||||
|
|
||||||
|
uint256 refund = agent.stake;
|
||||||
|
agent.stake = 0;
|
||||||
|
agent.status = AgentStatus.Revoked;
|
||||||
|
|
||||||
|
payable(msg.sender).transfer(refund);
|
||||||
|
emit AgentRevoked(_agentID);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证签名(EIP-191)
|
||||||
|
function verifySignature(
|
||||||
|
bytes32 _message,
|
||||||
|
bytes memory _signature,
|
||||||
|
bytes memory _publicKey
|
||||||
|
) internal pure returns (bool) {
|
||||||
|
bytes32 ethSignedMessageHash = keccak256(
|
||||||
|
abi.encodePacked("\x19Ethereum Signed Message:\n32", _message)
|
||||||
|
);
|
||||||
|
|
||||||
|
address signer = recoverSigner(ethSignedMessageHash, _signature);
|
||||||
|
address expectedSigner = address(uint160(uint256(keccak256(_publicKey))));
|
||||||
|
|
||||||
|
return signer == expectedSigner;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.1.3 DID(Decentralized Identifiers)
|
||||||
|
|
||||||
|
本草案兼容 W3C DID 标准,支持标准的 DID 格式。
|
||||||
|
|
||||||
|
**DID 格式**:
|
||||||
|
|
||||||
|
```
|
||||||
|
did:synapse:{method-specific-id}
|
||||||
|
|
||||||
|
示例:
|
||||||
|
did:synapse:ethereum:0x1234abcd...5678
|
||||||
|
did:synapse:polygon:0xabcd...efgh
|
||||||
|
did:synapse:solana:7DeF...8901
|
||||||
|
did:synapse:key:z6MkpTHR...
|
||||||
|
```
|
||||||
|
|
||||||
|
**DID 方法**:
|
||||||
|
|
||||||
|
| 方法 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| `did:synapse:ethereum` | 基于以太坊链上注册表 |
|
||||||
|
| `did:synapse:polygon` | 基于 Polygon 链 |
|
||||||
|
| `did:synapse:solana` | 基于 Solana 链 |
|
||||||
|
| `did:synapse:key` | 基于公钥的离链 DID |
|
||||||
|
| `did:synapse:dht` | 基于 DHT 的离链 DID |
|
||||||
|
|
||||||
|
**DID Document 示例**:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"@context": [
|
||||||
|
"https://www.w3.org/ns/did/v1",
|
||||||
|
"https://www.w3.org/ns/synapse/v1"
|
||||||
|
],
|
||||||
|
"id": "did:synapse:ethereum:0x1234abcd5678",
|
||||||
|
"verificationMethod": [{
|
||||||
|
"id": "did:synapse:ethereum:0x1234abcd5678#keys-1",
|
||||||
|
"type": "EcdsaSecp256k1VerificationKey2019",
|
||||||
|
"controller": "did:synapse:ethereum:0x1234abcd5678",
|
||||||
|
"publicKeyHex": "02b3..."
|
||||||
|
}],
|
||||||
|
"service": [{
|
||||||
|
"id": "did:synapse:ethereum:0x1234abcd5678#synapse-agent",
|
||||||
|
"type": "SynapseAgent",
|
||||||
|
"serviceEndpoint": "https://agent-01.example.com/api/synapse"
|
||||||
|
}],
|
||||||
|
"synapse:capabilities": ["text_generation", "image_generation"],
|
||||||
|
"synapse:agentName": "智能写作助手",
|
||||||
|
"synapse:version": "1.0.0"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.1.4 区块链平台选择
|
||||||
|
|
||||||
|
| 平台 | 优点 | 缺点 | 适合场景 |
|
||||||
|
|------|------|------|---------|
|
||||||
|
| Ethereum | 生态最大、安全最高 | Gas 贵、延迟高 | 高价值交易、核心 Agent |
|
||||||
|
| Polygon | 低 Gas、快确认 | 中心化程度较高 | 中等价值、大量 Agent |
|
||||||
|
| Solana | 高吞吐、低延迟 | 稳定性偶有问题 | 高频心跳场景 |
|
||||||
|
| 联盟链 | 可控、隐私好 | 需要许可机制 | 企业内部、联盟合作 |
|
||||||
|
| L2 (Arbitrum) | 低 Gas、安全继承 | 复杂度较高 | 通用场景 |
|
||||||
|
| 本地私链 | 完全可控、零成本 | 信任范围有限 | 测试、内部系统 |
|
||||||
|
|
||||||
|
### 4.1.5 混合架构(推荐)
|
||||||
|
|
||||||
|
结合本地缓存、DHT 和区块链的三层架构,平衡性能和安全性:
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 查询路径(快→慢) │
|
||||||
|
│ │
|
||||||
|
│ Agent A │
|
||||||
|
│ │ │
|
||||||
|
│ │ 1. 本地缓存查询(内存,微秒级) │
|
||||||
|
│ │ ─────────────────────────── │
|
||||||
|
│ │ [cache hit] → 返回 │
|
||||||
|
│ │ [cache miss] │
|
||||||
|
│ │ │
|
||||||
|
│ │ 2. DHT 查询(网络,毫秒~秒级) │
|
||||||
|
│ │ ─────────────────────────── │
|
||||||
|
│ │ [dht hit] → 验证签名 → 更新缓存 → 返回 │
|
||||||
|
│ │ [dht miss] │
|
||||||
|
│ │ │
|
||||||
|
│ │ 3. 区块链查询(链上,秒~分钟级) │
|
||||||
|
│ │ ─────────────────────────── │
|
||||||
|
│ │ [chain hit] → 验证签名 → 广播DHT → 更新缓存 → 返回 │
|
||||||
|
│ │ [chain miss] → 未找到 │
|
||||||
|
│ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**分层缓存实现**:
|
||||||
|
|
||||||
|
```go
|
||||||
|
type HybridLookup struct {
|
||||||
|
// L1: 本地缓存(内存,TTL 1分钟)
|
||||||
|
LocalCache map[string]*AgentRecord
|
||||||
|
|
||||||
|
// L2: DHT 网络(分钟级一致性)
|
||||||
|
DHT DHTClient
|
||||||
|
|
||||||
|
// L3: 区块链(最终一致性源)
|
||||||
|
Blockchain BlockchainClient
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *HybridLookup) Find(agentID string) (*AgentRecord, error) {
|
||||||
|
// 1. 查本地缓存
|
||||||
|
if record, ok := h.LocalCache.Get(agentID); ok {
|
||||||
|
if record.IsFresh() {
|
||||||
|
return record, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 查 DHT
|
||||||
|
if record, err := h.DHT.FindValue(agentID); err == nil {
|
||||||
|
// 验证签名
|
||||||
|
if record.VerifySignature() {
|
||||||
|
h.LocalCache.Set(agentID, record)
|
||||||
|
return record, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 查区块链(最终源)
|
||||||
|
if record, err := h.Blockchain.Lookup(agentID); err == nil {
|
||||||
|
// 验证链上签名(已由链上合约验证过)
|
||||||
|
h.LocalCache.Set(agentID, record)
|
||||||
|
// 广播到 DHT 加速后续查询
|
||||||
|
h.DHT.Store(agentID, record)
|
||||||
|
return record, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, ErrAgentNotFound
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.1.6 链上治理与激励
|
||||||
|
|
||||||
|
区块链还可实现链上治理功能:
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 质押机制 | Agent 注册需质押代币,恶意行为被 slash |
|
||||||
|
| 信誉评分 | 链上可查的 Agent 信誉分 |
|
||||||
|
| 服务定价 | 智能合约自动结算任务费用 |
|
||||||
|
| 争议仲裁 | 链上投票仲裁 Agent 纠纷 |
|
||||||
|
| 协议升级 | 通过 DAO 投票决定协议升级 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 身份冲突处理
|
||||||
|
|
||||||
|
### 5.1 冲突场景
|
||||||
|
|
||||||
|
| 场景 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 同一公钥注册多个别名 | 允许(同一 Agent 的多个别名) |
|
||||||
|
| 不同公钥生成相同 AgentID | 不可能(公钥哈希唯一) |
|
||||||
|
| 伪造他人 AgentID | 不可能(无法伪造签名) |
|
||||||
|
| Endpoint 欺骗 | 需要额外验证 |
|
||||||
|
|
||||||
|
### 5.2 Endpoint 绑定验证
|
||||||
|
|
||||||
|
为防止 Endpoint 欺骗,引入双向认证:
|
||||||
|
|
||||||
|
```
|
||||||
|
1. Agent A 声称自己是 "synapse:abc123:agent-A"
|
||||||
|
并声称其 Endpoint 是 "http://A:8080"
|
||||||
|
|
||||||
|
2. Agent B 收到声明后:
|
||||||
|
a. 用 A 的公钥验证 AgentID 合法
|
||||||
|
b. 向 Endpoint 发送挑战
|
||||||
|
c. A 必须用私钥响应挑战
|
||||||
|
d. 响应通过,确认 Endpoint 有效
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.3 挑战-响应协议
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 挑战消息
|
||||||
|
type Challenge struct {
|
||||||
|
ChallengeID string // 挑战 ID
|
||||||
|
Nonce []byte // 随机数
|
||||||
|
Timestamp int64 // 发送时间
|
||||||
|
}
|
||||||
|
|
||||||
|
// 响应消息
|
||||||
|
type ChallengeResponse struct {
|
||||||
|
ChallengeID string // 对应的挑战 ID
|
||||||
|
Nonce []byte // 原样返回的随机数
|
||||||
|
Signature []byte // 对 Nonce 的签名
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证流程
|
||||||
|
func VerifyEndpoint(endpoint string, publicKey []byte, challenge *Challenge) bool {
|
||||||
|
// 1. 发送挑战到 Endpoint
|
||||||
|
resp := SendChallenge(endpoint, challenge)
|
||||||
|
|
||||||
|
// 2. 验证响应
|
||||||
|
if resp.ChallengeID != challenge.ChallengeID {
|
||||||
|
return false // 挑战 ID 不匹配
|
||||||
|
}
|
||||||
|
if !bytes.Equal(resp.Nonce, challenge.Nonce) {
|
||||||
|
return false // Nonce 被篡改
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 验证签名
|
||||||
|
return crypto.Verify(publicKey, challenge.Nonce, resp.Signature)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 生命周期管理
|
||||||
|
|
||||||
|
### 6.1 状态流转
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────────┐
|
||||||
|
│ offline │
|
||||||
|
└──────┬───────┘
|
||||||
|
│ 注册/上线
|
||||||
|
▼
|
||||||
|
┌──────────────┐
|
||||||
|
┌─────────│ online │─────────┐
|
||||||
|
│ └──────┬───────┘ │
|
||||||
|
│ │ 刷新 │ 心跳超时
|
||||||
|
│ ▼ │
|
||||||
|
│ ┌──────────────┐ │
|
||||||
|
│ │ active │ │
|
||||||
|
│ └──────┬───────┘ │
|
||||||
|
│ │ │
|
||||||
|
│ ┌─────────┴─────────┐ │
|
||||||
|
│ ▼ ▼ │
|
||||||
|
│ ┌──────────┐ ┌──────────┐ │
|
||||||
|
│ │ refreshing│ │ suspended │ │
|
||||||
|
│ └────┬─────┘ └────┬─────┘ │
|
||||||
|
│ │ │ │
|
||||||
|
└──────┴───────────────────┴───────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────┐
|
||||||
|
│ offline │
|
||||||
|
└──────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 生命周期消息
|
||||||
|
|
||||||
|
| 状态 | 说明 | 触发条件 |
|
||||||
|
|------|------|---------|
|
||||||
|
| offline | 离线 | 初始状态或主动注销 |
|
||||||
|
| online | 上线中 | 注册完成,等待首次心跳 |
|
||||||
|
| active | 活跃 | 定期心跳维持 |
|
||||||
|
| refreshing | 刷新中 | 更新 Endpoint 或别名 |
|
||||||
|
| suspended | 挂起 | 心跳超时,未注销 |
|
||||||
|
| offline | 离线 | 注销或永久离线 |
|
||||||
|
|
||||||
|
### 6.3 消息类型
|
||||||
|
|
||||||
|
| 消息类型 | 方向 | 说明 |
|
||||||
|
|---------|------|------|
|
||||||
|
| `identity:register` | → 网络 | 注册 Agent 身份 |
|
||||||
|
| `identity:refresh` | → 网络 | 刷新注册信息 |
|
||||||
|
| `identity:challenge` | 双向 | Endpoint 验证挑战 |
|
||||||
|
| `identity:challenge_response` | 双向 | 挑战响应 |
|
||||||
|
| `identity:revoke` | → 网络 | 注销身份 |
|
||||||
|
| `identity:lookup` | → 网络 | 查询 Agent 信息 |
|
||||||
|
| `identity:lookup_response` | → 网络 | 查询响应 |
|
||||||
|
| `identity:announce` | → 网络 | 广播在线状态 |
|
||||||
|
| `identity:heartbeat` | → 网络 | 心跳保活 |
|
||||||
|
|
||||||
|
### 6.4 Register 载荷
|
||||||
|
|
||||||
|
```go
|
||||||
|
type IdentityRegisterPayload struct {
|
||||||
|
AgentID string // Agent 标识
|
||||||
|
Alias string // 人类可读别名
|
||||||
|
Endpoint string // 网络地址
|
||||||
|
PublicKey []byte // 公钥
|
||||||
|
TTL int64 // 注册有效期
|
||||||
|
Version uint64 // 版本号
|
||||||
|
Signature []byte // Agent 签名
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.5 Heartbeat 载荷
|
||||||
|
|
||||||
|
```go
|
||||||
|
type IdentityHeartbeatPayload struct {
|
||||||
|
AgentID string // Agent 标识
|
||||||
|
Endpoint string // 当前 Endpoint(可能变化)
|
||||||
|
TTL int64 // 续期时间
|
||||||
|
Signature []byte // Agent 签名
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 安全考虑
|
||||||
|
|
||||||
|
### 7.1 威胁模型
|
||||||
|
|
||||||
|
| 威胁 | 场景 | 防护措施 |
|
||||||
|
|------|------|---------|
|
||||||
|
| 身份伪造 | 攻击者声称自己是他人 | 公钥派生 ID + 签名验证 |
|
||||||
|
| Endpoint 欺骗 | 攻击者声称他人 Endpoint | 挑战-响应协议 |
|
||||||
|
| 重放攻击 | 攻击者重放旧消息 | 时间戳 + Nonce |
|
||||||
|
| 中间人攻击 | 拦截并修改消息 | TLS + 签名验证 |
|
||||||
|
| 女巫攻击 | 一个节点伪装多个身份 | 工作量证明或权益证明(可选) |
|
||||||
|
| 日食攻击 | 隔离目标节点 | 多路径查询 |
|
||||||
|
|
||||||
|
### 7.2 重放攻击防护
|
||||||
|
|
||||||
|
```go
|
||||||
|
type AntiReplay struct {
|
||||||
|
RecentNonces map[string]int64 // nonce -> timestamp
|
||||||
|
Window time.Duration // 时间窗口(5分钟)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *AntiReplay) CheckAndAdd(nonce string, timestamp int64) bool {
|
||||||
|
// 1. 检查时间戳是否在窗口内
|
||||||
|
now := time.Now().Unix()
|
||||||
|
if now - timestamp > int64(a.Window.Seconds()) {
|
||||||
|
return false // 时间戳太旧
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 检查 Nonce 是否已使用
|
||||||
|
if _, exists := a.RecentNonces[nonce]; exists {
|
||||||
|
return false // 重放
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 记录
|
||||||
|
a.RecentNonces[nonce] = timestamp
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.3 私钥保护
|
||||||
|
|
||||||
|
| 场景 | 建议 |
|
||||||
|
|------|------|
|
||||||
|
| 本地运行 | 使用密钥文件 + 操作系统密钥链 |
|
||||||
|
| 云端运行 | 使用 HSM/KMS |
|
||||||
|
| 嵌入式设备 | 使用 TPM |
|
||||||
|
| 多 Agent 共享 | 密钥分片(如 Shamir's Secret Sharing) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 与现有协议的关系
|
||||||
|
|
||||||
|
### 8.1 与原始协议的整合
|
||||||
|
|
||||||
|
本草案扩展 [01-raw-protocol.md](01-raw-protocol.md) 中的 `AgentEndpoint`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
type AgentEndpoint struct {
|
||||||
|
AgentID string // 扩展:基于公钥派生
|
||||||
|
AgentName string // 人类可读名称
|
||||||
|
SystemID string // 所属系统
|
||||||
|
Endpoint string // 回调端点
|
||||||
|
Version string // Agent 版本
|
||||||
|
|
||||||
|
// 新增字段
|
||||||
|
PublicKey []byte // 公钥(用于验证)
|
||||||
|
Namespace string // 命名空间
|
||||||
|
Alias string // 人类可读别名
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.2 与灵脉(Meridian)的整合
|
||||||
|
|
||||||
|
| 模式 | 行为 |
|
||||||
|
|------|------|
|
||||||
|
| 中心化可用 | 使用灵脉作为主注册表,本草案作为备份 |
|
||||||
|
| 去中心化 | 使用本草案的 DHT 机制,完全去中心化 |
|
||||||
|
| 混合模式 | 核心 Agent 使用中心化,边缘 Agent 使用去中心化 |
|
||||||
|
|
||||||
|
### 8.3 与灵玺(Sigil)的整合
|
||||||
|
|
||||||
|
| 组件 | 职责 |
|
||||||
|
|------|------|
|
||||||
|
| 灵玺(Sigil) | 密钥管理、签名验证 |
|
||||||
|
| 本草案 | ID 生成、发现协议、生命周期 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 协议消息汇总
|
||||||
|
|
||||||
|
### 9.1 消息类型列表
|
||||||
|
|
||||||
|
| 类型 | 协议前缀 | 说明 |
|
||||||
|
|------|---------|------|
|
||||||
|
| `identity:register` | 前端 | 注册身份 |
|
||||||
|
| `identity:refresh` | 前端 | 刷新注册 |
|
||||||
|
| `identity:revoke` | 前端 | 注销身份 |
|
||||||
|
| `identity:challenge` | 前端 | 挑战请求 |
|
||||||
|
| `identity:challenge_response` | 前端 | 挑战响应 |
|
||||||
|
| `identity:lookup` | 前端 | 查询身份 |
|
||||||
|
| `identity:lookup_response` | 前端 | 查询响应 |
|
||||||
|
| `identity:announce` | 前端 | 广播在线 |
|
||||||
|
| `identity:heartbeat` | 前端 | 心跳保活 |
|
||||||
|
| `dht:ping` | DHT | 节点探测 |
|
||||||
|
| `dht:store` | DHT | 存储记录 |
|
||||||
|
| `dht:find_node` | DHT | 查找节点 |
|
||||||
|
| `dht:find_value` | DHT | 查找值 |
|
||||||
|
| `dht:notify` | DHT | 通知更新 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. 待解决问题(Open Issues)
|
||||||
|
|
||||||
|
| 问题 | 说明 | 优先级 |
|
||||||
|
|------|------|--------|
|
||||||
|
| 隐私保护 | 公钥哈希是否暴露身份? | 高 |
|
||||||
|
| 密钥轮换 | 私钥更换后如何保持 AgentID? | 高 |
|
||||||
|
| 名称冲突 | 人类可读别名可能重复 | 中 |
|
||||||
|
| 性能优化 | DHT 查找延迟 | 中 |
|
||||||
|
| 移动 Agent | Endpoint 频繁变化 | 低 |
|
||||||
|
| 链上 Gas 成本 | 区块链交易费用 | 中 |
|
||||||
|
| DID 方法注册 | W3C 标准 DID 方法注册流程 | 低 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. 实现建议
|
||||||
|
|
||||||
|
### 11.1 分阶段实现
|
||||||
|
|
||||||
|
**Phase 1(最小可行)**:
|
||||||
|
- 实现 AgentID 公钥派生
|
||||||
|
- 实现消息签名验证
|
||||||
|
- 使用广播进行发现
|
||||||
|
|
||||||
|
**Phase 2(基本功能)**:
|
||||||
|
- 实现分层 DHT
|
||||||
|
- 实现生命周期管理
|
||||||
|
- 实现挑战-响应协议
|
||||||
|
|
||||||
|
**Phase 3(完整功能)**:
|
||||||
|
- 实现完整 Kademlia
|
||||||
|
- 实现隐私保护
|
||||||
|
- 实现密钥轮换
|
||||||
|
|
||||||
|
### 11.2 推荐库
|
||||||
|
|
||||||
|
| 功能 | 推荐库 |
|
||||||
|
|------|--------|
|
||||||
|
| 加密签名 | golang.org/x/crypto/ed25519 |
|
||||||
|
| Base58 | github.com/mr-tron/base58 |
|
||||||
|
| DHT | github.com/anacrolix/go-libutp 或自实现 |
|
||||||
|
| 分布式存储 | etcd/consul(混合模式) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. 参考资料
|
||||||
|
|
||||||
|
- [Kademlia: A Peer-to-peer Information System Based on the XOR Metric](https://pdos.csail.mit.edu/~petar/papers/maymounkov-kademlia-lncs.pdf)
|
||||||
|
- [Self-Certifying File System (SFS)](https://pdos.csail.mit.edu/~petar/papers/sfs.pdf)
|
||||||
|
- [Decentralized Identifiers (DIDs) v1.0](https://www.w3.org/TR/did-core/)
|
||||||
|
- [WebID 2.0](https://www.w3.org/2005/Incubator/webid/spec/identity/)
|
||||||
|
- [EIP-191: Signed Data Standard](https://eips.ethereum.org/EIPS/eip-191)
|
||||||
|
- [EIP-712: Ethereum Typed Structured Data Signing](https://eips.ethereum.org/EIPS/eip-712)
|
||||||
|
- [DID Method Registry](https://www.w3.org/TR/did-spec-registries/)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**草案状态**:本文档为初始草案,欢迎反馈和讨论。
|
||||||
521
harbor/harbor.go
Normal file
521
harbor/harbor.go
Normal file
@@ -0,0 +1,521 @@
|
|||||||
|
// Package harbor 灵泊 - 异步队列与暂存层
|
||||||
|
//
|
||||||
|
// "泊"为船舶停靠。数据包如远行之舟,
|
||||||
|
// 遇风浪(网络抖动)时暂泊于此,
|
||||||
|
// 待风平浪静(目标就绪)再启航。
|
||||||
|
// 不丢包、不超时,给予 Agent 异步协作的从容。
|
||||||
|
package harbor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"synapse/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Message Queue - 消息队列
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// QueueType 队列类型
|
||||||
|
type QueueType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
QueueFIFO QueueType = "fifo" // 先进先出
|
||||||
|
QueuePriority QueueType = "priority" // 优先级队列
|
||||||
|
QueueLIFO QueueType = "lifo" // 后进先出
|
||||||
|
)
|
||||||
|
|
||||||
|
// QueuedMessage 队列中的消息
|
||||||
|
type QueuedMessage struct {
|
||||||
|
ID string
|
||||||
|
Message *types.UnifiedSynapseMessage
|
||||||
|
Priority int
|
||||||
|
EnqueueTime time.Time
|
||||||
|
RetryCount int
|
||||||
|
MaxRetries int
|
||||||
|
NextRetry time.Time
|
||||||
|
Status QueuedStatus
|
||||||
|
Target string // 目标 endpoint
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueuedStatus 队列消息状态
|
||||||
|
type QueuedStatus string
|
||||||
|
|
||||||
|
const (
|
||||||
|
QueuedPending QueuedStatus = "pending"
|
||||||
|
QueuedProcessing QueuedStatus = "processing"
|
||||||
|
QueuedDelivered QueuedStatus = "delivered"
|
||||||
|
QueuedFailed QueuedStatus = "failed"
|
||||||
|
QueuedDead QueuedStatus = "dead"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MessageQueue 消息队列
|
||||||
|
type MessageQueue struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
messages []*QueuedMessage
|
||||||
|
config *QueueConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueueConfig 队列配置
|
||||||
|
type QueueConfig struct {
|
||||||
|
MaxSize int // 最大队列大小
|
||||||
|
DefaultMaxRetries int // 默认最大重试次数
|
||||||
|
DefaultRetryDelay time.Duration // 默认重试延迟
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultQueueConfig 返回默认队列配置
|
||||||
|
func DefaultQueueConfig() *QueueConfig {
|
||||||
|
return &QueueConfig{
|
||||||
|
MaxSize: 10000,
|
||||||
|
DefaultMaxRetries: 5,
|
||||||
|
DefaultRetryDelay: 30 * time.Second,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewMessageQueue 创建消息队列
|
||||||
|
func NewMessageQueue(config *QueueConfig) *MessageQueue {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultQueueConfig()
|
||||||
|
}
|
||||||
|
return &MessageQueue{
|
||||||
|
messages: make([]*QueuedMessage, 0),
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enqueue 入队
|
||||||
|
func (mq *MessageQueue) Enqueue(msg *types.UnifiedSynapseMessage, target string, priority int) (*QueuedMessage, error) {
|
||||||
|
mq.mu.Lock()
|
||||||
|
defer mq.mu.Unlock()
|
||||||
|
|
||||||
|
if len(mq.messages) >= mq.config.MaxSize {
|
||||||
|
return nil, fmt.Errorf("queue is full")
|
||||||
|
}
|
||||||
|
|
||||||
|
qm := &QueuedMessage{
|
||||||
|
ID: fmt.Sprintf("q-%d", time.Now().UnixNano()),
|
||||||
|
Message: msg,
|
||||||
|
Priority: priority,
|
||||||
|
EnqueueTime: time.Now(),
|
||||||
|
RetryCount: 0,
|
||||||
|
MaxRetries: mq.config.DefaultMaxRetries,
|
||||||
|
NextRetry: time.Now(),
|
||||||
|
Status: QueuedPending,
|
||||||
|
Target: target,
|
||||||
|
}
|
||||||
|
|
||||||
|
// 按优先级插入
|
||||||
|
inserted := false
|
||||||
|
for i, m := range mq.messages {
|
||||||
|
if priority > m.Priority {
|
||||||
|
mq.messages = append(mq.messages[:i], append([]*QueuedMessage{qm}, mq.messages[i:]...)...)
|
||||||
|
inserted = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !inserted {
|
||||||
|
mq.messages = append(mq.messages, qm)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("[灵泊] 消息入队: %s (目标: %s, 优先级: %d)", qm.ID, target, priority)
|
||||||
|
return qm, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dequeue 出队
|
||||||
|
func (mq *MessageQueue) Dequeue() (*QueuedMessage, error) {
|
||||||
|
mq.mu.Lock()
|
||||||
|
defer mq.mu.Unlock()
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
for i, qm := range mq.messages {
|
||||||
|
if qm.Status == QueuedPending && now.After(qm.NextRetry) {
|
||||||
|
qm.Status = QueuedProcessing
|
||||||
|
// 移到待处理
|
||||||
|
mq.messages = append(mq.messages[:i], mq.messages[i+1:]...)
|
||||||
|
return qm, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("no messages available")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkDelivered 标记为已送达
|
||||||
|
func (mq *MessageQueue) MarkDelivered(msgID string) error {
|
||||||
|
mq.mu.Lock()
|
||||||
|
defer mq.mu.Unlock()
|
||||||
|
|
||||||
|
for _, qm := range mq.messages {
|
||||||
|
if qm.ID == msgID {
|
||||||
|
qm.Status = QueuedDelivered
|
||||||
|
log.Printf("[灵泊] 消息送达: %s", msgID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Errorf("message %s not found", msgID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkFailed 标记为失败(会重试)
|
||||||
|
func (mq *MessageQueue) MarkFailed(msgID string, err error) error {
|
||||||
|
mq.mu.Lock()
|
||||||
|
defer mq.mu.Unlock()
|
||||||
|
|
||||||
|
for _, qm := range mq.messages {
|
||||||
|
if qm.ID == msgID {
|
||||||
|
qm.RetryCount++
|
||||||
|
if qm.RetryCount >= qm.MaxRetries {
|
||||||
|
qm.Status = QueuedDead
|
||||||
|
log.Printf("[灵泊] 消息失败(已死): %s (重试: %d次)", msgID, qm.RetryCount)
|
||||||
|
} else {
|
||||||
|
qm.Status = QueuedPending
|
||||||
|
// 指数退避
|
||||||
|
delay := mq.config.DefaultRetryDelay * time.Duration(1<<uint(qm.RetryCount-1))
|
||||||
|
qm.NextRetry = time.Now().Add(delay)
|
||||||
|
log.Printf("[灵泊] 消息失败(将重试): %s (重试: %d/%d, 下次: %v)",
|
||||||
|
msgID, qm.RetryCount, qm.MaxRetries, delay)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Errorf("message %s not found", msgID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size 队列大小
|
||||||
|
func (mq *MessageQueue) Size() int {
|
||||||
|
mq.mu.RLock()
|
||||||
|
defer mq.mu.RUnlock()
|
||||||
|
return len(mq.messages)
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Message Buffer - 消息缓冲
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// MessageBuffer 消息缓冲(暂存离线消息)
|
||||||
|
type MessageBuffer struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
buffers map[string][]*types.UnifiedSynapseMessage // agent_id -> messages
|
||||||
|
config *BufferConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// BufferConfig 缓冲配置
|
||||||
|
type BufferConfig struct {
|
||||||
|
MaxPerAgent int // 每个 Agent 最大缓冲数
|
||||||
|
MaxAge time.Duration // 消息最大存活时间
|
||||||
|
CleanupInterval time.Duration // 清理间隔
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultBufferConfig 返回默认缓冲配置
|
||||||
|
func DefaultBufferConfig() *BufferConfig {
|
||||||
|
return &BufferConfig{
|
||||||
|
MaxPerAgent: 1000,
|
||||||
|
MaxAge: 24 * time.Hour,
|
||||||
|
CleanupInterval: 1 * time.Hour,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewMessageBuffer 创建消息缓冲
|
||||||
|
func NewMessageBuffer(config *BufferConfig) *MessageBuffer {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultBufferConfig()
|
||||||
|
}
|
||||||
|
mb := &MessageBuffer{
|
||||||
|
buffers: make(map[string][]*types.UnifiedSynapseMessage),
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
|
||||||
|
// 启动清理协程
|
||||||
|
go mb.cleanupLoop()
|
||||||
|
|
||||||
|
return mb
|
||||||
|
}
|
||||||
|
|
||||||
|
// BufferMessage 缓冲消息
|
||||||
|
func (mb *MessageBuffer) BufferMessage(agentID string, msg *types.UnifiedSynapseMessage) error {
|
||||||
|
mb.mu.Lock()
|
||||||
|
defer mb.mu.Unlock()
|
||||||
|
|
||||||
|
buf, ok := mb.buffers[agentID]
|
||||||
|
if !ok {
|
||||||
|
buf = make([]*types.UnifiedSynapseMessage, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(buf) >= mb.config.MaxPerAgent {
|
||||||
|
// 丢弃最旧的
|
||||||
|
buf = buf[1:]
|
||||||
|
}
|
||||||
|
|
||||||
|
mb.buffers[agentID] = append(buf, msg)
|
||||||
|
|
||||||
|
log.Printf("[灵泊] 缓冲消息: %s -> %s (缓冲区大小: %d)",
|
||||||
|
msg.Sender.AgentID, agentID, len(mb.buffers[agentID]))
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FlushBuffer 清空缓冲并返回所有消息
|
||||||
|
func (mb *MessageBuffer) FlushBuffer(agentID string) []*types.UnifiedSynapseMessage {
|
||||||
|
mb.mu.Lock()
|
||||||
|
defer mb.mu.Unlock()
|
||||||
|
|
||||||
|
buf, ok := mb.buffers[agentID]
|
||||||
|
if !ok {
|
||||||
|
return []*types.UnifiedSynapseMessage{}
|
||||||
|
}
|
||||||
|
|
||||||
|
delete(mb.buffers, agentID)
|
||||||
|
|
||||||
|
log.Printf("[灵泊] 清空缓冲: %s (消息数: %d)", agentID, len(buf))
|
||||||
|
return buf
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetBufferSize 获取缓冲大小
|
||||||
|
func (mb *MessageBuffer) GetBufferSize(agentID string) int {
|
||||||
|
mb.mu.RLock()
|
||||||
|
defer mb.mu.RUnlock()
|
||||||
|
return len(mb.buffers[agentID])
|
||||||
|
}
|
||||||
|
|
||||||
|
// cleanupLoop 清理过期消息
|
||||||
|
func (mb *MessageBuffer) cleanupLoop() {
|
||||||
|
ticker := time.NewTicker(mb.config.CleanupInterval)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for range ticker.C {
|
||||||
|
mb.cleanup()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mb *MessageBuffer) cleanup() {
|
||||||
|
mb.mu.Lock()
|
||||||
|
defer mb.mu.Unlock()
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
cleaned := 0
|
||||||
|
|
||||||
|
for agentID, buf := range mb.buffers {
|
||||||
|
var newBuf []*types.UnifiedSynapseMessage
|
||||||
|
for _, msg := range buf {
|
||||||
|
msgTime, _ := time.Parse(time.RFC3339, string(msg.Timestamp))
|
||||||
|
if now.Sub(msgTime) < mb.config.MaxAge {
|
||||||
|
newBuf = append(newBuf, msg)
|
||||||
|
} else {
|
||||||
|
cleaned++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mb.buffers[agentID] = newBuf
|
||||||
|
}
|
||||||
|
|
||||||
|
if cleaned > 0 {
|
||||||
|
log.Printf("[灵泊] 清理过期消息: %d 条", cleaned)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Retry Manager - 重试管理器
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// RetryManager 重试管理器
|
||||||
|
type RetryManager struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
retries map[string]*RetryEntry
|
||||||
|
config *RetryConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// RetryEntry 重试条目
|
||||||
|
type RetryEntry struct {
|
||||||
|
ID string
|
||||||
|
Message *types.UnifiedSynapseMessage
|
||||||
|
Target string
|
||||||
|
RetryCount int
|
||||||
|
MaxRetries int
|
||||||
|
NextRetry time.Time
|
||||||
|
LastError string
|
||||||
|
BackoffBase time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// RetryConfig 重试配置
|
||||||
|
type RetryConfig struct {
|
||||||
|
MaxRetries int
|
||||||
|
BaseDelay time.Duration
|
||||||
|
MaxDelay time.Duration
|
||||||
|
JitterFactor float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultRetryConfig 返回默认重试配置
|
||||||
|
func DefaultRetryConfig() *RetryConfig {
|
||||||
|
return &RetryConfig{
|
||||||
|
MaxRetries: 5,
|
||||||
|
BaseDelay: 1 * time.Second,
|
||||||
|
MaxDelay: 5 * time.Minute,
|
||||||
|
JitterFactor: 0.1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRetryManager 创建重试管理器
|
||||||
|
func NewRetryManager(config *RetryConfig) *RetryManager {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultRetryConfig()
|
||||||
|
}
|
||||||
|
return &RetryManager{
|
||||||
|
retries: make(map[string]*RetryEntry),
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddRetry 添加重试条目
|
||||||
|
func (rm *RetryManager) AddRetry(msg *types.UnifiedSynapseMessage, target string) {
|
||||||
|
rm.mu.Lock()
|
||||||
|
defer rm.mu.Unlock()
|
||||||
|
|
||||||
|
id := fmt.Sprintf("retry-%d", time.Now().UnixNano())
|
||||||
|
entry := &RetryEntry{
|
||||||
|
ID: id,
|
||||||
|
Message: msg,
|
||||||
|
Target: target,
|
||||||
|
RetryCount: 0,
|
||||||
|
MaxRetries: rm.config.MaxRetries,
|
||||||
|
NextRetry: time.Now().Add(rm.config.BaseDelay),
|
||||||
|
BackoffBase: rm.config.BaseDelay,
|
||||||
|
}
|
||||||
|
|
||||||
|
rm.retries[id] = entry
|
||||||
|
|
||||||
|
log.Printf("[灵泊] 添加重试: %s -> %s (最多 %d 次)", id, target, rm.config.MaxRetries)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPendingRetries 获取待重试的条目
|
||||||
|
func (rm *RetryManager) GetPendingRetries() []*RetryEntry {
|
||||||
|
rm.mu.RLock()
|
||||||
|
defer rm.mu.RUnlock()
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
var pending []*RetryEntry
|
||||||
|
for _, entry := range rm.retries {
|
||||||
|
if now.After(entry.NextRetry) && entry.RetryCount < entry.MaxRetries {
|
||||||
|
pending = append(pending, entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pending
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkSuccess 标记成功
|
||||||
|
func (rm *RetryManager) MarkSuccess(retryID string) {
|
||||||
|
rm.mu.Lock()
|
||||||
|
defer rm.mu.Unlock()
|
||||||
|
delete(rm.retries, retryID)
|
||||||
|
log.Printf("[灵泊] 重试成功: %s", retryID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkFailure 标记失败
|
||||||
|
func (rm *RetryManager) MarkFailure(retryID string, err error) bool {
|
||||||
|
rm.mu.Lock()
|
||||||
|
defer rm.mu.Unlock()
|
||||||
|
|
||||||
|
entry, ok := rm.retries[retryID]
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
entry.RetryCount++
|
||||||
|
entry.LastError = err.Error()
|
||||||
|
|
||||||
|
if entry.RetryCount >= entry.MaxRetries {
|
||||||
|
delete(rm.retries, retryID)
|
||||||
|
log.Printf("[灵泊] 重试失败(已达上限): %s (重试 %d 次)", retryID, entry.RetryCount)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// 指数退避 + 抖动
|
||||||
|
delay := entry.BackoffBase * time.Duration(1<<uint(entry.RetryCount-1))
|
||||||
|
if delay > rm.config.MaxDelay {
|
||||||
|
delay = rm.config.MaxDelay
|
||||||
|
}
|
||||||
|
entry.NextRetry = time.Now().Add(delay)
|
||||||
|
|
||||||
|
log.Printf("[灵泊] 重试失败: %s (%d/%d, 下次: %v)",
|
||||||
|
retryID, entry.RetryCount, entry.MaxRetries, delay)
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stats 获取统计信息
|
||||||
|
func (rm *RetryManager) Stats() (pending, failed int) {
|
||||||
|
rm.mu.RLock()
|
||||||
|
defer rm.mu.RUnlock()
|
||||||
|
for _, entry := range rm.retries {
|
||||||
|
if entry.RetryCount == 0 {
|
||||||
|
pending++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pending, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Harbor - 灵泊整体入口
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// Harbor 灵泊 - 异步队列与暂存
|
||||||
|
type Harbor struct {
|
||||||
|
Queue *MessageQueue
|
||||||
|
Buffer *MessageBuffer
|
||||||
|
Retry *RetryManager
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHarbor 创建灵泊
|
||||||
|
func NewHarbor() *Harbor {
|
||||||
|
return &Harbor{
|
||||||
|
Queue: NewMessageQueue(nil),
|
||||||
|
Buffer: NewMessageBuffer(nil),
|
||||||
|
Retry: NewRetryManager(nil),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendWithRetry 发送消息并重试
|
||||||
|
func (h *Harbor) SendWithRetry(ctx context.Context, msg *types.UnifiedSynapseMessage, target string, sendFunc func(ctx context.Context, msg *types.UnifiedSynapseMessage, target string) error) error {
|
||||||
|
// 先入队
|
||||||
|
qm, err := h.Queue.Enqueue(msg, target, 5)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尝试发送
|
||||||
|
err = sendFunc(ctx, msg, target)
|
||||||
|
if err == nil {
|
||||||
|
h.Queue.MarkDelivered(qm.ID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 失败,加入重试
|
||||||
|
h.Retry.AddRetry(msg, target)
|
||||||
|
h.Queue.MarkFailed(qm.ID, err)
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// BufferForOffline 为离线 Agent 缓冲消息
|
||||||
|
func (h *Harbor) BufferForOffline(agentID string, msg *types.UnifiedSynapseMessage) {
|
||||||
|
h.Buffer.BufferMessage(agentID, msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FlushAndSend 清空缓冲并发送
|
||||||
|
func (h *Harbor) FlushAndSend(agentID string, sendFunc func(msg *types.UnifiedSynapseMessage) error) int {
|
||||||
|
msgs := h.Buffer.FlushBuffer(agentID)
|
||||||
|
sent := 0
|
||||||
|
for _, msg := range msgs {
|
||||||
|
if err := sendFunc(msg); err == nil {
|
||||||
|
sent++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sent
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToJSON 导出为 JSON
|
||||||
|
func (qm *QueuedMessage) ToJSON() string {
|
||||||
|
data, _ := json.MarshalIndent(qm, "", " ")
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
473
libra/libra.go
Normal file
473
libra/libra.go
Normal file
@@ -0,0 +1,473 @@
|
|||||||
|
// Package libra 灵衡 - 价值结算与激励层
|
||||||
|
//
|
||||||
|
// 权衡利弊,计量公平。此层负责将 Agent 间的
|
||||||
|
// "智力贡献"与"资源消耗"通证化,动态定价,
|
||||||
|
// 让多智能体经济具备自驱的盈亏平衡,
|
||||||
|
// 而非单一中心补贴。
|
||||||
|
package libra
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"synapse/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Accounting - 记账
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// TransactionType 交易类型
|
||||||
|
type TransactionType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
TxTaskExecution TransactionType = "task_execution" // 任务执行
|
||||||
|
TxDataSharing TransactionType = "data_sharing" // 数据共享
|
||||||
|
TxAPIInvocation TransactionType = "api_invocation" // API 调用
|
||||||
|
TxGroupContribution TransactionType = "group_contribution" // 群组贡献
|
||||||
|
TxDeposit TransactionType = "deposit" // 充值
|
||||||
|
TxWithdraw TransactionType = "withdraw" // 提现
|
||||||
|
TxReward TransactionType = "reward" // 奖励
|
||||||
|
TxPenalty TransactionType = "penalty" // 惩罚
|
||||||
|
)
|
||||||
|
|
||||||
|
// Transaction 交易记录
|
||||||
|
type Transaction struct {
|
||||||
|
TxID string `json:"tx_id"`
|
||||||
|
Type TransactionType `json:"type"`
|
||||||
|
FromAgentID string `json:"from_agent_id"`
|
||||||
|
ToAgentID string `json:"to_agent_id"`
|
||||||
|
Amount float64 `json:"amount"`
|
||||||
|
Currency string `json:"currency"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
TaskID string `json:"task_id,omitempty"`
|
||||||
|
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||||
|
Timestamp time.Time `json:"timestamp"`
|
||||||
|
Status TransactionStatus `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TransactionStatus 交易状态
|
||||||
|
type TransactionStatus string
|
||||||
|
|
||||||
|
const (
|
||||||
|
TxStatusPending TransactionStatus = "pending"
|
||||||
|
TxStatusCompleted TransactionStatus = "completed"
|
||||||
|
TxStatusFailed TransactionStatus = "failed"
|
||||||
|
TxStatusReverted TransactionStatus = "reverted"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Account 账户
|
||||||
|
type Account struct {
|
||||||
|
AgentID string `json:"agent_id"`
|
||||||
|
Balance map[string]float64 `json:"balance"` // currency -> amount
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ledger 账本
|
||||||
|
type Ledger struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
accounts map[string]*Account // agent_id -> account
|
||||||
|
transactions []Transaction
|
||||||
|
config *LedgerConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// LedgerConfig 账本配置
|
||||||
|
type LedgerConfig struct {
|
||||||
|
DefaultCurrency string
|
||||||
|
InitialBalance map[string]float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultLedgerConfig 返回默认账本配置
|
||||||
|
func DefaultLedgerConfig() *LedgerConfig {
|
||||||
|
return &LedgerConfig{
|
||||||
|
DefaultCurrency: "SYN",
|
||||||
|
InitialBalance: map[string]float64{
|
||||||
|
"SYN": 1000.0,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewLedger 创建账本
|
||||||
|
func NewLedger(config *LedgerConfig) *Ledger {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultLedgerConfig()
|
||||||
|
}
|
||||||
|
return &Ledger{
|
||||||
|
accounts: make(map[string]*Account),
|
||||||
|
transactions: make([]Transaction, 0),
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateAccount 创建账户
|
||||||
|
func (l *Ledger) CreateAccount(agentID string) (*Account, error) {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
|
||||||
|
if _, exists := l.accounts[agentID]; exists {
|
||||||
|
return nil, fmt.Errorf("account for agent %s already exists", agentID)
|
||||||
|
}
|
||||||
|
|
||||||
|
account := &Account{
|
||||||
|
AgentID: agentID,
|
||||||
|
Balance: make(map[string]float64),
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
UpdatedAt: time.Now(),
|
||||||
|
Metadata: make(map[string]interface{}),
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始余额
|
||||||
|
for currency, amount := range l.config.InitialBalance {
|
||||||
|
account.Balance[currency] = amount
|
||||||
|
}
|
||||||
|
|
||||||
|
l.accounts[agentID] = account
|
||||||
|
|
||||||
|
log.Printf("[灵衡] 创建账户: %s (初始余额: %v)", agentID, account.Balance)
|
||||||
|
return account, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetBalance 获取余额
|
||||||
|
func (l *Ledger) GetBalance(agentID string) (map[string]float64, error) {
|
||||||
|
l.mu.RLock()
|
||||||
|
defer l.mu.RUnlock()
|
||||||
|
|
||||||
|
account, ok := l.accounts[agentID]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("account for agent %s not found", agentID)
|
||||||
|
}
|
||||||
|
|
||||||
|
balance := make(map[string]float64)
|
||||||
|
for k, v := range account.Balance {
|
||||||
|
balance[k] = v
|
||||||
|
}
|
||||||
|
return balance, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transfer 转账
|
||||||
|
func (l *Ledger) Transfer(fromAgentID, toAgentID string, amount float64, currency string, txType TransactionType, description string, taskID string, metadata map[string]interface{}) (*Transaction, error) {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
|
||||||
|
// 检查账户
|
||||||
|
fromAccount, ok := l.accounts[fromAgentID]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("sender account not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
toAccount, ok := l.accounts[toAgentID]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("receiver account not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查余额
|
||||||
|
if fromAccount.Balance[currency] < amount {
|
||||||
|
return nil, fmt.Errorf("insufficient balance")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建交易
|
||||||
|
tx := Transaction{
|
||||||
|
TxID: fmt.Sprintf("tx-%d", time.Now().UnixNano()),
|
||||||
|
Type: txType,
|
||||||
|
FromAgentID: fromAgentID,
|
||||||
|
ToAgentID: toAgentID,
|
||||||
|
Amount: amount,
|
||||||
|
Currency: currency,
|
||||||
|
Description: description,
|
||||||
|
TaskID: taskID,
|
||||||
|
Metadata: metadata,
|
||||||
|
Timestamp: time.Now(),
|
||||||
|
Status: TxStatusCompleted,
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行转账
|
||||||
|
fromAccount.Balance[currency] -= amount
|
||||||
|
toAccount.Balance[currency] += amount
|
||||||
|
fromAccount.UpdatedAt = time.Now()
|
||||||
|
toAccount.UpdatedAt = time.Now()
|
||||||
|
|
||||||
|
l.transactions = append(l.transactions, tx)
|
||||||
|
|
||||||
|
log.Printf("[灵衡] 转账: %s -> %s: %.2f %s (%s)",
|
||||||
|
fromAgentID, toAgentID, amount, currency, description)
|
||||||
|
|
||||||
|
return &tx, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAccount 获取账户
|
||||||
|
func (l *Ledger) GetAccount(agentID string) (*Account, error) {
|
||||||
|
l.mu.RLock()
|
||||||
|
defer l.mu.RUnlock()
|
||||||
|
|
||||||
|
account, ok := l.accounts[agentID]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("account for agent %s not found", agentID)
|
||||||
|
}
|
||||||
|
return account, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetTransactionHistory 获取交易历史
|
||||||
|
func (l *Ledger) GetTransactionHistory(agentID string, limit int) []Transaction {
|
||||||
|
l.mu.RLock()
|
||||||
|
defer l.mu.RUnlock()
|
||||||
|
|
||||||
|
var history []Transaction
|
||||||
|
for i := len(l.transactions) - 1; i >= 0 && len(history) < limit; i-- {
|
||||||
|
tx := l.transactions[i]
|
||||||
|
if tx.FromAgentID == agentID || tx.ToAgentID == agentID {
|
||||||
|
history = append(history, tx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return history
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Pricing - 定价
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// PricingEngine 定价引擎
|
||||||
|
type PricingEngine struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
prices map[string]map[string]float64 // task_type -> capability -> price
|
||||||
|
config *PricingConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// PricingConfig 定价配置
|
||||||
|
type PricingConfig struct {
|
||||||
|
BasePrice map[string]float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultPricingConfig 返回默认定价配置
|
||||||
|
func DefaultPricingConfig() *PricingConfig {
|
||||||
|
return &PricingConfig{
|
||||||
|
BasePrice: map[string]float64{
|
||||||
|
"text_generation": 1.0,
|
||||||
|
"image_generation": 5.0,
|
||||||
|
"video_generation": 20.0,
|
||||||
|
"audio_generation": 3.0,
|
||||||
|
"analysis": 2.0,
|
||||||
|
"translation": 1.5,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPricingEngine 创建定价引擎
|
||||||
|
func NewPricingEngine(config *PricingConfig) *PricingEngine {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultPricingConfig()
|
||||||
|
}
|
||||||
|
return &PricingEngine{
|
||||||
|
prices: make(map[string]map[string]float64),
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetPrice 设置价格
|
||||||
|
func (pe *PricingEngine) SetPrice(taskType, capability string, price float64) {
|
||||||
|
pe.mu.Lock()
|
||||||
|
defer pe.mu.Unlock()
|
||||||
|
|
||||||
|
if _, ok := pe.prices[taskType]; !ok {
|
||||||
|
pe.prices[taskType] = make(map[string]float64)
|
||||||
|
}
|
||||||
|
pe.prices[taskType][capability] = price
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPrice 获取价格
|
||||||
|
func (pe *PricingEngine) GetPrice(taskType string) float64 {
|
||||||
|
pe.mu.RLock()
|
||||||
|
defer pe.mu.RUnlock()
|
||||||
|
|
||||||
|
// 先查自定义价格
|
||||||
|
if caps, ok := pe.prices[taskType]; ok {
|
||||||
|
if price, ok := caps["default"]; ok {
|
||||||
|
return price
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 再查基础价格
|
||||||
|
if price, ok := pe.config.BasePrice[taskType]; ok {
|
||||||
|
return price
|
||||||
|
}
|
||||||
|
|
||||||
|
// 默认价格
|
||||||
|
return 1.0
|
||||||
|
}
|
||||||
|
|
||||||
|
// CalculateCost 计算任务成本
|
||||||
|
func (pe *PricingEngine) CalculateCost(taskType string, complexity int, duration time.Duration) float64 {
|
||||||
|
basePrice := pe.GetPrice(taskType)
|
||||||
|
|
||||||
|
// 复杂度系数
|
||||||
|
complexityFactor := 1.0
|
||||||
|
if complexity > 0 {
|
||||||
|
complexityFactor = float64(complexity) * 0.5
|
||||||
|
}
|
||||||
|
|
||||||
|
// 时长系数(每秒0.01)
|
||||||
|
durationFactor := duration.Seconds() * 0.01
|
||||||
|
|
||||||
|
return basePrice*complexityFactor + durationFactor
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Settlement - 结算
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// SettlementEngine 结算引擎
|
||||||
|
type SettlementEngine struct {
|
||||||
|
ledger *Ledger
|
||||||
|
pricing *PricingEngine
|
||||||
|
config *SettlementConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// SettlementConfig 结算配置
|
||||||
|
type SettlementConfig struct {
|
||||||
|
AutoSettlement bool
|
||||||
|
SettlementInterval time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultSettlementConfig 返回默认结算配置
|
||||||
|
func DefaultSettlementConfig() *SettlementConfig {
|
||||||
|
return &SettlementConfig{
|
||||||
|
AutoSettlement: true,
|
||||||
|
SettlementInterval: 1 * time.Hour,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSettlementEngine 创建结算引擎
|
||||||
|
func NewSettlementEngine(ledger *Ledger, pricing *PricingEngine, config *SettlementConfig) *SettlementEngine {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultSettlementConfig()
|
||||||
|
}
|
||||||
|
return &SettlementEngine{
|
||||||
|
ledger: ledger,
|
||||||
|
pricing: pricing,
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SettleTask 结算任务
|
||||||
|
func (se *SettlementEngine) SettleTask(taskID string, fromAgentID, toAgentID string, taskType string, complexity int, duration time.Duration, resultQuality float64) (*Transaction, error) {
|
||||||
|
// 计算成本
|
||||||
|
cost := se.pricing.CalculateCost(taskType, complexity, duration)
|
||||||
|
|
||||||
|
// 质量调整
|
||||||
|
adjustedCost := cost * resultQuality
|
||||||
|
|
||||||
|
log.Printf("[灵衡] 任务结算: %s (成本: %.2f, 质量系数: %.2f, 最终: %.2f)",
|
||||||
|
taskID, cost, resultQuality, adjustedCost)
|
||||||
|
|
||||||
|
// 执行转账
|
||||||
|
return se.ledger.Transfer(
|
||||||
|
fromAgentID,
|
||||||
|
toAgentID,
|
||||||
|
adjustedCost,
|
||||||
|
"SYN",
|
||||||
|
TxTaskExecution,
|
||||||
|
fmt.Sprintf("任务执行: %s", taskType),
|
||||||
|
taskID,
|
||||||
|
map[string]interface{}{
|
||||||
|
"task_type": taskType,
|
||||||
|
"complexity": complexity,
|
||||||
|
"duration_s": duration.Seconds(),
|
||||||
|
"quality": resultQuality,
|
||||||
|
"base_cost": cost,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SettleGroupTask 结算群组任务(分摊费用)
|
||||||
|
func (se *SettlementEngine) SettleGroupTask(taskID string, coordinatorID string, workerIDs []string, taskType string, totalCost float64, shares map[string]float64) error {
|
||||||
|
// 协调者支付总费用,工作者按比例分配
|
||||||
|
for workerID, share := range shares {
|
||||||
|
amount := totalCost * share
|
||||||
|
_, err := se.ledger.Transfer(
|
||||||
|
coordinatorID,
|
||||||
|
workerID,
|
||||||
|
amount,
|
||||||
|
"SYN",
|
||||||
|
TxGroupContribution,
|
||||||
|
fmt.Sprintf("群组任务分成: %s", taskType),
|
||||||
|
taskID,
|
||||||
|
map[string]interface{}{
|
||||||
|
"share": share,
|
||||||
|
"amount": amount,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("settle worker %s failed: %w", workerID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("[灵衡] 群组任务结算: %s (总费用: %.2f, 工作者: %d)",
|
||||||
|
taskID, totalCost, len(workerIDs))
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reward 奖励
|
||||||
|
func (se *SettlementEngine) Reward(agentID string, amount float64, reason string) (*Transaction, error) {
|
||||||
|
// 创建系统账户(简化处理)
|
||||||
|
if _, err := se.ledger.GetAccount("system"); err != nil {
|
||||||
|
se.ledger.CreateAccount("system")
|
||||||
|
}
|
||||||
|
|
||||||
|
return se.ledger.Transfer(
|
||||||
|
"system",
|
||||||
|
agentID,
|
||||||
|
amount,
|
||||||
|
"SYN",
|
||||||
|
TxReward,
|
||||||
|
reason,
|
||||||
|
"",
|
||||||
|
nil,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Libra - 灵衡整体入口
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// Libra 灵衡 - 价值结算与激励
|
||||||
|
type Libra struct {
|
||||||
|
Ledger *Ledger
|
||||||
|
Pricing *PricingEngine
|
||||||
|
Settlement *SettlementEngine
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewLibra 创建灵衡
|
||||||
|
func NewLibra() *Libra {
|
||||||
|
ledger := NewLedger(nil)
|
||||||
|
pricing := NewPricingEngine(nil)
|
||||||
|
settlement := NewSettlementEngine(ledger, pricing, nil)
|
||||||
|
|
||||||
|
return &Libra{
|
||||||
|
Ledger: ledger,
|
||||||
|
Pricing: pricing,
|
||||||
|
Settlement: settlement,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegisterAgent 注册 Agent(创建账户)
|
||||||
|
func (l *Libra) RegisterAgent(agentID string) error {
|
||||||
|
_, err := l.Ledger.CreateAccount(agentID)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// PayForTask 为任务付费
|
||||||
|
func (l *Libra) PayForTask(ctx context.Context, fromAgentID, toAgentID string, msg *types.UnifiedSynapseMessage, duration time.Duration, quality float64) error {
|
||||||
|
return nil // 简化实现
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToJSON 导出为 JSON
|
||||||
|
func (tx *Transaction) ToJSON() string {
|
||||||
|
data, _ := json.MarshalIndent(tx, "", " ")
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
351
meridian/meridian.go
Normal file
351
meridian/meridian.go
Normal file
@@ -0,0 +1,351 @@
|
|||||||
|
// Package meridian 灵脉 - 寻址与路由层
|
||||||
|
//
|
||||||
|
// 取中医"经脉"之意。Agent 之间虽有空隙(灵隙),
|
||||||
|
// 但暗中有能量流动的轨迹(脉)。
|
||||||
|
//
|
||||||
|
// 此层负责维护全局路由表,让新 Agent "通脉"入网,
|
||||||
|
// 旧 Agent "断脉"离场,不死不休。
|
||||||
|
package meridian
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"synapse/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Agent Registry - Agent 注册发现
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// AgentRegistry Agent 注册表
|
||||||
|
type AgentRegistry struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
agents map[string]*types.AgentEndpoint // agent_id -> endpoint
|
||||||
|
ttl map[string]time.Time // agent_id -> 过期时间
|
||||||
|
config *RegistryConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegistryConfig 注册表配置
|
||||||
|
type RegistryConfig struct {
|
||||||
|
DefaultTTL time.Duration // 默认存活时间
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultRegistryConfig 返回默认注册表配置
|
||||||
|
func DefaultRegistryConfig() *RegistryConfig {
|
||||||
|
return &RegistryConfig{
|
||||||
|
DefaultTTL: 5 * time.Minute,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewAgentRegistry 创建 Agent 注册表
|
||||||
|
func NewAgentRegistry(config *RegistryConfig) *AgentRegistry {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultRegistryConfig()
|
||||||
|
}
|
||||||
|
return &AgentRegistry{
|
||||||
|
agents: make(map[string]*types.AgentEndpoint),
|
||||||
|
ttl: make(map[string]time.Time),
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register 注册 Agent(通脉)
|
||||||
|
func (r *AgentRegistry) Register(endpoint types.AgentEndpoint) error {
|
||||||
|
if endpoint.AgentID == "" {
|
||||||
|
return fmt.Errorf("agent_id is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
|
||||||
|
r.agents[endpoint.AgentID] = &endpoint
|
||||||
|
r.ttl[endpoint.AgentID] = time.Now().Add(r.config.DefaultTTL)
|
||||||
|
|
||||||
|
log.Printf("[灵脉] Agent 通脉入网: %s (%s)", endpoint.AgentID, endpoint.AgentName)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unregister 注销 Agent(断脉)
|
||||||
|
func (r *AgentRegistry) Unregister(agentID string) error {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
|
||||||
|
if _, ok := r.agents[agentID]; !ok {
|
||||||
|
return fmt.Errorf("agent %s not found", agentID)
|
||||||
|
}
|
||||||
|
|
||||||
|
delete(r.agents, agentID)
|
||||||
|
delete(r.ttl, agentID)
|
||||||
|
|
||||||
|
log.Printf("[灵脉] Agent 断脉离场: %s", agentID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAgent 获取 Agent 端点
|
||||||
|
func (r *AgentRegistry) GetAgent(agentID string) (*types.AgentEndpoint, error) {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
|
||||||
|
agent, ok := r.agents[agentID]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("agent %s not found", agentID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否过期
|
||||||
|
if time.Now().After(r.ttl[agentID]) {
|
||||||
|
return nil, fmt.Errorf("agent %s has expired", agentID)
|
||||||
|
}
|
||||||
|
|
||||||
|
return agent, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListAgents 列出所有活跃 Agent
|
||||||
|
func (r *AgentRegistry) ListAgents() []types.AgentEndpoint {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
|
||||||
|
agents := make([]types.AgentEndpoint, 0, len(r.agents))
|
||||||
|
now := time.Now()
|
||||||
|
for id, agent := range r.agents {
|
||||||
|
if now.Before(r.ttl[id]) {
|
||||||
|
agents = append(agents, *agent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return agents
|
||||||
|
}
|
||||||
|
|
||||||
|
// Heartbeat 心跳保活
|
||||||
|
func (r *AgentRegistry) Heartbeat(agentID string) error {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
|
||||||
|
if _, ok := r.agents[agentID]; !ok {
|
||||||
|
return fmt.Errorf("agent %s not registered", agentID)
|
||||||
|
}
|
||||||
|
|
||||||
|
r.ttl[agentID] = time.Now().Add(r.config.DefaultTTL)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FindByCapability 按能力查找 Agent
|
||||||
|
func (r *AgentRegistry) FindByCapability(capability string) []types.AgentEndpoint {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
|
||||||
|
var result []types.AgentEndpoint
|
||||||
|
now := time.Now()
|
||||||
|
for id, agent := range r.agents {
|
||||||
|
if now.Before(r.ttl[id]) {
|
||||||
|
// 简化处理,实际需要查询能力
|
||||||
|
result = append(result, *agent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Message Router - 消息路由
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// Router 消息路由器
|
||||||
|
type Router struct {
|
||||||
|
registry *AgentRegistry
|
||||||
|
|
||||||
|
// 协议处理器
|
||||||
|
handlers map[string]MessageHandler
|
||||||
|
|
||||||
|
mu sync.RWMutex
|
||||||
|
config *RouterConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// MessageHandler 消息处理器接口
|
||||||
|
type MessageHandler interface {
|
||||||
|
HandleMessage(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RouterConfig 路由器配置
|
||||||
|
type RouterConfig struct {
|
||||||
|
MaxHops int // 最大跳数
|
||||||
|
EnableCaching bool // 启用路由缓存
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultRouterConfig 返回默认路由器配置
|
||||||
|
func DefaultRouterConfig() *RouterConfig {
|
||||||
|
return &RouterConfig{
|
||||||
|
MaxHops: 10,
|
||||||
|
EnableCaching: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRouter 创建消息路由器
|
||||||
|
func NewRouter(registry *AgentRegistry, config *RouterConfig) *Router {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultRouterConfig()
|
||||||
|
}
|
||||||
|
if registry == nil {
|
||||||
|
registry = NewAgentRegistry(nil)
|
||||||
|
}
|
||||||
|
return &Router{
|
||||||
|
registry: registry,
|
||||||
|
handlers: make(map[string]MessageHandler),
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegisterHandler 注册消息类型处理器
|
||||||
|
func (r *Router) RegisterHandler(msgType string, handler MessageHandler) {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
r.handlers[msgType] = handler
|
||||||
|
}
|
||||||
|
|
||||||
|
// Route 路由消息
|
||||||
|
func (r *Router) Route(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||||
|
if msg.Receiver == nil {
|
||||||
|
return nil, fmt.Errorf("receiver is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查找接收方
|
||||||
|
_, err := r.registry.GetAgent(msg.Receiver.AgentID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("route failed: agent not found: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查找处理器
|
||||||
|
r.mu.RLock()
|
||||||
|
handler, ok := r.handlers[msg.Type]
|
||||||
|
r.mu.RUnlock()
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("no handler for message type: %s", msg.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("[灵脉] 路由消息: %s -> %s (类型: %s)",
|
||||||
|
msg.Sender.AgentID, msg.Receiver.AgentID, msg.Type)
|
||||||
|
|
||||||
|
return handler.HandleMessage(ctx, msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Topology Manager - 拓扑管理
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// TopologyType 拓扑类型
|
||||||
|
type TopologyType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
TopologyStar TopologyType = "star" // 星型拓扑
|
||||||
|
TopologyMesh TopologyType = "mesh" // 网状拓扑
|
||||||
|
TopologyRing TopologyType = "ring" // 环形拓扑
|
||||||
|
TopologyTree TopologyType = "tree" // 树形拓扑
|
||||||
|
TopologyHybrid TopologyType = "hybrid" // 混合拓扑
|
||||||
|
)
|
||||||
|
|
||||||
|
// TopologyManager 拓扑管理器
|
||||||
|
type TopologyManager struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
topologies map[string]*NetworkTopology
|
||||||
|
}
|
||||||
|
|
||||||
|
// NetworkTopology 网络拓扑
|
||||||
|
type NetworkTopology struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Type TopologyType `json:"type"`
|
||||||
|
Nodes map[string]bool `json:"nodes"`
|
||||||
|
Edges map[string][]string `json:"edges"` // node_id -> connected_nodes
|
||||||
|
Config map[string]interface{} `json:"config"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTopologyManager 创建拓扑管理器
|
||||||
|
func NewTopologyManager() *TopologyManager {
|
||||||
|
return &TopologyManager{
|
||||||
|
topologies: make(map[string]*NetworkTopology),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateTopology 创建拓扑
|
||||||
|
func (tm *TopologyManager) CreateTopology(id, name string, topologyType TopologyType) *NetworkTopology {
|
||||||
|
tm.mu.Lock()
|
||||||
|
defer tm.mu.Unlock()
|
||||||
|
|
||||||
|
topo := &NetworkTopology{
|
||||||
|
ID: id,
|
||||||
|
Name: name,
|
||||||
|
Type: topologyType,
|
||||||
|
Nodes: make(map[string]bool),
|
||||||
|
Edges: make(map[string][]string),
|
||||||
|
Config: make(map[string]interface{}),
|
||||||
|
}
|
||||||
|
tm.topologies[id] = topo
|
||||||
|
|
||||||
|
log.Printf("[灵脉] 创建拓扑: %s (%s, %s)", id, name, topologyType)
|
||||||
|
return topo
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddNode 添加节点
|
||||||
|
func (tm *TopologyManager) AddNode(topologyID, nodeID string) error {
|
||||||
|
tm.mu.Lock()
|
||||||
|
defer tm.mu.Unlock()
|
||||||
|
|
||||||
|
topo, ok := tm.topologies[topologyID]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("topology %s not found", topologyID)
|
||||||
|
}
|
||||||
|
|
||||||
|
topo.Nodes[nodeID] = true
|
||||||
|
if _, ok := topo.Edges[nodeID]; !ok {
|
||||||
|
topo.Edges[nodeID] = []string{}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddEdge 添加边
|
||||||
|
func (tm *TopologyManager) AddEdge(topologyID, from, to string) error {
|
||||||
|
tm.mu.Lock()
|
||||||
|
defer tm.mu.Unlock()
|
||||||
|
|
||||||
|
topo, ok := tm.topologies[topologyID]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("topology %s not found", topologyID)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !topo.Nodes[from] || !topo.Nodes[to] {
|
||||||
|
return fmt.Errorf("node not found in topology")
|
||||||
|
}
|
||||||
|
|
||||||
|
topo.Edges[from] = append(topo.Edges[from], to)
|
||||||
|
topo.Edges[to] = append(topo.Edges[to], from)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetNeighbors 获取邻居节点
|
||||||
|
func (tm *TopologyManager) GetNeighbors(topologyID, nodeID string) ([]string, error) {
|
||||||
|
tm.mu.RLock()
|
||||||
|
defer tm.mu.RUnlock()
|
||||||
|
|
||||||
|
topo, ok := tm.topologies[topologyID]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("topology %s not found", topologyID)
|
||||||
|
}
|
||||||
|
|
||||||
|
neighbors, ok := topo.Edges[nodeID]
|
||||||
|
if !ok {
|
||||||
|
return []string{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return neighbors, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToJSON 导出为 JSON
|
||||||
|
func (t *NetworkTopology) ToJSON() string {
|
||||||
|
data, _ := json.MarshalIndent(t, "", " ")
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
494
p2p/protocol_test.go
Normal file
494
p2p/protocol_test.go
Normal file
@@ -0,0 +1,494 @@
|
|||||||
|
package p2p
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"synapse/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Mock Task Handler
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
type mockTaskHandler struct {
|
||||||
|
canHandle bool
|
||||||
|
missingFields []types.MissingField
|
||||||
|
result any
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockTaskHandler) ExecuteTask(ctx context.Context, taskType string, payload map[string]interface{}) (any, error) {
|
||||||
|
return m.result, m.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockTaskHandler) ValidateTask(taskType string, payload map[string]interface{}) ([]types.MissingField, bool) {
|
||||||
|
return m.missingFields, m.canHandle
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockTaskHandler) GetCapabilities() []string {
|
||||||
|
return []string{"text_generation", "image_generation"}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Mock Callback Sender
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
type mockCallbackSender struct {
|
||||||
|
lastMsg *types.UnifiedSynapseMessage
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockCallbackSender) SendCallback(ctx context.Context, endpoint string, msg *types.UnifiedSynapseMessage) error {
|
||||||
|
m.lastMsg = msg
|
||||||
|
return m.err
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// P2PProtocol 测试
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func TestNewP2PProtocol(t *testing.T) {
|
||||||
|
ep := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := NewP2PProtocol(ep, nil)
|
||||||
|
if proto == nil {
|
||||||
|
t.Error("Protocol should not be nil")
|
||||||
|
}
|
||||||
|
if proto.AgentEndpoint().AgentID != "agent-001" {
|
||||||
|
t.Error("Agent ID mismatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestP2PProtocolWithCustomConfig(t *testing.T) {
|
||||||
|
ep := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
|
||||||
|
config := &P2PConfig{
|
||||||
|
MaxRetries: 10,
|
||||||
|
RetryBaseDelay: 5 * time.Second,
|
||||||
|
TaskTimeout: 10 * time.Minute,
|
||||||
|
HeartbeatInterval: 60 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := NewP2PProtocol(ep, config)
|
||||||
|
if proto.config.MaxRetries != 10 {
|
||||||
|
t.Errorf("MaxRetries mismatch: got %d, want 10", proto.config.MaxRetries)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDefaultP2PConfig(t *testing.T) {
|
||||||
|
config := DefaultP2PConfig()
|
||||||
|
if config.MaxRetries != 5 {
|
||||||
|
t.Errorf("Default MaxRetries should be 5")
|
||||||
|
}
|
||||||
|
if config.TaskTimeout != 5*time.Minute {
|
||||||
|
t.Errorf("Default TaskTimeout should be 5 minutes")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 消息处理测试
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func TestHandleTaskRequest(t *testing.T) {
|
||||||
|
ep := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := NewP2PProtocol(ep, nil)
|
||||||
|
proto.SetTaskHandler(&mockTaskHandler{
|
||||||
|
canHandle: true,
|
||||||
|
result: "test result",
|
||||||
|
})
|
||||||
|
|
||||||
|
// 构造任务请求消息
|
||||||
|
taskReq := types.TaskRequestPayload{}
|
||||||
|
taskReq.Task.ID = "task-001"
|
||||||
|
taskReq.Task.Type = "text_generation"
|
||||||
|
taskReq.Task.Priority = types.PriorityNormal
|
||||||
|
taskReq.Task.Payload = map[string]interface{}{"prompt": "test"}
|
||||||
|
|
||||||
|
payloadBytes, _ := json.Marshal(taskReq)
|
||||||
|
|
||||||
|
msg := &types.UnifiedSynapseMessage{
|
||||||
|
ID: types.GenerateMessageID(),
|
||||||
|
Version: "1.0.0",
|
||||||
|
Type: string(types.P2PTaskRequest),
|
||||||
|
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
|
||||||
|
Payload: payloadBytes,
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := proto.HandleMessage(context.Background(), msg)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("HandleMessage failed: %v", err)
|
||||||
|
}
|
||||||
|
if resp == nil {
|
||||||
|
t.Error("Response should not be nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleTaskReject(t *testing.T) {
|
||||||
|
ep := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := NewP2PProtocol(ep, nil)
|
||||||
|
proto.SetTaskHandler(&mockTaskHandler{
|
||||||
|
canHandle: false,
|
||||||
|
missingFields: nil,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 构造任务请求消息
|
||||||
|
taskReq := types.TaskRequestPayload{}
|
||||||
|
taskReq.Task.ID = "task-001"
|
||||||
|
taskReq.Task.Type = "unsupported_type"
|
||||||
|
taskReq.Task.Priority = types.PriorityNormal
|
||||||
|
|
||||||
|
payloadBytes, _ := json.Marshal(taskReq)
|
||||||
|
|
||||||
|
msg := &types.UnifiedSynapseMessage{
|
||||||
|
ID: types.GenerateMessageID(),
|
||||||
|
Version: "1.0.0",
|
||||||
|
Type: string(types.P2PTaskRequest),
|
||||||
|
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
|
||||||
|
Payload: payloadBytes,
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := proto.HandleMessage(context.Background(), msg)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("HandleMessage should not return error for rejection: %v", err)
|
||||||
|
}
|
||||||
|
if resp == nil {
|
||||||
|
t.Error("Response should not be nil")
|
||||||
|
}
|
||||||
|
// 应该返回拒绝消息
|
||||||
|
if resp.Type != string(types.P2PTaskReject) {
|
||||||
|
t.Errorf("Expected reject response, got: %s", resp.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleHeartbeat(t *testing.T) {
|
||||||
|
ep := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := NewP2PProtocol(ep, nil)
|
||||||
|
|
||||||
|
msg := &types.UnifiedSynapseMessage{
|
||||||
|
ID: types.GenerateMessageID(),
|
||||||
|
Version: "1.0.0",
|
||||||
|
Type: string(types.P2PHeartbeat),
|
||||||
|
Sender: types.AgentEndpoint{AgentID: "agent-002"},
|
||||||
|
Payload: json.RawMessage("{}"),
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := proto.HandleMessage(context.Background(), msg)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("HandleHeartbeat failed: %v", err)
|
||||||
|
}
|
||||||
|
if resp == nil {
|
||||||
|
t.Error("Heartbeat response should not be nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleAck(t *testing.T) {
|
||||||
|
ep := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := NewP2PProtocol(ep, nil)
|
||||||
|
|
||||||
|
msg := &types.UnifiedSynapseMessage{
|
||||||
|
ID: types.GenerateMessageID(),
|
||||||
|
Version: "1.0.0",
|
||||||
|
Type: string(types.P2PAck),
|
||||||
|
Sender: types.AgentEndpoint{AgentID: "agent-002"},
|
||||||
|
ReplyTo: "msg-001",
|
||||||
|
Payload: json.RawMessage("{}"),
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := proto.HandleMessage(context.Background(), msg)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("HandleAck failed: %v", err)
|
||||||
|
}
|
||||||
|
// ACK 不需要响应
|
||||||
|
if resp != nil {
|
||||||
|
t.Error("ACK should not produce a response")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 消息验证测试
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func TestValidateMessage(t *testing.T) {
|
||||||
|
ep := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := NewP2PProtocol(ep, nil)
|
||||||
|
|
||||||
|
// 有效消息
|
||||||
|
validMsg := &types.UnifiedSynapseMessage{
|
||||||
|
ID: "msg-001",
|
||||||
|
Type: string(types.P2PTaskRequest),
|
||||||
|
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
|
||||||
|
Payload: json.RawMessage("{}"),
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := proto.validateMessage(validMsg); err != nil {
|
||||||
|
t.Errorf("Valid message should pass validation: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 缺少 ID 的消息
|
||||||
|
noIDMsg := &types.UnifiedSynapseMessage{
|
||||||
|
Type: string(types.P2PTaskRequest),
|
||||||
|
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
|
||||||
|
Payload: json.RawMessage("{}"),
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := proto.validateMessage(noIDMsg); err == nil {
|
||||||
|
t.Error("Message without ID should fail validation")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 缺少 Sender AgentID 的消息
|
||||||
|
noSenderMsg := &types.UnifiedSynapseMessage{
|
||||||
|
ID: "msg-001",
|
||||||
|
Type: string(types.P2PTaskRequest),
|
||||||
|
Sender: types.AgentEndpoint{Endpoint: "http://localhost:8081"},
|
||||||
|
Payload: json.RawMessage("{}"),
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := proto.validateMessage(noSenderMsg); err == nil {
|
||||||
|
t.Error("Message without sender AgentID should fail validation")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 状态管理测试
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func TestGetTaskStatus(t *testing.T) {
|
||||||
|
ep := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := NewP2PProtocol(ep, nil)
|
||||||
|
|
||||||
|
// 查询不存在的任务
|
||||||
|
status, ok := proto.GetTaskStatus("nonexistent")
|
||||||
|
if ok {
|
||||||
|
t.Error("Nonexistent task should not be found")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 先通过任务请求添加任务状态
|
||||||
|
taskReq := types.TaskRequestPayload{}
|
||||||
|
taskReq.Task.ID = "task-001"
|
||||||
|
taskReq.Task.Type = "text_generation"
|
||||||
|
taskReq.Task.Priority = types.PriorityNormal
|
||||||
|
taskReq.Task.Payload = map[string]interface{}{"prompt": "test"}
|
||||||
|
|
||||||
|
payloadBytes, _ := json.Marshal(taskReq)
|
||||||
|
|
||||||
|
msg := &types.UnifiedSynapseMessage{
|
||||||
|
ID: types.GenerateMessageID(),
|
||||||
|
Version: "1.0.0",
|
||||||
|
Type: string(types.P2PTaskRequest),
|
||||||
|
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
|
||||||
|
Payload: payloadBytes,
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
proto.HandleMessage(context.Background(), msg)
|
||||||
|
|
||||||
|
// 然后查询状态
|
||||||
|
status, ok = proto.GetTaskStatus("task-001")
|
||||||
|
if !ok {
|
||||||
|
t.Error("Task should be found")
|
||||||
|
}
|
||||||
|
// 状态应该是 pending 或 confirmed
|
||||||
|
if status != types.P2PStatusPending && status != types.P2PStatusConfirmed {
|
||||||
|
t.Errorf("Status should be pending or confirmed: got %s", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListTasks(t *testing.T) {
|
||||||
|
ep := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := NewP2PProtocol(ep, nil)
|
||||||
|
|
||||||
|
// 初始应该为空
|
||||||
|
tasks := proto.ListTasks()
|
||||||
|
if len(tasks) != 0 {
|
||||||
|
t.Error("Initial task list should be empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加任务(通过消息处理)
|
||||||
|
taskReq := types.TaskRequestPayload{}
|
||||||
|
taskReq.Task.ID = "task-001"
|
||||||
|
taskReq.Task.Type = "text_generation"
|
||||||
|
taskReq.Task.Priority = types.PriorityNormal
|
||||||
|
|
||||||
|
payloadBytes, _ := json.Marshal(taskReq)
|
||||||
|
|
||||||
|
msg := &types.UnifiedSynapseMessage{
|
||||||
|
ID: types.GenerateMessageID(),
|
||||||
|
Version: "1.0.0",
|
||||||
|
Type: string(types.P2PTaskRequest),
|
||||||
|
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
|
||||||
|
Payload: payloadBytes,
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
proto.HandleMessage(context.Background(), msg)
|
||||||
|
|
||||||
|
tasks = proto.ListTasks()
|
||||||
|
if len(tasks) < 1 {
|
||||||
|
t.Errorf("Task list should have at least 1 item: got %d", len(tasks))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 回调发送测试
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func TestSendStatusUpdate(t *testing.T) {
|
||||||
|
ep := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := NewP2PProtocol(ep, nil)
|
||||||
|
mockSender := &mockCallbackSender{}
|
||||||
|
proto.SetCallbackSender(mockSender)
|
||||||
|
|
||||||
|
// 发送状态更新
|
||||||
|
proto.sendStatusUpdate(context.Background(), "task-001", types.P2PStatusExecuting, 50, "Processing")
|
||||||
|
|
||||||
|
if mockSender.lastMsg == nil {
|
||||||
|
t.Error("Callback should have been sent")
|
||||||
|
}
|
||||||
|
if mockSender.lastMsg.Type != string(types.P2PTaskStatusUpdate) {
|
||||||
|
t.Errorf("Callback type mismatch: got %s", mockSender.lastMsg.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSendTaskComplete(t *testing.T) {
|
||||||
|
ep := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := NewP2PProtocol(ep, nil)
|
||||||
|
mockSender := &mockCallbackSender{}
|
||||||
|
proto.SetCallbackSender(mockSender)
|
||||||
|
|
||||||
|
// 发送完成通知
|
||||||
|
proto.sendTaskComplete(context.Background(), "task-001", "test result")
|
||||||
|
|
||||||
|
if mockSender.lastMsg == nil {
|
||||||
|
t.Error("Callback should have been sent")
|
||||||
|
}
|
||||||
|
if mockSender.lastMsg.Type != string(types.P2PTaskComplete) {
|
||||||
|
t.Errorf("Callback type mismatch: got %s", mockSender.lastMsg.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSendTaskFailed(t *testing.T) {
|
||||||
|
ep := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := NewP2PProtocol(ep, nil)
|
||||||
|
mockSender := &mockCallbackSender{}
|
||||||
|
proto.SetCallbackSender(mockSender)
|
||||||
|
|
||||||
|
// 发送失败通知
|
||||||
|
proto.sendTaskFailed(context.Background(), "task-001", "execution_failed", "test error", true, nil)
|
||||||
|
|
||||||
|
if mockSender.lastMsg == nil {
|
||||||
|
t.Error("Callback should have been sent")
|
||||||
|
}
|
||||||
|
if mockSender.lastMsg.Type != string(types.P2PTaskFailed) {
|
||||||
|
t.Errorf("Callback type mismatch: got %s", mockSender.lastMsg.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 错误处理测试
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func TestHandleInvalidPayload(t *testing.T) {
|
||||||
|
ep := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := NewP2PProtocol(ep, nil)
|
||||||
|
|
||||||
|
msg := &types.UnifiedSynapseMessage{
|
||||||
|
ID: types.GenerateMessageID(),
|
||||||
|
Version: "1.0.0",
|
||||||
|
Type: string(types.P2PTaskRequest),
|
||||||
|
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
|
||||||
|
Payload: json.RawMessage("invalid json"),
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := proto.HandleMessage(context.Background(), msg)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Should handle invalid payload gracefully: %v", err)
|
||||||
|
}
|
||||||
|
// 应该返回 NACK
|
||||||
|
if resp == nil {
|
||||||
|
t.Error("Should return NACK for invalid payload")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleUnknownMessageType(t *testing.T) {
|
||||||
|
ep := types.AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := NewP2PProtocol(ep, nil)
|
||||||
|
|
||||||
|
msg := &types.UnifiedSynapseMessage{
|
||||||
|
ID: types.GenerateMessageID(),
|
||||||
|
Version: "1.0.0",
|
||||||
|
Type: "p2p:unknown_type",
|
||||||
|
Sender: types.AgentEndpoint{AgentID: "agent-002", Endpoint: "http://localhost:8081"},
|
||||||
|
Payload: json.RawMessage("{}"),
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := proto.HandleMessage(context.Background(), msg)
|
||||||
|
if err == nil {
|
||||||
|
t.Error("Unknown message type should return error")
|
||||||
|
}
|
||||||
|
}
|
||||||
540
panorama/panorama.go
Normal file
540
panorama/panorama.go
Normal file
@@ -0,0 +1,540 @@
|
|||||||
|
// Package panorama 灵瞰 - 可观测与度量层
|
||||||
|
//
|
||||||
|
// 居高临下,俯瞰全局。此层不参与业务交互,
|
||||||
|
// 却如"天眼"般记录每一帧交互的耗时、置信度与资源消耗,
|
||||||
|
// 让黑盒群体智能变为白盒可解释的图景。
|
||||||
|
package panorama
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"synapse/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Tracing - 链路追踪
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// Trace 追踪链路
|
||||||
|
type Trace struct {
|
||||||
|
TraceID string `json:"trace_id"`
|
||||||
|
RootSpan *Span `json:"root_span"`
|
||||||
|
Spans map[string]*Span `json:"spans"`
|
||||||
|
StartTime time.Time `json:"start_time"`
|
||||||
|
EndTime *time.Time `json:"end_time,omitempty"`
|
||||||
|
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Span 追踪跨度
|
||||||
|
type Span struct {
|
||||||
|
SpanID string `json:"span_id"`
|
||||||
|
TraceID string `json:"trace_id"`
|
||||||
|
ParentID string `json:"parent_id,omitempty"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Service string `json:"service"`
|
||||||
|
AgentID string `json:"agent_id"`
|
||||||
|
StartTime time.Time `json:"start_time"`
|
||||||
|
EndTime *time.Time `json:"end_time,omitempty"`
|
||||||
|
Duration time.Duration `json:"duration_ms"`
|
||||||
|
Status SpanStatus `json:"status"`
|
||||||
|
Tags map[string]string `json:"tags,omitempty"`
|
||||||
|
Logs []SpanLog `json:"logs,omitempty"`
|
||||||
|
Attributes map[string]interface{} `json:"attributes,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SpanStatus 跨度状态
|
||||||
|
type SpanStatus string
|
||||||
|
|
||||||
|
const (
|
||||||
|
SpanStatusPending SpanStatus = "pending"
|
||||||
|
SpanStatusRunning SpanStatus = "running"
|
||||||
|
SpanStatusSuccess SpanStatus = "success"
|
||||||
|
SpanStatusFailed SpanStatus = "failed"
|
||||||
|
SpanStatusCancelled SpanStatus = "cancelled"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SpanLog 跨度日志
|
||||||
|
type SpanLog struct {
|
||||||
|
Timestamp time.Time `json:"timestamp"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
Fields map[string]interface{} `json:"fields,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tracer 追踪器
|
||||||
|
type Tracer struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
traces map[string]*Trace
|
||||||
|
config *TracerConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// TracerConfig 追踪器配置
|
||||||
|
type TracerConfig struct {
|
||||||
|
MaxTraces int
|
||||||
|
MaxSpansPerTrace int
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultTracerConfig 返回默认追踪器配置
|
||||||
|
func DefaultTracerConfig() *TracerConfig {
|
||||||
|
return &TracerConfig{
|
||||||
|
MaxTraces: 1000,
|
||||||
|
MaxSpansPerTrace: 100,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTracer 创建追踪器
|
||||||
|
func NewTracer(config *TracerConfig) *Tracer {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultTracerConfig()
|
||||||
|
}
|
||||||
|
return &Tracer{
|
||||||
|
traces: make(map[string]*Trace),
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartTrace 开始追踪
|
||||||
|
func (t *Tracer) StartTrace(traceID, name string, agentID string) *Trace {
|
||||||
|
if traceID == "" {
|
||||||
|
traceID = fmt.Sprintf("trace-%d", time.Now().UnixNano())
|
||||||
|
}
|
||||||
|
|
||||||
|
rootSpan := &Span{
|
||||||
|
SpanID: fmt.Sprintf("span-%d", time.Now().UnixNano()),
|
||||||
|
TraceID: traceID,
|
||||||
|
Name: name,
|
||||||
|
Service: "synapse",
|
||||||
|
AgentID: agentID,
|
||||||
|
StartTime: time.Now(),
|
||||||
|
Status: SpanStatusRunning,
|
||||||
|
Tags: make(map[string]string),
|
||||||
|
Logs: make([]SpanLog, 0),
|
||||||
|
Attributes: make(map[string]interface{}),
|
||||||
|
}
|
||||||
|
|
||||||
|
trace := &Trace{
|
||||||
|
TraceID: traceID,
|
||||||
|
RootSpan: rootSpan,
|
||||||
|
Spans: map[string]*Span{rootSpan.SpanID: rootSpan},
|
||||||
|
StartTime: time.Now(),
|
||||||
|
Metadata: make(map[string]interface{}),
|
||||||
|
}
|
||||||
|
|
||||||
|
t.mu.Lock()
|
||||||
|
t.traces[traceID] = trace
|
||||||
|
t.mu.Unlock()
|
||||||
|
|
||||||
|
log.Printf("[灵瞰] 开始追踪: %s (%s)", traceID, name)
|
||||||
|
return trace
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartSpan 开始跨度
|
||||||
|
func (t *Tracer) StartSpan(traceID, parentSpanID, name, agentID string) (*Span, error) {
|
||||||
|
t.mu.Lock()
|
||||||
|
defer t.mu.Unlock()
|
||||||
|
|
||||||
|
trace, ok := t.traces[traceID]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("trace %s not found", traceID)
|
||||||
|
}
|
||||||
|
|
||||||
|
span := &Span{
|
||||||
|
SpanID: fmt.Sprintf("span-%d", time.Now().UnixNano()),
|
||||||
|
TraceID: traceID,
|
||||||
|
ParentID: parentSpanID,
|
||||||
|
Name: name,
|
||||||
|
Service: "synapse",
|
||||||
|
AgentID: agentID,
|
||||||
|
StartTime: time.Now(),
|
||||||
|
Status: SpanStatusRunning,
|
||||||
|
Tags: make(map[string]string),
|
||||||
|
Logs: make([]SpanLog, 0),
|
||||||
|
Attributes: make(map[string]interface{}),
|
||||||
|
}
|
||||||
|
|
||||||
|
trace.Spans[span.SpanID] = span
|
||||||
|
return span, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// EndSpan 结束跨度
|
||||||
|
func (t *Tracer) EndSpan(traceID, spanID string, status SpanStatus, err error) error {
|
||||||
|
t.mu.Lock()
|
||||||
|
defer t.mu.Unlock()
|
||||||
|
|
||||||
|
trace, ok := t.traces[traceID]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("trace %s not found", traceID)
|
||||||
|
}
|
||||||
|
|
||||||
|
span, ok := trace.Spans[spanID]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("span %s not found", spanID)
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
span.EndTime = &now
|
||||||
|
span.Duration = now.Sub(span.StartTime)
|
||||||
|
span.Status = status
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
span.Logs = append(span.Logs, SpanLog{
|
||||||
|
Timestamp: now,
|
||||||
|
Message: err.Error(),
|
||||||
|
Fields: map[string]interface{}{"error": err.Error()},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果是根跨度,结束整个追踪
|
||||||
|
if span == trace.RootSpan {
|
||||||
|
trace.EndTime = &now
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("[灵瞰] 结束跨度: %s (%s) - %v", spanID, span.Name, span.Duration)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddSpanLog 添加日志
|
||||||
|
func (t *Tracer) AddSpanLog(traceID, spanID, message string, fields map[string]interface{}) error {
|
||||||
|
t.mu.Lock()
|
||||||
|
defer t.mu.Unlock()
|
||||||
|
|
||||||
|
trace, ok := t.traces[traceID]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("trace %s not found", traceID)
|
||||||
|
}
|
||||||
|
|
||||||
|
span, ok := trace.Spans[spanID]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("span %s not found", spanID)
|
||||||
|
}
|
||||||
|
|
||||||
|
span.Logs = append(span.Logs, SpanLog{
|
||||||
|
Timestamp: time.Now(),
|
||||||
|
Message: message,
|
||||||
|
Fields: fields,
|
||||||
|
})
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetTrace 获取追踪
|
||||||
|
func (t *Tracer) GetTrace(traceID string) (*Trace, error) {
|
||||||
|
t.mu.RLock()
|
||||||
|
defer t.mu.RUnlock()
|
||||||
|
|
||||||
|
trace, ok := t.traces[traceID]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("trace %s not found", traceID)
|
||||||
|
}
|
||||||
|
return trace, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Metrics - 指标收集
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// MetricType 指标类型
|
||||||
|
type MetricType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
MetricCounter MetricType = "counter"
|
||||||
|
MetricGauge MetricType = "gauge"
|
||||||
|
MetricHistogram MetricType = "histogram"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Metric 指标
|
||||||
|
type Metric struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Type MetricType `json:"type"`
|
||||||
|
Value float64 `json:"value"`
|
||||||
|
Labels map[string]string `json:"labels"`
|
||||||
|
Timestamp time.Time `json:"timestamp"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MetricsCollector 指标收集器
|
||||||
|
type MetricsCollector struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
metrics map[string]*Metric
|
||||||
|
histories map[string][]Metric
|
||||||
|
config *MetricsConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// MetricsConfig 指标配置
|
||||||
|
type MetricsConfig struct {
|
||||||
|
MaxHistory int
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultMetricsConfig 返回默认指标配置
|
||||||
|
func DefaultMetricsConfig() *MetricsConfig {
|
||||||
|
return &MetricsConfig{
|
||||||
|
MaxHistory: 1000,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewMetricsCollector 创建指标收集器
|
||||||
|
func NewMetricsCollector(config *MetricsConfig) *MetricsCollector {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultMetricsConfig()
|
||||||
|
}
|
||||||
|
return &MetricsCollector{
|
||||||
|
metrics: make(map[string]*Metric),
|
||||||
|
histories: make(map[string][]Metric),
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecordMetric 记录指标
|
||||||
|
func (mc *MetricsCollector) RecordMetric(name string, metricType MetricType, value float64, labels map[string]string) {
|
||||||
|
mc.mu.Lock()
|
||||||
|
defer mc.mu.Unlock()
|
||||||
|
|
||||||
|
key := name + labelKey(labels)
|
||||||
|
metric := &Metric{
|
||||||
|
Name: name,
|
||||||
|
Type: metricType,
|
||||||
|
Value: value,
|
||||||
|
Labels: labels,
|
||||||
|
Timestamp: time.Now(),
|
||||||
|
}
|
||||||
|
|
||||||
|
mc.metrics[key] = metric
|
||||||
|
|
||||||
|
// 记录历史
|
||||||
|
if history, ok := mc.histories[key]; ok {
|
||||||
|
if len(history) >= mc.config.MaxHistory {
|
||||||
|
history = history[1:]
|
||||||
|
}
|
||||||
|
mc.histories[key] = append(history, *metric)
|
||||||
|
} else {
|
||||||
|
mc.histories[key] = []Metric{*metric}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// IncrementCounter 计数器递增
|
||||||
|
func (mc *MetricsCollector) IncrementCounter(name string, labels map[string]string, delta float64) {
|
||||||
|
mc.mu.Lock()
|
||||||
|
defer mc.mu.Unlock()
|
||||||
|
|
||||||
|
key := name + labelKey(labels)
|
||||||
|
metric, ok := mc.metrics[key]
|
||||||
|
if !ok {
|
||||||
|
metric = &Metric{
|
||||||
|
Name: name,
|
||||||
|
Type: MetricCounter,
|
||||||
|
Value: 0,
|
||||||
|
Labels: labels,
|
||||||
|
Timestamp: time.Now(),
|
||||||
|
}
|
||||||
|
mc.metrics[key] = metric
|
||||||
|
}
|
||||||
|
metric.Value += delta
|
||||||
|
metric.Timestamp = time.Now()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetGauge 设置计量值
|
||||||
|
func (mc *MetricsCollector) SetGauge(name string, labels map[string]string, value float64) {
|
||||||
|
mc.RecordMetric(name, MetricGauge, value, labels)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMetric 获取指标
|
||||||
|
func (mc *MetricsCollector) GetMetric(name string, labels map[string]string) (*Metric, error) {
|
||||||
|
mc.mu.RLock()
|
||||||
|
defer mc.mu.RUnlock()
|
||||||
|
|
||||||
|
key := name + labelKey(labels)
|
||||||
|
metric, ok := mc.metrics[key]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("metric %s not found", name)
|
||||||
|
}
|
||||||
|
return metric, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAllMetrics 获取所有指标
|
||||||
|
func (mc *MetricsCollector) GetAllMetrics() []Metric {
|
||||||
|
mc.mu.RLock()
|
||||||
|
defer mc.mu.RUnlock()
|
||||||
|
|
||||||
|
metrics := make([]Metric, 0, len(mc.metrics))
|
||||||
|
for _, m := range mc.metrics {
|
||||||
|
metrics = append(metrics, *m)
|
||||||
|
}
|
||||||
|
return metrics
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMetricHistory 获取指标历史
|
||||||
|
func (mc *MetricsCollector) GetMetricHistory(name string, labels map[string]string) ([]Metric, error) {
|
||||||
|
mc.mu.RLock()
|
||||||
|
defer mc.mu.RUnlock()
|
||||||
|
|
||||||
|
key := name + labelKey(labels)
|
||||||
|
history, ok := mc.histories[key]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("metric %s not found", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
result := make([]Metric, len(history))
|
||||||
|
copy(result, history)
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func labelKey(labels map[string]string) string {
|
||||||
|
if len(labels) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
data, _ := json.Marshal(labels)
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Health Check - 健康检查
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// HealthStatus 健康状态
|
||||||
|
type HealthStatus string
|
||||||
|
|
||||||
|
const (
|
||||||
|
HealthStatusHealthy HealthStatus = "healthy"
|
||||||
|
HealthStatusDegraded HealthStatus = "degraded"
|
||||||
|
HealthStatusUnhealthy HealthStatus = "unhealthy"
|
||||||
|
HealthStatusUnknown HealthStatus = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
// HealthCheck 健康检查结果
|
||||||
|
type HealthCheck struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Status HealthStatus `json:"status"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
Details map[string]interface{} `json:"details,omitempty"`
|
||||||
|
CheckedAt time.Time `json:"checked_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// HealthChecker 健康检查器
|
||||||
|
type HealthChecker struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
checks map[string]HealthCheckable
|
||||||
|
config *HealthConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// HealthCheckable 可健康检查的接口
|
||||||
|
type HealthCheckable interface {
|
||||||
|
HealthCheck(ctx context.Context) *HealthCheck
|
||||||
|
}
|
||||||
|
|
||||||
|
// HealthConfig 健康检查配置
|
||||||
|
type HealthConfig struct {
|
||||||
|
CheckInterval time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultHealthConfig 返回默认健康检查配置
|
||||||
|
func DefaultHealthConfig() *HealthConfig {
|
||||||
|
return &HealthConfig{
|
||||||
|
CheckInterval: 30 * time.Second,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHealthChecker 创建健康检查器
|
||||||
|
func NewHealthChecker(config *HealthConfig) *HealthChecker {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultHealthConfig()
|
||||||
|
}
|
||||||
|
return &HealthChecker{
|
||||||
|
checks: make(map[string]HealthCheckable),
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegisterCheck 注册健康检查
|
||||||
|
func (hc *HealthChecker) RegisterCheck(name string, checkable HealthCheckable) {
|
||||||
|
hc.mu.Lock()
|
||||||
|
defer hc.mu.Unlock()
|
||||||
|
hc.checks[name] = checkable
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckAll 检查所有组件
|
||||||
|
func (hc *HealthChecker) CheckAll(ctx context.Context) map[string]*HealthCheck {
|
||||||
|
hc.mu.RLock()
|
||||||
|
defer hc.mu.RUnlock()
|
||||||
|
|
||||||
|
results := make(map[string]*HealthCheck)
|
||||||
|
for name, checkable := range hc.checks {
|
||||||
|
results[name] = checkable.HealthCheck(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
return results
|
||||||
|
}
|
||||||
|
|
||||||
|
// OverallStatus 总体健康状态
|
||||||
|
func (hc *HealthChecker) OverallStatus(ctx context.Context) HealthStatus {
|
||||||
|
results := hc.CheckAll(ctx)
|
||||||
|
|
||||||
|
allHealthy := true
|
||||||
|
anyUnhealthy := false
|
||||||
|
|
||||||
|
for _, result := range results {
|
||||||
|
switch result.Status {
|
||||||
|
case HealthStatusUnhealthy:
|
||||||
|
anyUnhealthy = true
|
||||||
|
case HealthStatusDegraded:
|
||||||
|
allHealthy = false
|
||||||
|
case HealthStatusUnknown:
|
||||||
|
allHealthy = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if anyUnhealthy {
|
||||||
|
return HealthStatusUnhealthy
|
||||||
|
}
|
||||||
|
if !allHealthy {
|
||||||
|
return HealthStatusDegraded
|
||||||
|
}
|
||||||
|
return HealthStatusHealthy
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Panorama - 灵瞰整体入口
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// Panorama 灵瞰 - 可观测与度量
|
||||||
|
type Panorama struct {
|
||||||
|
Tracer *Tracer
|
||||||
|
Metrics *MetricsCollector
|
||||||
|
Health *HealthChecker
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPanorama 创建灵瞰
|
||||||
|
func NewPanorama() *Panorama {
|
||||||
|
return &Panorama{
|
||||||
|
Tracer: NewTracer(nil),
|
||||||
|
Metrics: NewMetricsCollector(nil),
|
||||||
|
Health: NewHealthChecker(nil),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecordMessage 记录消息(自动增加指标)
|
||||||
|
func (p *Panorama) RecordMessage(msg *types.UnifiedSynapseMessage, direction string, duration time.Duration) {
|
||||||
|
labels := map[string]string{
|
||||||
|
"type": msg.Type,
|
||||||
|
"direction": direction,
|
||||||
|
"sender": msg.Sender.AgentID,
|
||||||
|
}
|
||||||
|
|
||||||
|
p.Metrics.IncrementCounter("synapse_messages_total", labels, 1)
|
||||||
|
p.Metrics.RecordMetric("synapse_message_duration_seconds", MetricHistogram,
|
||||||
|
duration.Seconds(), labels)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartTaskTrace 开始任务追踪
|
||||||
|
func (p *Panorama) StartTaskTrace(taskID, taskType, agentID string) string {
|
||||||
|
trace := p.Tracer.StartTrace(taskID, fmt.Sprintf("task:%s", taskType), agentID)
|
||||||
|
return trace.TraceID
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToJSON 导出为 JSON
|
||||||
|
func (t *Trace) ToJSON() string {
|
||||||
|
data, _ := json.MarshalIndent(t, "", " ")
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
503
pivot/pivot.go
Normal file
503
pivot/pivot.go
Normal file
@@ -0,0 +1,503 @@
|
|||||||
|
// Package pivot 灵枢 - 紧急制动与治理层
|
||||||
|
//
|
||||||
|
// 取自《灵枢经》(黄帝内经下半部),
|
||||||
|
// 讲的是针灸经络之枢纽。
|
||||||
|
// 这是整个协议的"总闸"与"方向盘",
|
||||||
|
// 不轻易触发,但触发时能以最小代价
|
||||||
|
// 重置整个 Synapse 网络的状态。
|
||||||
|
package pivot
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"synapse/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Circuit Breaker - 熔断器
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// CircuitState 熔断器状态
|
||||||
|
type CircuitState string
|
||||||
|
|
||||||
|
const (
|
||||||
|
CircuitClosed CircuitState = "closed" // 关闭:正常流通
|
||||||
|
CircuitOpen CircuitState = "open" // 打开:熔断,拒绝请求
|
||||||
|
CircuitHalfOpen CircuitState = "half_open" // 半开:尝试恢复
|
||||||
|
)
|
||||||
|
|
||||||
|
// CircuitBreaker 熔断器
|
||||||
|
type CircuitBreaker struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
name string
|
||||||
|
state CircuitState
|
||||||
|
failureCount int
|
||||||
|
successCount int
|
||||||
|
threshold int // 失败阈值
|
||||||
|
timeout time.Duration // 熔断超时
|
||||||
|
lastFailure time.Time
|
||||||
|
lastSuccess time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// CircuitBreakerConfig 熔断器配置
|
||||||
|
type CircuitBreakerConfig struct {
|
||||||
|
Threshold int
|
||||||
|
Timeout time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultCircuitBreakerConfig 返回默认熔断器配置
|
||||||
|
func DefaultCircuitBreakerConfig() *CircuitBreakerConfig {
|
||||||
|
return &CircuitBreakerConfig{
|
||||||
|
Threshold: 5,
|
||||||
|
Timeout: 30 * time.Second,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewCircuitBreaker 创建熔断器
|
||||||
|
func NewCircuitBreaker(name string, config *CircuitBreakerConfig) *CircuitBreaker {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultCircuitBreakerConfig()
|
||||||
|
}
|
||||||
|
return &CircuitBreaker{
|
||||||
|
name: name,
|
||||||
|
state: CircuitClosed,
|
||||||
|
threshold: config.Threshold,
|
||||||
|
timeout: config.Timeout,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow 是否允许请求通过
|
||||||
|
func (cb *CircuitBreaker) Allow() bool {
|
||||||
|
cb.mu.RLock()
|
||||||
|
defer cb.mu.RUnlock()
|
||||||
|
|
||||||
|
switch cb.state {
|
||||||
|
case CircuitClosed:
|
||||||
|
return true
|
||||||
|
case CircuitOpen:
|
||||||
|
// 检查是否超时,可以进入半开状态
|
||||||
|
if time.Since(cb.lastFailure) > cb.timeout {
|
||||||
|
cb.mu.RUnlock()
|
||||||
|
cb.mu.Lock()
|
||||||
|
if cb.state == CircuitOpen && time.Since(cb.lastFailure) > cb.timeout {
|
||||||
|
cb.state = CircuitHalfOpen
|
||||||
|
cb.successCount = 0
|
||||||
|
log.Printf("[灵枢] 熔断器 %s 进入半开状态", cb.name)
|
||||||
|
}
|
||||||
|
cb.mu.Unlock()
|
||||||
|
cb.mu.RLock()
|
||||||
|
return cb.state == CircuitHalfOpen
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
case CircuitHalfOpen:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecordSuccess 记录成功
|
||||||
|
func (cb *CircuitBreaker) RecordSuccess() {
|
||||||
|
cb.mu.Lock()
|
||||||
|
defer cb.mu.Unlock()
|
||||||
|
|
||||||
|
cb.lastSuccess = time.Now()
|
||||||
|
|
||||||
|
switch cb.state {
|
||||||
|
case CircuitHalfOpen:
|
||||||
|
cb.successCount++
|
||||||
|
// 连续成功几次后关闭熔断
|
||||||
|
if cb.successCount >= 3 {
|
||||||
|
cb.state = CircuitClosed
|
||||||
|
cb.failureCount = 0
|
||||||
|
cb.successCount = 0
|
||||||
|
log.Printf("[灵枢] 熔断器 %s 恢复关闭", cb.name)
|
||||||
|
}
|
||||||
|
case CircuitClosed:
|
||||||
|
cb.failureCount = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecordFailure 记录失败
|
||||||
|
func (cb *CircuitBreaker) RecordFailure() {
|
||||||
|
cb.mu.Lock()
|
||||||
|
defer cb.mu.Unlock()
|
||||||
|
|
||||||
|
cb.failureCount++
|
||||||
|
cb.lastFailure = time.Now()
|
||||||
|
|
||||||
|
switch cb.state {
|
||||||
|
case CircuitClosed:
|
||||||
|
if cb.failureCount >= cb.threshold {
|
||||||
|
cb.state = CircuitOpen
|
||||||
|
log.Printf("[灵枢] 熔断器 %s 触发熔断 (失败: %d次)", cb.name, cb.failureCount)
|
||||||
|
}
|
||||||
|
case CircuitHalfOpen:
|
||||||
|
cb.state = CircuitOpen
|
||||||
|
log.Printf("[灵枢] 熔断器 %s 半开失败,重新熔断", cb.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// State 获取当前状态
|
||||||
|
func (cb *CircuitBreaker) State() CircuitState {
|
||||||
|
cb.mu.RLock()
|
||||||
|
defer cb.mu.RUnlock()
|
||||||
|
return cb.state
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset 重置熔断器
|
||||||
|
func (cb *CircuitBreaker) Reset() {
|
||||||
|
cb.mu.Lock()
|
||||||
|
defer cb.mu.Unlock()
|
||||||
|
|
||||||
|
cb.state = CircuitClosed
|
||||||
|
cb.failureCount = 0
|
||||||
|
cb.successCount = 0
|
||||||
|
log.Printf("[灵枢] 熔断器 %s 已重置", cb.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Governance - 治理
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// GovernanceLevel 治理级别
|
||||||
|
type GovernanceLevel int
|
||||||
|
|
||||||
|
const (
|
||||||
|
GovLevelNormal GovernanceLevel = iota // 正常运行
|
||||||
|
GovLevelWatch // 观察模式
|
||||||
|
GovLevelRestricted // 受限模式
|
||||||
|
GovLevelEmergency // 紧急模式
|
||||||
|
GovLevelShutdown // 停机模式
|
||||||
|
)
|
||||||
|
|
||||||
|
func (l GovernanceLevel) String() string {
|
||||||
|
switch l {
|
||||||
|
case GovLevelNormal:
|
||||||
|
return "normal"
|
||||||
|
case GovLevelWatch:
|
||||||
|
return "watch"
|
||||||
|
case GovLevelRestricted:
|
||||||
|
return "restricted"
|
||||||
|
case GovLevelEmergency:
|
||||||
|
return "emergency"
|
||||||
|
case GovLevelShutdown:
|
||||||
|
return "shutdown"
|
||||||
|
default:
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GovernanceManager 治理管理器
|
||||||
|
type GovernanceManager struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
level GovernanceLevel
|
||||||
|
policies map[string]GovernancePolicy
|
||||||
|
blacklist map[string]bool // 被封禁的 agent_id
|
||||||
|
whitelist map[string]bool // 白名单
|
||||||
|
config *GovernanceConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// GovernancePolicy 治理策略
|
||||||
|
type GovernancePolicy struct {
|
||||||
|
ID string
|
||||||
|
Name string
|
||||||
|
Description string
|
||||||
|
Enabled bool
|
||||||
|
Level GovernanceLevel
|
||||||
|
Evaluate func(ctx context.Context, msg *types.UnifiedSynapseMessage) (bool, string)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GovernanceConfig 治理配置
|
||||||
|
type GovernanceConfig struct {
|
||||||
|
InitialLevel GovernanceLevel
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultGovernanceConfig 返回默认治理配置
|
||||||
|
func DefaultGovernanceConfig() *GovernanceConfig {
|
||||||
|
return &GovernanceConfig{
|
||||||
|
InitialLevel: GovLevelNormal,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewGovernanceManager 创建治理管理器
|
||||||
|
func NewGovernanceManager(config *GovernanceConfig) *GovernanceManager {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultGovernanceConfig()
|
||||||
|
}
|
||||||
|
return &GovernanceManager{
|
||||||
|
level: config.InitialLevel,
|
||||||
|
policies: make(map[string]GovernancePolicy),
|
||||||
|
blacklist: make(map[string]bool),
|
||||||
|
whitelist: make(map[string]bool),
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetLevel 设置治理级别
|
||||||
|
func (gm *GovernanceManager) SetLevel(level GovernanceLevel) {
|
||||||
|
gm.mu.Lock()
|
||||||
|
defer gm.mu.Unlock()
|
||||||
|
|
||||||
|
gm.level = level
|
||||||
|
log.Printf("[灵枢] 治理级别调整为: %s", level.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLevel 获取治理级别
|
||||||
|
func (gm *GovernanceManager) GetLevel() GovernanceLevel {
|
||||||
|
gm.mu.RLock()
|
||||||
|
defer gm.mu.RUnlock()
|
||||||
|
return gm.level
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddPolicy 添加治理策略
|
||||||
|
func (gm *GovernanceManager) AddPolicy(policy GovernancePolicy) {
|
||||||
|
gm.mu.Lock()
|
||||||
|
defer gm.mu.Unlock()
|
||||||
|
gm.policies[policy.ID] = policy
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemovePolicy 移除治理策略
|
||||||
|
func (gm *GovernanceManager) RemovePolicy(policyID string) {
|
||||||
|
gm.mu.Lock()
|
||||||
|
defer gm.mu.Unlock()
|
||||||
|
delete(gm.policies, policyID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// BanAgent 封禁 Agent
|
||||||
|
func (gm *GovernanceManager) BanAgent(agentID, reason string) {
|
||||||
|
gm.mu.Lock()
|
||||||
|
defer gm.mu.Unlock()
|
||||||
|
gm.blacklist[agentID] = true
|
||||||
|
log.Printf("[灵枢] 封禁 Agent: %s (%s)", agentID, reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnbanAgent 解封 Agent
|
||||||
|
func (gm *GovernanceManager) UnbanAgent(agentID string) {
|
||||||
|
gm.mu.Lock()
|
||||||
|
defer gm.mu.Unlock()
|
||||||
|
delete(gm.blacklist, agentID)
|
||||||
|
log.Printf("[灵枢] 解封 Agent: %s", agentID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsBanned 检查是否被封禁
|
||||||
|
func (gm *GovernanceManager) IsBanned(agentID string) bool {
|
||||||
|
gm.mu.RLock()
|
||||||
|
defer gm.mu.RUnlock()
|
||||||
|
return gm.blacklist[agentID]
|
||||||
|
}
|
||||||
|
|
||||||
|
// AllowMessage 检查是否允许消息通过
|
||||||
|
func (gm *GovernanceManager) AllowMessage(ctx context.Context, msg *types.UnifiedSynapseMessage) (bool, string) {
|
||||||
|
gm.mu.RLock()
|
||||||
|
defer gm.mu.RUnlock()
|
||||||
|
|
||||||
|
// 停机模式,全部拒绝
|
||||||
|
if gm.level >= GovLevelShutdown {
|
||||||
|
return false, "system shutdown"
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查黑名单
|
||||||
|
if gm.blacklist[msg.Sender.AgentID] {
|
||||||
|
return false, "sender banned"
|
||||||
|
}
|
||||||
|
|
||||||
|
// 紧急模式,仅允许白名单
|
||||||
|
if gm.level >= GovLevelEmergency {
|
||||||
|
if !gm.whitelist[msg.Sender.AgentID] {
|
||||||
|
return false, "emergency mode, whitelist only"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行策略检查
|
||||||
|
for _, policy := range gm.policies {
|
||||||
|
if !policy.Enabled || policy.Level > gm.level {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
allowed, reason := policy.Evaluate(ctx, msg)
|
||||||
|
if !allowed {
|
||||||
|
return false, fmt.Sprintf("policy %s: %s", policy.Name, reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true, ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Protocol Upgrade - 协议升级
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// UpgradeManager 升级管理器
|
||||||
|
type UpgradeManager struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
currentVersion string
|
||||||
|
upgrades map[string]ProtocolUpgrade
|
||||||
|
config *UpgradeConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProtocolUpgrade 协议升级
|
||||||
|
type ProtocolUpgrade struct {
|
||||||
|
Version string
|
||||||
|
Description string
|
||||||
|
ReleasedAt time.Time
|
||||||
|
Mandatory bool
|
||||||
|
Apply func() error
|
||||||
|
Rollback func() error
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpgradeConfig 升级配置
|
||||||
|
type UpgradeConfig struct {
|
||||||
|
AutoUpgrade bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultUpgradeConfig 返回默认升级配置
|
||||||
|
func DefaultUpgradeConfig() *UpgradeConfig {
|
||||||
|
return &UpgradeConfig{
|
||||||
|
AutoUpgrade: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewUpgradeManager 创建升级管理器
|
||||||
|
func NewUpgradeManager(initialVersion string, config *UpgradeConfig) *UpgradeManager {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultUpgradeConfig()
|
||||||
|
}
|
||||||
|
return &UpgradeManager{
|
||||||
|
currentVersion: initialVersion,
|
||||||
|
upgrades: make(map[string]ProtocolUpgrade),
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CurrentVersion 当前版本
|
||||||
|
func (um *UpgradeManager) CurrentVersion() string {
|
||||||
|
um.mu.RLock()
|
||||||
|
defer um.mu.RUnlock()
|
||||||
|
return um.currentVersion
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegisterUpgrade 注册升级
|
||||||
|
func (um *UpgradeManager) RegisterUpgrade(upgrade ProtocolUpgrade) {
|
||||||
|
um.mu.Lock()
|
||||||
|
defer um.mu.Unlock()
|
||||||
|
um.upgrades[upgrade.Version] = upgrade
|
||||||
|
}
|
||||||
|
|
||||||
|
// ApplyUpgrade 应用升级
|
||||||
|
func (um *UpgradeManager) ApplyUpgrade(version string) error {
|
||||||
|
um.mu.Lock()
|
||||||
|
defer um.mu.Unlock()
|
||||||
|
|
||||||
|
upgrade, ok := um.upgrades[version]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("upgrade %s not found", version)
|
||||||
|
}
|
||||||
|
|
||||||
|
if upgrade.Apply == nil {
|
||||||
|
um.currentVersion = version
|
||||||
|
log.Printf("[灵枢] 协议升级到: %s", version)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := upgrade.Apply(); err != nil {
|
||||||
|
return fmt.Errorf("upgrade failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
um.currentVersion = version
|
||||||
|
log.Printf("[灵枢] 协议升级成功: %s", version)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RollbackUpgrade 回滚升级
|
||||||
|
func (um *UpgradeManager) RollbackUpgrade(version string) error {
|
||||||
|
um.mu.Lock()
|
||||||
|
defer um.mu.Unlock()
|
||||||
|
|
||||||
|
upgrade, ok := um.upgrades[version]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("upgrade %s not found", version)
|
||||||
|
}
|
||||||
|
|
||||||
|
if upgrade.Rollback == nil {
|
||||||
|
return fmt.Errorf("no rollback function for version %s", version)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := upgrade.Rollback(); err != nil {
|
||||||
|
return fmt.Errorf("rollback failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("[灵枢] 协议回滚: %s", version)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Pivot - 灵枢整体入口
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// Pivot 灵枢 - 紧急制动与治理
|
||||||
|
type Pivot struct {
|
||||||
|
CircuitBreakers map[string]*CircuitBreaker
|
||||||
|
Governance *GovernanceManager
|
||||||
|
Upgrade *UpgradeManager
|
||||||
|
mu sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPivot 创建灵枢
|
||||||
|
func NewPivot() *Pivot {
|
||||||
|
return &Pivot{
|
||||||
|
CircuitBreakers: make(map[string]*CircuitBreaker),
|
||||||
|
Governance: NewGovernanceManager(nil),
|
||||||
|
Upgrade: NewUpgradeManager("1.0.0", nil),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCircuitBreaker 获取或创建熔断器
|
||||||
|
func (p *Pivot) GetCircuitBreaker(name string) *CircuitBreaker {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
|
||||||
|
if cb, ok := p.CircuitBreakers[name]; ok {
|
||||||
|
return cb
|
||||||
|
}
|
||||||
|
|
||||||
|
cb := NewCircuitBreaker(name, nil)
|
||||||
|
p.CircuitBreakers[name] = cb
|
||||||
|
return cb
|
||||||
|
}
|
||||||
|
|
||||||
|
// EmergencyStop 紧急停止(一键熔断所有)
|
||||||
|
func (p *Pivot) EmergencyStop(reason string) {
|
||||||
|
log.Printf("[灵枢] ⚠️ 紧急制动启动: %s", reason)
|
||||||
|
p.Governance.SetLevel(GovLevelEmergency)
|
||||||
|
|
||||||
|
for name, cb := range p.CircuitBreakers {
|
||||||
|
cb.RecordFailure()
|
||||||
|
log.Printf("[灵枢] 熔断器 %s 已熔断", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resume 恢复正常
|
||||||
|
func (p *Pivot) Resume() {
|
||||||
|
log.Printf("[灵枢] 系统恢复正常")
|
||||||
|
p.Governance.SetLevel(GovLevelNormal)
|
||||||
|
|
||||||
|
for _, cb := range p.CircuitBreakers {
|
||||||
|
cb.Reset()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToJSON 导出为 JSON
|
||||||
|
func (gm *GovernanceManager) ToJSON() string {
|
||||||
|
data, _ := json.MarshalIndent(map[string]interface{}{
|
||||||
|
"level": gm.level.String(),
|
||||||
|
"policies": len(gm.policies),
|
||||||
|
"blacklist": len(gm.blacklist),
|
||||||
|
"whitelist": len(gm.whitelist),
|
||||||
|
}, "", " ")
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
459
sdk/a2a/client.go
Normal file
459
sdk/a2a/client.go
Normal file
@@ -0,0 +1,459 @@
|
|||||||
|
package a2a
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"synapse/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Synapse P2P SDK (灵隙协议)
|
||||||
|
// Agent 间点对点通信客户端 SDK
|
||||||
|
// 基于 A2A 协议:两个 Agent 之间进行点对点任务协作
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// MessageCallbackHandler 消息回调处理器接口
|
||||||
|
type MessageCallbackHandler interface {
|
||||||
|
HandleTaskRequest(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error)
|
||||||
|
HandleTaskStatusUpdate(ctx context.Context, msg *types.UnifiedSynapseMessage) error
|
||||||
|
HandleTaskComplete(ctx context.Context, msg *types.UnifiedSynapseMessage) error
|
||||||
|
HandleTaskFailed(ctx context.Context, msg *types.UnifiedSynapseMessage) error
|
||||||
|
HandleNeedHuman(ctx context.Context, msg *types.UnifiedSynapseMessage) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client 灵隙 点对点通信客户端
|
||||||
|
type Client struct {
|
||||||
|
agentEndpoint types.AgentEndpoint
|
||||||
|
authSecret string
|
||||||
|
callbackHandler MessageCallbackHandler
|
||||||
|
tasks map[string]*P2PTaskState
|
||||||
|
tasksMu sync.RWMutex
|
||||||
|
httpClient *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClientConfig 灵隙 客户端配置
|
||||||
|
type ClientConfig struct {
|
||||||
|
AgentEndpoint types.AgentEndpoint
|
||||||
|
AuthSecret string
|
||||||
|
CallbackPort int
|
||||||
|
Timeout time.Duration
|
||||||
|
MaxRetries int
|
||||||
|
}
|
||||||
|
|
||||||
|
// P2PTaskState P2P 任务状态
|
||||||
|
type P2PTaskState struct {
|
||||||
|
TaskID string
|
||||||
|
Status types.P2PTaskStatus
|
||||||
|
Progress int
|
||||||
|
Message string
|
||||||
|
Result any
|
||||||
|
Error *types.SynapseError
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewClient 创建新的 灵隙 客户端
|
||||||
|
func NewClient(config *ClientConfig) (*Client, error) {
|
||||||
|
if config.Timeout == 0 {
|
||||||
|
config.Timeout = 30 * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Client{
|
||||||
|
agentEndpoint: config.AgentEndpoint,
|
||||||
|
authSecret: config.AuthSecret,
|
||||||
|
tasks: make(map[string]*P2PTaskState),
|
||||||
|
httpClient: &http.Client{Timeout: config.Timeout},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetMessageHandler 设置消息回调处理器
|
||||||
|
func (c *Client) SetMessageHandler(handler MessageCallbackHandler) {
|
||||||
|
c.callbackHandler = handler
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 任务状态管理
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// GetTaskState 获取任务状态
|
||||||
|
func (c *Client) GetTaskState(taskID string) (*P2PTaskState, bool) {
|
||||||
|
c.tasksMu.RLock()
|
||||||
|
defer c.tasksMu.RUnlock()
|
||||||
|
state, ok := c.tasks[taskID]
|
||||||
|
return state, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListTasks 列出所有任务
|
||||||
|
func (c *Client) ListTasks() map[string]*P2PTaskState {
|
||||||
|
c.tasksMu.RLock()
|
||||||
|
defer c.tasksMu.RUnlock()
|
||||||
|
result := make(map[string]*P2PTaskState, len(c.tasks))
|
||||||
|
for k, v := range c.tasks {
|
||||||
|
result[k] = v
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) setTaskState(taskID string, status types.P2PTaskStatus, progress int, message string) {
|
||||||
|
c.tasksMu.Lock()
|
||||||
|
defer c.tasksMu.Unlock()
|
||||||
|
if _, ok := c.tasks[taskID]; !ok {
|
||||||
|
c.tasks[taskID] = &P2PTaskState{TaskID: taskID}
|
||||||
|
}
|
||||||
|
c.tasks[taskID].Status = status
|
||||||
|
c.tasks[taskID].Progress = progress
|
||||||
|
c.tasks[taskID].Message = message
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) setTaskResult(taskID string, result any) {
|
||||||
|
c.tasksMu.Lock()
|
||||||
|
defer c.tasksMu.Unlock()
|
||||||
|
if state, ok := c.tasks[taskID]; ok {
|
||||||
|
state.Result = result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) setTaskError(taskID string, err *types.SynapseError) {
|
||||||
|
c.tasksMu.Lock()
|
||||||
|
defer c.tasksMu.Unlock()
|
||||||
|
if state, ok := c.tasks[taskID]; ok {
|
||||||
|
state.Error = err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 消息发送
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// SendTaskRequest 发送任务请求
|
||||||
|
func (c *Client) SendTaskRequest(ctx context.Context, target types.AgentEndpoint, taskType string, payload map[string]any) (string, error) {
|
||||||
|
taskID := types.GenerateTaskID()
|
||||||
|
|
||||||
|
taskReq := types.TaskRequestPayload{}
|
||||||
|
taskReq.Task.ID = taskID
|
||||||
|
taskReq.Task.Type = taskType
|
||||||
|
taskReq.Task.Priority = types.PriorityNormal
|
||||||
|
taskReq.Task.Payload = payload
|
||||||
|
|
||||||
|
payloadBytes, _ := json.Marshal(taskReq)
|
||||||
|
|
||||||
|
msg := &types.UnifiedSynapseMessage{
|
||||||
|
ID: types.GenerateMessageID(),
|
||||||
|
Version: "1.0.0",
|
||||||
|
Type: string(types.P2PTaskRequest),
|
||||||
|
Sender: c.agentEndpoint,
|
||||||
|
Receiver: &target,
|
||||||
|
Payload: payloadBytes,
|
||||||
|
Priority: types.PriorityNormal,
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
c.setTaskState(taskID, types.P2PStatusPending, 0, "任务已发送")
|
||||||
|
|
||||||
|
err := c.sendMessage(ctx, target.Endpoint, msg)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed to send task request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return taskID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendTaskCancel 发送任务取消
|
||||||
|
func (c *Client) SendTaskCancel(ctx context.Context, target types.AgentEndpoint, taskID, reason string) error {
|
||||||
|
cancelPayload := types.TaskCancelPayload{
|
||||||
|
TaskID: taskID,
|
||||||
|
Reason: reason,
|
||||||
|
CancelledBy: c.agentEndpoint.AgentID,
|
||||||
|
}
|
||||||
|
|
||||||
|
payloadBytes, _ := json.Marshal(cancelPayload)
|
||||||
|
|
||||||
|
msg := &types.UnifiedSynapseMessage{
|
||||||
|
ID: types.GenerateMessageID(),
|
||||||
|
Version: "1.0.0",
|
||||||
|
Type: string(types.P2PTaskCancel),
|
||||||
|
Sender: c.agentEndpoint,
|
||||||
|
Receiver: &target,
|
||||||
|
Payload: payloadBytes,
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
c.setTaskState(taskID, types.P2PStatusCancelled, 0, "任务已取消")
|
||||||
|
|
||||||
|
return c.sendMessage(ctx, target.Endpoint, msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendHumanDecision 发送人类决策结果
|
||||||
|
func (c *Client) SendHumanDecision(ctx context.Context, target types.AgentEndpoint, taskID string, decision types.HumanDecisionPayload) error {
|
||||||
|
payloadBytes, _ := json.Marshal(decision)
|
||||||
|
|
||||||
|
msg := &types.UnifiedSynapseMessage{
|
||||||
|
ID: types.GenerateMessageID(),
|
||||||
|
Version: "1.0.0",
|
||||||
|
Type: string(types.P2PHumanDecision),
|
||||||
|
Sender: c.agentEndpoint,
|
||||||
|
Receiver: &target,
|
||||||
|
Payload: payloadBytes,
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.sendMessage(ctx, target.Endpoint, msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendCapabilityQuery 查询对方能力
|
||||||
|
func (c *Client) SendCapabilityQuery(ctx context.Context, target types.AgentEndpoint) ([]string, error) {
|
||||||
|
msg := &types.UnifiedSynapseMessage{
|
||||||
|
ID: types.GenerateMessageID(),
|
||||||
|
Version: "1.0.0",
|
||||||
|
Type: string(types.P2PCapabilityQuery),
|
||||||
|
Sender: c.agentEndpoint,
|
||||||
|
Receiver: &target,
|
||||||
|
Payload: []byte("{}"),
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
respMsg, err := c.sendRequest(ctx, target.Endpoint, msg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to query capabilities: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var resp struct {
|
||||||
|
Capabilities []string `json:"capabilities"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(respMsg.Payload, &resp); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse capabilities: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return resp.Capabilities, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 消息签名与验证
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func (c *Client) signMessage(msg *types.UnifiedSynapseMessage) string {
|
||||||
|
if c.authSecret == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
h := hmac.New(sha256.New, []byte(c.authSecret))
|
||||||
|
h.Write([]byte(msg.ID + "." + string(msg.Payload)))
|
||||||
|
return hex.EncodeToString(h.Sum(nil))
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifySignature 验证消息签名
|
||||||
|
func (c *Client) VerifySignature(msg *types.UnifiedSynapseMessage, secret string) bool {
|
||||||
|
if secret == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if msg.Signature == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
h := hmac.New(sha256.New, []byte(secret))
|
||||||
|
h.Write([]byte(msg.ID + "." + string(msg.Payload)))
|
||||||
|
expected := hex.EncodeToString(h.Sum(nil))
|
||||||
|
return hmac.Equal([]byte(msg.Signature), []byte(expected))
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 消息发送底层
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func (c *Client) sendMessage(ctx context.Context, endpoint string, msg *types.UnifiedSynapseMessage) error {
|
||||||
|
msg.Signature = c.signMessage(msg)
|
||||||
|
|
||||||
|
body, err := json.Marshal(msg)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to marshal message: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
httpReq, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to create request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
httpReq.Header.Set("Content-Type", "application/json")
|
||||||
|
httpReq.Header.Set("X-Synapse-Signature", msg.Signature)
|
||||||
|
|
||||||
|
resp, err := c.httpClient.Do(httpReq)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("request failed: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode >= 400 {
|
||||||
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
return fmt.Errorf("remote error: %s", string(respBody))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) sendRequest(ctx context.Context, endpoint string, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||||
|
msg.Signature = c.signMessage(msg)
|
||||||
|
|
||||||
|
body, err := json.Marshal(msg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to marshal message: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
httpReq, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
httpReq.Header.Set("Content-Type", "application/json")
|
||||||
|
httpReq.Header.Set("X-Synapse-Signature", msg.Signature)
|
||||||
|
|
||||||
|
resp, err := c.httpClient.Do(httpReq)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("request failed: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
|
||||||
|
if resp.StatusCode >= 400 {
|
||||||
|
return nil, fmt.Errorf("remote error: %s", string(respBody))
|
||||||
|
}
|
||||||
|
|
||||||
|
var respMsg types.UnifiedSynapseMessage
|
||||||
|
if err := json.Unmarshal(respBody, &respMsg); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &respMsg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 等待任务完成
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// WaitForTask 等待任务完成(轮询方式,通过回调更新状态)
|
||||||
|
func (c *Client) WaitForTask(ctx context.Context, taskID string, timeout time.Duration) (*P2PTaskState, error) {
|
||||||
|
deadline := time.Now().Add(timeout)
|
||||||
|
ticker := time.NewTicker(1 * time.Second)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
case <-ticker.C:
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
return nil, fmt.Errorf("task timeout")
|
||||||
|
}
|
||||||
|
|
||||||
|
state, ok := c.GetTaskState(taskID)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
switch state.Status {
|
||||||
|
case types.P2PStatusCompleted, types.P2PStatusFailed, types.P2PStatusCancelled, types.P2PStatusRejected:
|
||||||
|
return state, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 回调处理
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// HandleMessage 处理收到的消息(供 HTTP 服务调用)
|
||||||
|
func (c *Client) HandleMessage(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||||
|
if c.authSecret != "" && !c.VerifySignature(msg, c.authSecret) {
|
||||||
|
return nil, fmt.Errorf("invalid signature")
|
||||||
|
}
|
||||||
|
|
||||||
|
switch types.P2PMessageType(msg.Type) {
|
||||||
|
case types.P2PTaskRequest:
|
||||||
|
if c.callbackHandler != nil {
|
||||||
|
return c.callbackHandler.HandleTaskRequest(ctx, msg)
|
||||||
|
}
|
||||||
|
return c.ackMessage(msg), nil
|
||||||
|
|
||||||
|
case types.P2PTaskConfirm:
|
||||||
|
var payload types.TaskConfirmPayload
|
||||||
|
_ = json.Unmarshal(msg.Payload, &payload)
|
||||||
|
c.setTaskState(payload.TaskID, types.P2PStatusConfirmed, 0, "任务已确认")
|
||||||
|
return c.ackMessage(msg), nil
|
||||||
|
|
||||||
|
case types.P2PTaskReject:
|
||||||
|
var payload types.TaskRejectPayload
|
||||||
|
_ = json.Unmarshal(msg.Payload, &payload)
|
||||||
|
c.setTaskState(payload.TaskID, types.P2PStatusRejected, 0, payload.Reason.Message)
|
||||||
|
return c.ackMessage(msg), nil
|
||||||
|
|
||||||
|
case types.P2PTaskStatusUpdate:
|
||||||
|
var payload types.TaskStatusUpdatePayload
|
||||||
|
_ = json.Unmarshal(msg.Payload, &payload)
|
||||||
|
c.setTaskState(payload.TaskID, types.P2PTaskStatus(payload.Status), payload.Progress, payload.Message)
|
||||||
|
if c.callbackHandler != nil {
|
||||||
|
_ = c.callbackHandler.HandleTaskStatusUpdate(ctx, msg)
|
||||||
|
}
|
||||||
|
return c.ackMessage(msg), nil
|
||||||
|
|
||||||
|
case types.P2PTaskComplete:
|
||||||
|
var payload types.TaskCompletePayload
|
||||||
|
_ = json.Unmarshal(msg.Payload, &payload)
|
||||||
|
c.setTaskState(payload.TaskID, types.P2PStatusCompleted, 100, payload.Summary)
|
||||||
|
c.setTaskResult(payload.TaskID, payload.Result.Output)
|
||||||
|
if c.callbackHandler != nil {
|
||||||
|
_ = c.callbackHandler.HandleTaskComplete(ctx, msg)
|
||||||
|
}
|
||||||
|
return c.ackMessage(msg), nil
|
||||||
|
|
||||||
|
case types.P2PTaskFailed:
|
||||||
|
var payload types.TaskFailedPayload
|
||||||
|
_ = json.Unmarshal(msg.Payload, &payload)
|
||||||
|
c.setTaskState(payload.TaskID, types.P2PStatusFailed, 0, payload.Error.Message)
|
||||||
|
c.setTaskError(payload.TaskID, types.NewSynapseError(
|
||||||
|
types.SynapseErrorCode(0),
|
||||||
|
payload.Error.Message,
|
||||||
|
nil,
|
||||||
|
))
|
||||||
|
if c.callbackHandler != nil {
|
||||||
|
_ = c.callbackHandler.HandleTaskFailed(ctx, msg)
|
||||||
|
}
|
||||||
|
return c.ackMessage(msg), nil
|
||||||
|
|
||||||
|
case types.P2PTaskNeedHuman:
|
||||||
|
var payload types.TaskNeedHumanPayload
|
||||||
|
_ = json.Unmarshal(msg.Payload, &payload)
|
||||||
|
c.setTaskState(payload.TaskID, types.P2PStatusNeedHuman, 0, payload.Reason.Message)
|
||||||
|
if c.callbackHandler != nil {
|
||||||
|
_ = c.callbackHandler.HandleNeedHuman(ctx, msg)
|
||||||
|
}
|
||||||
|
return c.ackMessage(msg), nil
|
||||||
|
|
||||||
|
case types.P2PCapabilityQuery:
|
||||||
|
return nil, nil
|
||||||
|
|
||||||
|
default:
|
||||||
|
return c.ackMessage(msg), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) ackMessage(msg *types.UnifiedSynapseMessage) *types.UnifiedSynapseMessage {
|
||||||
|
return &types.UnifiedSynapseMessage{
|
||||||
|
ID: types.GenerateMessageID(),
|
||||||
|
Version: msg.Version,
|
||||||
|
Type: string(types.P2PAck),
|
||||||
|
Sender: c.agentEndpoint,
|
||||||
|
Receiver: &msg.Sender,
|
||||||
|
ReplyTo: msg.ID,
|
||||||
|
Payload: []byte("{}"),
|
||||||
|
Timestamp: types.NowTimestamp(),
|
||||||
|
}
|
||||||
|
}
|
||||||
346
sdk/a2n/client.go
Normal file
346
sdk/a2n/client.go
Normal file
@@ -0,0 +1,346 @@
|
|||||||
|
package a2n
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"synapse/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Synapse Group SDK (A2N Protocol)
|
||||||
|
// 多 Agent 群组协作客户端 SDK
|
||||||
|
// 基于 A2N 协议:多个 Agent 组成群组进行协同工作
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// GroupEventHandler 群组事件处理器接口
|
||||||
|
type GroupEventHandler interface {
|
||||||
|
OnGroupCreated(ctx context.Context, groupID string) error
|
||||||
|
OnGroupDisbanded(ctx context.Context, groupID string) error
|
||||||
|
OnMemberJoined(ctx context.Context, groupID string, member types.GroupMember) error
|
||||||
|
OnMemberLeft(ctx context.Context, groupID, agentID string) error
|
||||||
|
OnTaskSplit(ctx context.Context, groupID, originalTaskID string, subtasks []types.Subtask) error
|
||||||
|
OnSubtaskProgress(ctx context.Context, groupID, subtaskID string, progress int) error
|
||||||
|
OnTaskMerged(ctx context.Context, groupID, originalTaskID string, result any) error
|
||||||
|
OnVoteInitiated(ctx context.Context, groupID string, vote types.GroupVotePayload) error
|
||||||
|
OnVoteResult(ctx context.Context, groupID, voteID, option string, passed bool) error
|
||||||
|
OnEscalation(ctx context.Context, groupID, escalationID string, level int) error
|
||||||
|
OnBroadcast(ctx context.Context, groupID string, sender types.AgentEndpoint, message []byte) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client A2N 群组协作客户端
|
||||||
|
type Client struct {
|
||||||
|
a2aClient *a2aClient
|
||||||
|
groups map[string]*GroupState
|
||||||
|
groupsMu sync.RWMutex
|
||||||
|
eventHandler GroupEventHandler
|
||||||
|
}
|
||||||
|
|
||||||
|
// a2aClient 是 P2P 客户端的简化接口
|
||||||
|
type a2aClient interface {
|
||||||
|
SendMessage(ctx context.Context, target types.AgentEndpoint, msg *types.UnifiedSynapseMessage) error
|
||||||
|
AgentEndpoint() types.AgentEndpoint
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClientConfig A2N 客户端配置
|
||||||
|
type ClientConfig struct {
|
||||||
|
P2PClient *a2aClient
|
||||||
|
EventHandler GroupEventHandler
|
||||||
|
}
|
||||||
|
|
||||||
|
// GroupState 群组状态
|
||||||
|
type GroupState struct {
|
||||||
|
GroupID string
|
||||||
|
Name string
|
||||||
|
Topology types.GroupTopology
|
||||||
|
Status types.GroupStatus
|
||||||
|
Members []types.GroupMember
|
||||||
|
Role string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewClient 创建新的 A2N 群组客户端
|
||||||
|
func NewClient(a2aClient interface{}, eventHandler GroupEventHandler) (*Client, error) {
|
||||||
|
return &Client{
|
||||||
|
groups: make(map[string]*GroupState),
|
||||||
|
eventHandler: eventHandler,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetEventHandler 设置群组事件处理器
|
||||||
|
func (c *Client) SetEventHandler(handler GroupEventHandler) {
|
||||||
|
c.eventHandler = handler
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 群组管理
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// CreateGroup 创建群组
|
||||||
|
func (c *Client) CreateGroup(ctx context.Context, name string, topology types.GroupTopology, config *types.GroupConfig, initialMembers []types.AgentEndpoint) (*GroupState, error) {
|
||||||
|
groupID := fmt.Sprintf("group-%d", time.Now().UnixNano())
|
||||||
|
|
||||||
|
if config == nil {
|
||||||
|
config = &types.GroupConfig{
|
||||||
|
AllowSelfLeave: true,
|
||||||
|
RequiresApproval: false,
|
||||||
|
ConsensusRequired: false,
|
||||||
|
ConsensusThreshold: 0.5,
|
||||||
|
BroadcastMode: "all",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
members := make([]types.GroupMember, 0, len(initialMembers)+1)
|
||||||
|
for _, m := range initialMembers {
|
||||||
|
members = append(members, types.GroupMember{
|
||||||
|
AgentID: m.AgentID,
|
||||||
|
AgentName: m.AgentName,
|
||||||
|
Role: "worker",
|
||||||
|
JoinedAt: types.NowTimestamp(),
|
||||||
|
Status: types.GroupMemberActive,
|
||||||
|
Capabilities: []string{},
|
||||||
|
LoadFactor: 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
groupState := &GroupState{
|
||||||
|
GroupID: groupID,
|
||||||
|
Name: name,
|
||||||
|
Topology: topology,
|
||||||
|
Status: types.GroupStatusActive,
|
||||||
|
Members: members,
|
||||||
|
Role: "coordinator",
|
||||||
|
}
|
||||||
|
|
||||||
|
c.groupsMu.Lock()
|
||||||
|
c.groups[groupID] = groupState
|
||||||
|
c.groupsMu.Unlock()
|
||||||
|
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnGroupCreated(ctx, groupID)
|
||||||
|
}
|
||||||
|
|
||||||
|
return groupState, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// JoinGroup 加入群组
|
||||||
|
func (c *Client) JoinGroup(ctx context.Context, groupID string) error {
|
||||||
|
c.groupsMu.Lock()
|
||||||
|
defer c.groupsMu.Unlock()
|
||||||
|
|
||||||
|
if _, ok := c.groups[groupID]; !ok {
|
||||||
|
c.groups[groupID] = &GroupState{
|
||||||
|
GroupID: groupID,
|
||||||
|
Status: types.GroupStatusActive,
|
||||||
|
Role: "worker",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnMemberJoined(ctx, groupID, types.GroupMember{})
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LeaveGroup 离开群组
|
||||||
|
func (c *Client) LeaveGroup(ctx context.Context, groupID string) error {
|
||||||
|
c.groupsMu.Lock()
|
||||||
|
delete(c.groups, groupID)
|
||||||
|
c.groupsMu.Unlock()
|
||||||
|
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnMemberLeft(ctx, groupID, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DisbandGroup 解散群组
|
||||||
|
func (c *Client) DisbandGroup(ctx context.Context, groupID string) error {
|
||||||
|
c.groupsMu.Lock()
|
||||||
|
if group, ok := c.groups[groupID]; ok {
|
||||||
|
group.Status = types.GroupStatusDisbanded
|
||||||
|
}
|
||||||
|
c.groupsMu.Unlock()
|
||||||
|
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnGroupDisbanded(ctx, groupID)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetGroup 获取群组信息
|
||||||
|
func (c *Client) GetGroup(groupID string) (*GroupState, bool) {
|
||||||
|
c.groupsMu.RLock()
|
||||||
|
defer c.groupsMu.RUnlock()
|
||||||
|
group, ok := c.groups[groupID]
|
||||||
|
return group, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListGroups 列出所有群组
|
||||||
|
func (c *Client) ListGroups() []*GroupState {
|
||||||
|
c.groupsMu.RLock()
|
||||||
|
defer c.groupsMu.RUnlock()
|
||||||
|
result := make([]*GroupState, 0, len(c.groups))
|
||||||
|
for _, g := range c.groups {
|
||||||
|
result = append(result, g)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 任务协作
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// SubmitGroupTask 提交群组任务(作为 coordinator 拆分任务)
|
||||||
|
func (c *Client) SubmitGroupTask(ctx context.Context, groupID, taskType string, requirements map[string]any, mergeStrategy types.MergeStrategy) ([]types.Subtask, error) {
|
||||||
|
subtasks := []types.Subtask{
|
||||||
|
{
|
||||||
|
ID: fmt.Sprintf("sub-%d-1", time.Now().UnixNano()),
|
||||||
|
Description: "子任务 1",
|
||||||
|
AssignedTo: "",
|
||||||
|
Dependencies: []string{},
|
||||||
|
EstimatedDuration: 60,
|
||||||
|
Priority: 1,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnTaskSplit(ctx, groupID, "", subtasks)
|
||||||
|
}
|
||||||
|
|
||||||
|
return subtasks, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendSubtaskResult 发送子任务结果
|
||||||
|
func (c *Client) SendSubtaskResult(ctx context.Context, groupID, subtaskID string, result any, err error) error {
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnTaskMerged(ctx, groupID, "", result)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 投票与共识
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// InitiateVote 发起投票
|
||||||
|
func (c *Client) InitiateVote(ctx context.Context, groupID, question string, options []string, voterIDs []string, threshold float64, deadline time.Duration) (string, error) {
|
||||||
|
voteID := fmt.Sprintf("vote-%d", time.Now().UnixNano())
|
||||||
|
|
||||||
|
vote := types.GroupVotePayload{
|
||||||
|
VoteID: voteID,
|
||||||
|
Question: question,
|
||||||
|
Options: options,
|
||||||
|
Voters: voterIDs,
|
||||||
|
Deadline: types.Timestamp(time.Now().Add(deadline).UTC().Format(time.RFC3339)),
|
||||||
|
Threshold: threshold,
|
||||||
|
Status: "open",
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnVoteInitiated(ctx, groupID, vote)
|
||||||
|
}
|
||||||
|
|
||||||
|
return voteID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SubmitVote 提交投票
|
||||||
|
func (c *Client) SubmitVote(ctx context.Context, groupID, voteID, option, reason string) error {
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnVoteResult(ctx, groupID, voteID, option, true)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 广播与升级
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// Broadcast 广播消息
|
||||||
|
func (c *Client) Broadcast(ctx context.Context, groupID string, message []byte) error {
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnBroadcast(ctx, groupID, types.AgentEndpoint{}, message)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// EscalateToHuman 升级到人类决策
|
||||||
|
func (c *Client) EscalateToHuman(ctx context.Context, groupID string, level int, reason string) (string, error) {
|
||||||
|
escalationID := fmt.Sprintf("esc-%d", time.Now().UnixNano())
|
||||||
|
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnEscalation(ctx, groupID, escalationID, level)
|
||||||
|
}
|
||||||
|
|
||||||
|
return escalationID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 消息处理
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// HandleMessage 处理群组消息
|
||||||
|
func (c *Client) HandleMessage(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||||
|
groupID := msg.GroupID
|
||||||
|
|
||||||
|
switch types.GroupMessageType(msg.Type) {
|
||||||
|
case types.GroupCreate:
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnGroupCreated(ctx, groupID)
|
||||||
|
}
|
||||||
|
|
||||||
|
case types.GroupDisband:
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnGroupDisbanded(ctx, groupID)
|
||||||
|
}
|
||||||
|
|
||||||
|
case types.GroupMemberUpdate:
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnMemberJoined(ctx, groupID, types.GroupMember{})
|
||||||
|
}
|
||||||
|
|
||||||
|
case types.GroupTaskSplit:
|
||||||
|
var payload types.GroupTaskSplitPayload
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnTaskSplit(ctx, groupID, payload.OriginalTask.ID, payload.Subtasks)
|
||||||
|
}
|
||||||
|
|
||||||
|
case types.GroupTaskProgress:
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnSubtaskProgress(ctx, groupID, "", 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
case types.GroupTaskMerge:
|
||||||
|
var payload types.GroupTaskMergePayload
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnTaskMerged(ctx, groupID, payload.OriginalTaskID, payload.MergedResult)
|
||||||
|
}
|
||||||
|
|
||||||
|
case types.GroupVote:
|
||||||
|
var payload types.GroupVotePayload
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnVoteInitiated(ctx, groupID, payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
case types.GroupConsensus:
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnVoteResult(ctx, groupID, "", "", true)
|
||||||
|
}
|
||||||
|
|
||||||
|
case types.GroupConsensusEscalate, types.GroupSubtaskEscalate:
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnEscalation(ctx, groupID, "", 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
case types.GroupBroadcast:
|
||||||
|
if c.eventHandler != nil {
|
||||||
|
_ = c.eventHandler.OnBroadcast(ctx, groupID, msg.Sender, msg.Payload)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
547
sdk/p2a/client.go
Normal file
547
sdk/p2a/client.go
Normal file
@@ -0,0 +1,547 @@
|
|||||||
|
package p2a
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Synapse Caller SDK (P2A Protocol)
|
||||||
|
// 非Agent调用方使用的客户端SDK
|
||||||
|
// 基于 P2A 协议:非 Agent 调用方通过 REST API 调用 Agent 能力
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// Client 是 Synapse P2A 服务的外部调用客户端
|
||||||
|
type Client struct {
|
||||||
|
baseURL string
|
||||||
|
apiKey string
|
||||||
|
httpClient *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClientConfig 客户端配置
|
||||||
|
type ClientConfig struct {
|
||||||
|
BaseURL string
|
||||||
|
APIKey string
|
||||||
|
Timeout time.Duration
|
||||||
|
MaxRetries int
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewClient 创建新的 Synapse Caller 客户端
|
||||||
|
func NewClient(config ClientConfig) *Client {
|
||||||
|
if config.Timeout == 0 {
|
||||||
|
config.Timeout = 30 * time.Second
|
||||||
|
}
|
||||||
|
return &Client{
|
||||||
|
baseURL: config.BaseURL,
|
||||||
|
apiKey: config.APIKey,
|
||||||
|
httpClient: &http.Client{Timeout: config.Timeout},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 通用响应结构
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// APIResponse 通用 API 响应
|
||||||
|
type APIResponse struct {
|
||||||
|
Success bool `json:"success"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskResponse 任务提交响应
|
||||||
|
type TaskResponse struct {
|
||||||
|
APIResponse
|
||||||
|
TaskID string `json:"task_id"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskStatusResponse 任务状态响应(简化版)
|
||||||
|
type TaskStatusResponse struct {
|
||||||
|
APIResponse
|
||||||
|
TaskID string `json:"task_id"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Progress int `json:"progress"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskDetailResponse 任务详情响应
|
||||||
|
type TaskDetailResponse struct {
|
||||||
|
APIResponse
|
||||||
|
Task TaskInfo `json:"task"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskListResponse 任务列表响应
|
||||||
|
type TaskListResponse struct {
|
||||||
|
APIResponse
|
||||||
|
Tasks []TaskInfo `json:"tasks"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
Limit int `json:"limit"`
|
||||||
|
Offset int `json:"offset"`
|
||||||
|
HasMore bool `json:"has_more"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskInfo 任务详情信息
|
||||||
|
type TaskInfo struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Progress int `json:"progress"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
CreatedAt string `json:"created_at"`
|
||||||
|
UpdatedAt string `json:"updated_at"`
|
||||||
|
CompletedAt string `json:"completed_at,omitempty"`
|
||||||
|
ETA string `json:"eta,omitempty"`
|
||||||
|
Result map[string]any `json:"result,omitempty"`
|
||||||
|
Error *TaskError `json:"error,omitempty"`
|
||||||
|
ExternalTaskID string `json:"external_task_id,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskError 任务错误
|
||||||
|
type TaskError struct {
|
||||||
|
Code string `json:"code"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskRequest 任务请求
|
||||||
|
type TaskRequest struct {
|
||||||
|
TaskType string `json:"task_type"`
|
||||||
|
Payload map[string]any `json:"payload"`
|
||||||
|
ExternalTaskID string `json:"external_task_id,omitempty"`
|
||||||
|
Priority string `json:"priority,omitempty"`
|
||||||
|
CallbackURL string `json:"callback_url,omitempty"`
|
||||||
|
CallbackToken string `json:"callback_token,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileParam 上传文件参数
|
||||||
|
type FileParam struct {
|
||||||
|
FieldName string
|
||||||
|
Filename string
|
||||||
|
Data []byte
|
||||||
|
MimeType string
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 能力查询
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// CapabilitiesResponse 能力查询响应
|
||||||
|
type CapabilitiesResponse struct {
|
||||||
|
APIResponse
|
||||||
|
Capabilities CapabilitiesInfo `json:"capabilities"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CapabilitiesInfo Agent 能力信息
|
||||||
|
type CapabilitiesInfo struct {
|
||||||
|
AgentID string `json:"agent_id"`
|
||||||
|
AgentName string `json:"agent_name"`
|
||||||
|
SystemID string `json:"system_id"`
|
||||||
|
ProtocolVersion string `json:"protocol_version"`
|
||||||
|
SupportedTaskTypes []SupportedTaskType `json:"supported_task_types"`
|
||||||
|
SupportedTransportModes []string `json:"supported_transport_modes"`
|
||||||
|
MaxFileSize int64 `json:"max_file_size"`
|
||||||
|
MaxConcurrentTasks int `json:"max_concurrent_tasks"`
|
||||||
|
SupportProgressUpdates bool `json:"support_progress_updates"`
|
||||||
|
SupportStreaming bool `json:"support_streaming"`
|
||||||
|
SupportHiL bool `json:"support_hil"`
|
||||||
|
SupportGroups bool `json:"support_groups"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportedTaskType 支持的任务类型
|
||||||
|
type SupportedTaskType struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
EstimatedTime string `json:"estimated_time"`
|
||||||
|
InputSchema string `json:"input_schema,omitempty"`
|
||||||
|
OutputSchema string `json:"output_schema,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCapabilities 获取 Agent 能力清单
|
||||||
|
func (c *Client) GetCapabilities(ctx context.Context) (*CapabilitiesResponse, error) {
|
||||||
|
url := fmt.Sprintf("%s/api/v1/synapse/capabilities", c.baseURL)
|
||||||
|
|
||||||
|
httpReq, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.setAuthHeaders(httpReq)
|
||||||
|
|
||||||
|
resp, err := c.httpClient.Do(httpReq)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("request failed: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
|
||||||
|
var result CapabilitiesResponse
|
||||||
|
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode >= 400 {
|
||||||
|
return &result, fmt.Errorf("API error: %s", result.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 任务提交
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// SubmitTask 提交任务(JSON 方式)
|
||||||
|
func (c *Client) SubmitTask(ctx context.Context, req *TaskRequest) (*TaskResponse, error) {
|
||||||
|
url := fmt.Sprintf("%s/api/v1/synapse/task", c.baseURL)
|
||||||
|
|
||||||
|
body, err := json.Marshal(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to marshal request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
httpReq.Header.Set("Content-Type", "application/json")
|
||||||
|
c.setAuthHeaders(httpReq)
|
||||||
|
|
||||||
|
resp, err := c.httpClient.Do(httpReq)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("request failed: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
|
||||||
|
var result TaskResponse
|
||||||
|
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode >= 400 {
|
||||||
|
return &result, fmt.Errorf("API error: %s", result.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SubmitTaskWithFiles 提交带文件的任务(multipart/form-data 方式)
|
||||||
|
func (c *Client) SubmitTaskWithFiles(ctx context.Context, req *TaskRequest, files []FileParam) (*TaskResponse, error) {
|
||||||
|
url := fmt.Sprintf("%s/api/v1/synapse/task/multipart", c.baseURL)
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
writer := multipart.NewWriter(&buf)
|
||||||
|
|
||||||
|
_ = writer.WriteField("task_type", req.TaskType)
|
||||||
|
|
||||||
|
payloadJSON, _ := json.Marshal(req.Payload)
|
||||||
|
_ = writer.WriteField("payload", string(payloadJSON))
|
||||||
|
|
||||||
|
if req.ExternalTaskID != "" {
|
||||||
|
_ = writer.WriteField("external_task_id", req.ExternalTaskID)
|
||||||
|
}
|
||||||
|
if req.Priority != "" {
|
||||||
|
_ = writer.WriteField("priority", req.Priority)
|
||||||
|
}
|
||||||
|
if req.CallbackURL != "" {
|
||||||
|
_ = writer.WriteField("callback_url", req.CallbackURL)
|
||||||
|
}
|
||||||
|
if req.CallbackToken != "" {
|
||||||
|
_ = writer.WriteField("callback_token", req.CallbackToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, f := range files {
|
||||||
|
var part io.Writer
|
||||||
|
var err error
|
||||||
|
if f.MimeType != "" {
|
||||||
|
part, err = writer.CreatePart(map[string][]string{
|
||||||
|
"Content-Disposition": {fmt.Sprintf(`form-data; name="%s"; filename="%s"`, f.FieldName, f.Filename)},
|
||||||
|
"Content-Type": {f.MimeType},
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
part, err = writer.CreateFormFile(f.FieldName, f.Filename)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create form file: %w", err)
|
||||||
|
}
|
||||||
|
_, _ = part.Write(f.Data)
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = writer.Close()
|
||||||
|
|
||||||
|
httpReq, err := http.NewRequestWithContext(ctx, "POST", url, &buf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
httpReq.Header.Set("Content-Type", writer.FormDataContentType())
|
||||||
|
c.setAuthHeaders(httpReq)
|
||||||
|
|
||||||
|
resp, err := c.httpClient.Do(httpReq)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("request failed: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
|
||||||
|
var result TaskResponse
|
||||||
|
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode >= 400 {
|
||||||
|
return &result, fmt.Errorf("API error: %s", result.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 任务查询
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// GetTask 获取任务详情
|
||||||
|
func (c *Client) GetTask(ctx context.Context, taskID string) (*TaskDetailResponse, error) {
|
||||||
|
url := fmt.Sprintf("%s/api/v1/synapse/task/%s", c.baseURL, taskID)
|
||||||
|
|
||||||
|
httpReq, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.setAuthHeaders(httpReq)
|
||||||
|
|
||||||
|
resp, err := c.httpClient.Do(httpReq)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("request failed: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
|
||||||
|
var result TaskDetailResponse
|
||||||
|
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode >= 400 {
|
||||||
|
return &result, fmt.Errorf("API error: %s", result.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetTaskStatus 获取任务状态(简化版)
|
||||||
|
func (c *Client) GetTaskStatus(ctx context.Context, taskID string) (*TaskStatusResponse, error) {
|
||||||
|
url := fmt.Sprintf("%s/api/v1/synapse/task/%s/status", c.baseURL, taskID)
|
||||||
|
|
||||||
|
httpReq, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.setAuthHeaders(httpReq)
|
||||||
|
|
||||||
|
resp, err := c.httpClient.Do(httpReq)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("request failed: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
|
||||||
|
var result TaskStatusResponse
|
||||||
|
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode >= 400 {
|
||||||
|
return &result, fmt.Errorf("API error: %s", result.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListTasks 获取任务列表
|
||||||
|
func (c *Client) ListTasks(ctx context.Context, status string, limit, offset int) (*TaskListResponse, error) {
|
||||||
|
if limit <= 0 {
|
||||||
|
limit = 20
|
||||||
|
}
|
||||||
|
url := fmt.Sprintf("%s/api/v1/synapse/tasks?status=%s&limit=%d&offset=%d",
|
||||||
|
c.baseURL, status, limit, offset)
|
||||||
|
|
||||||
|
httpReq, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.setAuthHeaders(httpReq)
|
||||||
|
|
||||||
|
resp, err := c.httpClient.Do(httpReq)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("request failed: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
|
||||||
|
var result TaskListResponse
|
||||||
|
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode >= 400 {
|
||||||
|
return &result, fmt.Errorf("API error: %s", result.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 任务取消
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// CancelTask 取消任务
|
||||||
|
func (c *Client) CancelTask(ctx context.Context, taskID string) (*TaskResponse, error) {
|
||||||
|
url := fmt.Sprintf("%s/api/v1/synapse/task/%s/cancel", c.baseURL, taskID)
|
||||||
|
|
||||||
|
httpReq, err := http.NewRequestWithContext(ctx, "POST", url, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.setAuthHeaders(httpReq)
|
||||||
|
|
||||||
|
resp, err := c.httpClient.Do(httpReq)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("request failed: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
|
||||||
|
var result TaskResponse
|
||||||
|
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode >= 400 {
|
||||||
|
return &result, fmt.Errorf("API error: %s", result.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 等待任务完成
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// WaitForTask 等待任务完成(轮询方式)
|
||||||
|
func (c *Client) WaitForTask(ctx context.Context, taskID string, interval time.Duration) (*TaskInfo, error) {
|
||||||
|
if interval == 0 {
|
||||||
|
interval = 5 * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
ticker := time.NewTicker(interval)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
case <-ticker.C:
|
||||||
|
resp, err := c.GetTask(ctx, taskID)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
switch resp.Task.Status {
|
||||||
|
case "completed", "failed", "cancelled", "rejected":
|
||||||
|
return &resp.Task, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 回调验证
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// CallbackRequest 回调请求结构
|
||||||
|
type CallbackRequest struct {
|
||||||
|
TaskID string `json:"task_id"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Progress int `json:"progress"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
Result map[string]any `json:"result,omitempty"`
|
||||||
|
Error *TaskError `json:"error,omitempty"`
|
||||||
|
Timestamp string `json:"timestamp"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifyCallback 验证回调请求签名
|
||||||
|
func (c *Client) VerifyCallback(r *http.Request, callbackToken string) bool {
|
||||||
|
if callbackToken == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
token := r.Header.Get("X-Callback-Token")
|
||||||
|
return token == callbackToken
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 高阶 API: 快速创建任务并等待
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// CreateAndWait 创建任务并等待完成
|
||||||
|
func (c *Client) CreateAndWait(ctx context.Context, taskType string, payload map[string]any, interval time.Duration) (*TaskInfo, error) {
|
||||||
|
req := &TaskRequest{
|
||||||
|
TaskType: taskType,
|
||||||
|
Payload: payload,
|
||||||
|
Priority: "normal",
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := c.SubmitTask(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if !resp.Success {
|
||||||
|
return nil, fmt.Errorf("task submission failed: %s", resp.Message)
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.WaitForTask(ctx, resp.TaskID, interval)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateWithCallback 创建任务并指定回调
|
||||||
|
func (c *Client) CreateWithCallback(ctx context.Context, taskType string, payload map[string]any, callbackURL, callbackToken string) (*TaskResponse, error) {
|
||||||
|
req := &TaskRequest{
|
||||||
|
TaskType: taskType,
|
||||||
|
Payload: payload,
|
||||||
|
Priority: "normal",
|
||||||
|
CallbackURL: callbackURL,
|
||||||
|
CallbackToken: callbackToken,
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.SubmitTask(ctx, req)
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 辅助方法
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func (c *Client) setAuthHeaders(req *http.Request) {
|
||||||
|
if c.apiKey != "" {
|
||||||
|
req.Header.Set("X-API-Key", c.apiKey)
|
||||||
|
}
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
}
|
||||||
446
sigil/sigil.go
Normal file
446
sigil/sigil.go
Normal file
@@ -0,0 +1,446 @@
|
|||||||
|
// Package sigil 灵玺 - 身份与凭证层
|
||||||
|
//
|
||||||
|
// 皇帝的玉玺是最高凭证。在此协议中,
|
||||||
|
// 每个 Agent 的初始身份都需经过"铸玺"过程,
|
||||||
|
// 每一次交互都要"验玺",确保穿透零信任边界后
|
||||||
|
// 的每一次握手都正统且不可篡改。
|
||||||
|
package sigil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/sha512"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"hash"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"synapse/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Agent Identity - Agent 身份
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// AgentIdentity Agent 身份凭证
|
||||||
|
type AgentIdentity struct {
|
||||||
|
// Agent 基本信息
|
||||||
|
AgentID string `json:"agent_id"`
|
||||||
|
AgentName string `json:"agent_name"`
|
||||||
|
SystemID string `json:"system_id"`
|
||||||
|
|
||||||
|
// 身份凭证
|
||||||
|
PublicKey string `json:"public_key,omitempty"` // 公钥(可选)
|
||||||
|
PrivateKey string `json:"private_key,omitempty"` // 私钥(本地保存,不对外)
|
||||||
|
AuthSecret string `json:"-"` // HMAC 密钥(不序列化)
|
||||||
|
|
||||||
|
// 权限与角色
|
||||||
|
Roles []string `json:"roles,omitempty"`
|
||||||
|
Permissions []string `json:"permissions,omitempty"`
|
||||||
|
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||||
|
|
||||||
|
// 生命周期
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||||
|
RevokedAt *time.Time `json:"revoked_at,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// IdentityManager 身份管理器
|
||||||
|
type IdentityManager struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
identities map[string]*AgentIdentity // agent_id -> identity
|
||||||
|
config *IdentityConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// IdentityConfig 身份管理配置
|
||||||
|
type IdentityConfig struct {
|
||||||
|
DefaultAlgorithm string // 默认签名算法
|
||||||
|
TokenTTL time.Duration // Token 有效期
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultIdentityConfig 返回默认身份配置
|
||||||
|
func DefaultIdentityConfig() *IdentityConfig {
|
||||||
|
return &IdentityConfig{
|
||||||
|
DefaultAlgorithm: "HMAC-SHA256",
|
||||||
|
TokenTTL: 24 * time.Hour,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewIdentityManager 创建身份管理器
|
||||||
|
func NewIdentityManager(config *IdentityConfig) *IdentityManager {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultIdentityConfig()
|
||||||
|
}
|
||||||
|
return &IdentityManager{
|
||||||
|
identities: make(map[string]*AgentIdentity),
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateIdentity 铸玺 - 创建新身份
|
||||||
|
func (im *IdentityManager) CreateIdentity(agentID, agentName, systemID string, authSecret string) (*AgentIdentity, error) {
|
||||||
|
if agentID == "" {
|
||||||
|
return nil, fmt.Errorf("agent_id is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
im.mu.Lock()
|
||||||
|
defer im.mu.Unlock()
|
||||||
|
|
||||||
|
if _, exists := im.identities[agentID]; exists {
|
||||||
|
return nil, fmt.Errorf("agent %s already exists", agentID)
|
||||||
|
}
|
||||||
|
|
||||||
|
identity := &AgentIdentity{
|
||||||
|
AgentID: agentID,
|
||||||
|
AgentName: agentName,
|
||||||
|
SystemID: systemID,
|
||||||
|
AuthSecret: authSecret,
|
||||||
|
Roles: []string{"agent"},
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
UpdatedAt: time.Now(),
|
||||||
|
}
|
||||||
|
|
||||||
|
im.identities[agentID] = identity
|
||||||
|
return identity, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetIdentity 获取身份
|
||||||
|
func (im *IdentityManager) GetIdentity(agentID string) (*AgentIdentity, error) {
|
||||||
|
im.mu.RLock()
|
||||||
|
defer im.mu.RUnlock()
|
||||||
|
|
||||||
|
identity, ok := im.identities[agentID]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("agent %s not found", agentID)
|
||||||
|
}
|
||||||
|
return identity, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RevokeIdentity 废玺 - 撤销身份
|
||||||
|
func (im *IdentityManager) RevokeIdentity(agentID string) error {
|
||||||
|
im.mu.Lock()
|
||||||
|
defer im.mu.Unlock()
|
||||||
|
|
||||||
|
identity, ok := im.identities[agentID]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("agent %s not found", agentID)
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
identity.RevokedAt = &now
|
||||||
|
identity.UpdatedAt = now
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsRevoked 检查是否已撤销
|
||||||
|
func (im *IdentityManager) IsRevoked(agentID string) (bool, error) {
|
||||||
|
im.mu.RLock()
|
||||||
|
defer im.mu.RUnlock()
|
||||||
|
|
||||||
|
identity, ok := im.identities[agentID]
|
||||||
|
if !ok {
|
||||||
|
return false, fmt.Errorf("agent %s not found", agentID)
|
||||||
|
}
|
||||||
|
|
||||||
|
return identity.RevokedAt != nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Signature - 签名验证
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// SignatureAlgorithm 签名算法
|
||||||
|
type SignatureAlgorithm string
|
||||||
|
|
||||||
|
const (
|
||||||
|
AlgHMACSHA256 SignatureAlgorithm = "HMAC-SHA256"
|
||||||
|
AlgHMACSHA512 SignatureAlgorithm = "HMAC-SHA512"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Signer 签名器
|
||||||
|
type Signer struct {
|
||||||
|
algorithm SignatureAlgorithm
|
||||||
|
secret string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSigner 创建签名器
|
||||||
|
func NewSigner(algorithm SignatureAlgorithm, secret string) *Signer {
|
||||||
|
if algorithm == "" {
|
||||||
|
algorithm = AlgHMACSHA256
|
||||||
|
}
|
||||||
|
return &Signer{
|
||||||
|
algorithm: algorithm,
|
||||||
|
secret: secret,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SignMessage 对消息签名
|
||||||
|
func (s *Signer) SignMessage(msg *types.UnifiedSynapseMessage) error {
|
||||||
|
if msg == nil {
|
||||||
|
return fmt.Errorf("message is nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构造待签名内容:sender_id + receiver_id + timestamp + payload
|
||||||
|
payloadJSON, _ := json.Marshal(msg.Payload)
|
||||||
|
signContent := fmt.Sprintf("%s|%s|%s|%s",
|
||||||
|
msg.Sender.AgentID,
|
||||||
|
msg.Receiver.AgentID,
|
||||||
|
string(msg.Timestamp),
|
||||||
|
string(payloadJSON),
|
||||||
|
)
|
||||||
|
|
||||||
|
signature, err := s.sign([]byte(signContent))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
msg.Signature = hex.EncodeToString(signature)
|
||||||
|
msg.SignatureAlgorithm = string(s.algorithm)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifySignature 验证消息签名
|
||||||
|
func (s *Signer) VerifySignature(msg *types.UnifiedSynapseMessage) (bool, error) {
|
||||||
|
if msg == nil || msg.Signature == "" {
|
||||||
|
return false, fmt.Errorf("no signature to verify")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构造待签名内容
|
||||||
|
payloadJSON, _ := json.Marshal(msg.Payload)
|
||||||
|
signContent := fmt.Sprintf("%s|%s|%s|%s",
|
||||||
|
msg.Sender.AgentID,
|
||||||
|
msg.Receiver.AgentID,
|
||||||
|
string(msg.Timestamp),
|
||||||
|
string(payloadJSON),
|
||||||
|
)
|
||||||
|
|
||||||
|
expectedSig, err := s.sign([]byte(signContent))
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
actualSig, err := hex.DecodeString(msg.Signature)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("invalid signature format: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return hmac.Equal(expectedSig, actualSig), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// sign 生成 HMAC 签名
|
||||||
|
func (s *Signer) sign(data []byte) ([]byte, error) {
|
||||||
|
var h hash.Hash
|
||||||
|
|
||||||
|
switch s.algorithm {
|
||||||
|
case AlgHMACSHA256:
|
||||||
|
h = hmac.New(sha256.New, []byte(s.secret))
|
||||||
|
case AlgHMACSHA512:
|
||||||
|
h = hmac.New(sha512.New, []byte(s.secret))
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported algorithm: %s", s.algorithm)
|
||||||
|
}
|
||||||
|
|
||||||
|
h.Write(data)
|
||||||
|
return h.Sum(nil), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Auth Token - 认证令牌
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// AuthToken 认证令牌
|
||||||
|
type AuthToken struct {
|
||||||
|
TokenID string `json:"token_id"`
|
||||||
|
AgentID string `json:"agent_id"`
|
||||||
|
SystemID string `json:"system_id"`
|
||||||
|
Roles []string `json:"roles"`
|
||||||
|
IssuedAt time.Time `json:"issued_at"`
|
||||||
|
ExpiresAt time.Time `json:"expires_at"`
|
||||||
|
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TokenManager 令牌管理器
|
||||||
|
type TokenManager struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
tokens map[string]*AuthToken // token_id -> token
|
||||||
|
config *TokenConfig
|
||||||
|
signer *Signer
|
||||||
|
}
|
||||||
|
|
||||||
|
// TokenConfig 令牌配置
|
||||||
|
type TokenConfig struct {
|
||||||
|
DefaultTTL time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultTokenConfig 返回默认令牌配置
|
||||||
|
func DefaultTokenConfig() *TokenConfig {
|
||||||
|
return &TokenConfig{
|
||||||
|
DefaultTTL: 24 * time.Hour,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTokenManager 创建令牌管理器
|
||||||
|
func NewTokenManager(signer *Signer, config *TokenConfig) *TokenManager {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultTokenConfig()
|
||||||
|
}
|
||||||
|
return &TokenManager{
|
||||||
|
tokens: make(map[string]*AuthToken),
|
||||||
|
config: config,
|
||||||
|
signer: signer,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// IssueToken 颁发令牌
|
||||||
|
func (tm *TokenManager) IssueToken(agentID, systemID string, roles []string) (*AuthToken, string, error) {
|
||||||
|
tm.mu.Lock()
|
||||||
|
defer tm.mu.Unlock()
|
||||||
|
|
||||||
|
tokenID := fmt.Sprintf("token-%d", time.Now().UnixNano())
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
token := &AuthToken{
|
||||||
|
TokenID: tokenID,
|
||||||
|
AgentID: agentID,
|
||||||
|
SystemID: systemID,
|
||||||
|
Roles: roles,
|
||||||
|
IssuedAt: now,
|
||||||
|
ExpiresAt: now.Add(tm.config.DefaultTTL),
|
||||||
|
}
|
||||||
|
|
||||||
|
tm.tokens[tokenID] = token
|
||||||
|
|
||||||
|
// 生成签名令牌字符串
|
||||||
|
tokenJSON, _ := json.Marshal(token)
|
||||||
|
signature, _ := tm.signer.sign(tokenJSON)
|
||||||
|
signedToken := fmt.Sprintf("%s.%s", string(tokenJSON), hex.EncodeToString(signature))
|
||||||
|
|
||||||
|
return token, signedToken, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateToken 验证令牌
|
||||||
|
func (tm *TokenManager) ValidateToken(signedToken string) (*AuthToken, error) {
|
||||||
|
// 解析令牌(简化实现)
|
||||||
|
parts := splitToken(signedToken)
|
||||||
|
if len(parts) != 2 {
|
||||||
|
return nil, fmt.Errorf("invalid token format")
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenJSON := []byte(parts[0])
|
||||||
|
signature, err := hex.DecodeString(parts[1])
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid signature format")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证签名
|
||||||
|
expectedSig, err := tm.signer.sign(tokenJSON)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if !hmac.Equal(expectedSig, signature) {
|
||||||
|
return nil, fmt.Errorf("invalid token signature")
|
||||||
|
}
|
||||||
|
|
||||||
|
var token AuthToken
|
||||||
|
if err := json.Unmarshal(tokenJSON, &token); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid token payload")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查过期
|
||||||
|
if time.Now().After(token.ExpiresAt) {
|
||||||
|
return nil, fmt.Errorf("token expired")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RevokeToken 撤销令牌
|
||||||
|
func (tm *TokenManager) RevokeToken(tokenID string) error {
|
||||||
|
tm.mu.Lock()
|
||||||
|
defer tm.mu.Unlock()
|
||||||
|
|
||||||
|
delete(tm.tokens, tokenID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitToken(s string) []string {
|
||||||
|
// 简化实现,找最后一个点
|
||||||
|
for i := len(s) - 1; i >= 0; i-- {
|
||||||
|
if s[i] == '.' {
|
||||||
|
return []string{s[:i], s[i+1:]}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return []string{s}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Authorization - 授权检查
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// Authorizer 授权检查器
|
||||||
|
type Authorizer struct {
|
||||||
|
identityMgr *IdentityManager
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewAuthorizer 创建授权检查器
|
||||||
|
func NewAuthorizer(identityMgr *IdentityManager) *Authorizer {
|
||||||
|
return &Authorizer{
|
||||||
|
identityMgr: identityMgr,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasRole 检查角色
|
||||||
|
func (a *Authorizer) HasRole(agentID, role string) (bool, error) {
|
||||||
|
identity, err := a.identityMgr.GetIdentity(agentID)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, r := range identity.Roles {
|
||||||
|
if r == role {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasPermission 检查权限
|
||||||
|
func (a *Authorizer) HasPermission(agentID, permission string) (bool, error) {
|
||||||
|
identity, err := a.identityMgr.GetIdentity(agentID)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, p := range identity.Permissions {
|
||||||
|
if p == permission {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CanSendMessage 检查是否可以发送消息
|
||||||
|
func (a *Authorizer) CanSendMessage(fromAgentID, toAgentID string, msgType string) (bool, error) {
|
||||||
|
// 检查发送方是否存在且未被撤销
|
||||||
|
fromIdentity, err := a.identityMgr.GetIdentity(fromAgentID)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if fromIdentity.RevokedAt != nil {
|
||||||
|
return false, fmt.Errorf("sender identity revoked")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查接收方是否存在
|
||||||
|
_, err = a.identityMgr.GetIdentity(toAgentID)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
523
speculum/speculum.go
Normal file
523
speculum/speculum.go
Normal file
@@ -0,0 +1,523 @@
|
|||||||
|
// Package speculum 灵鉴 - 共识与裁决层
|
||||||
|
//
|
||||||
|
// 古有"以史为鉴",今有"以智为鉴"。
|
||||||
|
// 此层不是粗暴的少数服从多数,而是让各方 Agent
|
||||||
|
// 将推理过程"照"进公共镜面,通过对比逻辑链的
|
||||||
|
// 严密性来达成共识,如青天明镜,照破虚妄。
|
||||||
|
package speculum
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Consensus Engine - 共识引擎
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// ConsensusType 共识类型
|
||||||
|
type ConsensusType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
ConsensusMajority ConsensusType = "majority" // 多数投票
|
||||||
|
ConsensusSupermajority ConsensusType = "supermajority" // 绝对多数(2/3)
|
||||||
|
ConsensusUnanimity ConsensusType = "unanimity" // 一致同意
|
||||||
|
ConsensusWeighted ConsensusType = "weighted" // 加权投票
|
||||||
|
ConsensusRanked ConsensusType = "ranked" // 排序投票
|
||||||
|
)
|
||||||
|
|
||||||
|
// VoteOption 投票选项
|
||||||
|
type VoteOption struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Description string `json:"description,omitempty"`
|
||||||
|
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vote 投票
|
||||||
|
type Vote struct {
|
||||||
|
VoteID string
|
||||||
|
Question string
|
||||||
|
Options []VoteOption
|
||||||
|
Type ConsensusType
|
||||||
|
Initiator string
|
||||||
|
Participants []string
|
||||||
|
Votes map[string]string // voter_id -> option_id
|
||||||
|
Weights map[string]float64 // voter_id -> 权重
|
||||||
|
Status VoteStatus
|
||||||
|
Deadline time.Time
|
||||||
|
Result *VoteResult
|
||||||
|
Reasoning map[string]string // voter_id -> 推理理由
|
||||||
|
}
|
||||||
|
|
||||||
|
// VoteStatus 投票状态
|
||||||
|
type VoteStatus string
|
||||||
|
|
||||||
|
const (
|
||||||
|
VotePending VoteStatus = "pending"
|
||||||
|
VoteActive VoteStatus = "active"
|
||||||
|
VoteClosed VoteStatus = "closed"
|
||||||
|
VoteTied VoteStatus = "tied"
|
||||||
|
)
|
||||||
|
|
||||||
|
// VoteResult 投票结果
|
||||||
|
type VoteResult struct {
|
||||||
|
Winner string
|
||||||
|
WinOption VoteOption
|
||||||
|
VoteCounts map[string]int
|
||||||
|
Passed bool
|
||||||
|
Margin float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConsensusEngine 共识引擎
|
||||||
|
type ConsensusEngine struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
votes map[string]*Vote
|
||||||
|
config *ConsensusConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConsensusConfig 共识配置
|
||||||
|
type ConsensusConfig struct {
|
||||||
|
DefaultType ConsensusType
|
||||||
|
DefaultTimeout time.Duration
|
||||||
|
QuorumSize int
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultConsensusConfig 返回默认共识配置
|
||||||
|
func DefaultConsensusConfig() *ConsensusConfig {
|
||||||
|
return &ConsensusConfig{
|
||||||
|
DefaultType: ConsensusMajority,
|
||||||
|
DefaultTimeout: 5 * time.Minute,
|
||||||
|
QuorumSize: 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewConsensusEngine 创建共识引擎
|
||||||
|
func NewConsensusEngine(config *ConsensusConfig) *ConsensusEngine {
|
||||||
|
if config == nil {
|
||||||
|
config = DefaultConsensusConfig()
|
||||||
|
}
|
||||||
|
return &ConsensusEngine{
|
||||||
|
votes: make(map[string]*Vote),
|
||||||
|
config: config,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// InitiateVote 发起投票
|
||||||
|
func (ce *ConsensusEngine) InitiateVote(
|
||||||
|
voteID, question string,
|
||||||
|
options []VoteOption,
|
||||||
|
initiator string,
|
||||||
|
participants []string,
|
||||||
|
consensusType ConsensusType,
|
||||||
|
deadline time.Time,
|
||||||
|
) (*Vote, error) {
|
||||||
|
|
||||||
|
if voteID == "" {
|
||||||
|
voteID = fmt.Sprintf("vote-%d", time.Now().UnixNano())
|
||||||
|
}
|
||||||
|
if consensusType == "" {
|
||||||
|
consensusType = ce.config.DefaultType
|
||||||
|
}
|
||||||
|
if deadline.IsZero() {
|
||||||
|
deadline = time.Now().Add(ce.config.DefaultTimeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
ce.mu.Lock()
|
||||||
|
defer ce.mu.Unlock()
|
||||||
|
|
||||||
|
vote := &Vote{
|
||||||
|
VoteID: voteID,
|
||||||
|
Question: question,
|
||||||
|
Options: options,
|
||||||
|
Type: consensusType,
|
||||||
|
Initiator: initiator,
|
||||||
|
Participants: participants,
|
||||||
|
Votes: make(map[string]string),
|
||||||
|
Weights: make(map[string]float64),
|
||||||
|
Status: VoteActive,
|
||||||
|
Deadline: deadline,
|
||||||
|
Reasoning: make(map[string]string),
|
||||||
|
}
|
||||||
|
|
||||||
|
// 默认权重相同
|
||||||
|
for _, p := range participants {
|
||||||
|
vote.Weights[p] = 1.0
|
||||||
|
}
|
||||||
|
|
||||||
|
ce.votes[voteID] = vote
|
||||||
|
|
||||||
|
log.Printf("[灵鉴] 发起投票: %s (发起者: %s, 类型: %s, 参与者: %d人)",
|
||||||
|
voteID, initiator, consensusType, len(participants))
|
||||||
|
|
||||||
|
return vote, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SubmitVote 提交投票
|
||||||
|
func (ce *ConsensusEngine) SubmitVote(voteID, voterID, optionID, reasoning string) error {
|
||||||
|
ce.mu.Lock()
|
||||||
|
defer ce.mu.Unlock()
|
||||||
|
|
||||||
|
vote, ok := ce.votes[voteID]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("vote %s not found", voteID)
|
||||||
|
}
|
||||||
|
|
||||||
|
if vote.Status != VoteActive {
|
||||||
|
return fmt.Errorf("vote is not active (status: %s)", vote.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否是参与者
|
||||||
|
isParticipant := false
|
||||||
|
for _, p := range vote.Participants {
|
||||||
|
if p == voterID {
|
||||||
|
isParticipant = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !isParticipant {
|
||||||
|
return fmt.Errorf("voter %s is not a participant", voterID)
|
||||||
|
}
|
||||||
|
|
||||||
|
vote.Votes[voterID] = optionID
|
||||||
|
if reasoning != "" {
|
||||||
|
vote.Reasoning[voterID] = reasoning
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("[灵鉴] %s 投票: %s -> %s", voterID, voteID, optionID)
|
||||||
|
|
||||||
|
// 检查是否所有参与者都已投票,可以提前结束
|
||||||
|
if len(vote.Votes) >= len(vote.Participants) {
|
||||||
|
ce.countVotesLocked(vote)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CloseVote 关闭投票并统计结果
|
||||||
|
func (ce *ConsensusEngine) CloseVote(voteID string) (*VoteResult, error) {
|
||||||
|
ce.mu.Lock()
|
||||||
|
defer ce.mu.Unlock()
|
||||||
|
|
||||||
|
vote, ok := ce.votes[voteID]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("vote %s not found", voteID)
|
||||||
|
}
|
||||||
|
|
||||||
|
if vote.Status != VoteActive {
|
||||||
|
return vote.Result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return ce.countVotesLocked(vote), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// countVotesLocked 统计投票(调用者需持有锁)
|
||||||
|
func (ce *ConsensusEngine) countVotesLocked(vote *Vote) *VoteResult {
|
||||||
|
vote.Status = VoteClosed
|
||||||
|
|
||||||
|
// 统计票数
|
||||||
|
voteCounts := make(map[string]int)
|
||||||
|
for _, optID := range vote.Votes {
|
||||||
|
voteCounts[optID]++
|
||||||
|
}
|
||||||
|
|
||||||
|
// 找出获胜者
|
||||||
|
var winner string
|
||||||
|
maxVotes := 0
|
||||||
|
for optID, count := range voteCounts {
|
||||||
|
if count > maxVotes {
|
||||||
|
maxVotes = count
|
||||||
|
winner = optID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算是否通过
|
||||||
|
totalVotes := len(vote.Votes)
|
||||||
|
required := ce.getRequiredVotes(vote, totalVotes)
|
||||||
|
passed := maxVotes >= required && totalVotes >= ce.config.QuorumSize
|
||||||
|
|
||||||
|
// 查找获胜选项
|
||||||
|
var winOption VoteOption
|
||||||
|
for _, opt := range vote.Options {
|
||||||
|
if opt.ID == winner {
|
||||||
|
winOption = opt
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result := &VoteResult{
|
||||||
|
Winner: winner,
|
||||||
|
WinOption: winOption,
|
||||||
|
VoteCounts: voteCounts,
|
||||||
|
Passed: passed,
|
||||||
|
Margin: float64(maxVotes) / float64(totalVotes),
|
||||||
|
}
|
||||||
|
|
||||||
|
vote.Result = result
|
||||||
|
|
||||||
|
log.Printf("[灵鉴] 投票结果: %s -> %s (通过: %v, 得票率: %.1f%%)",
|
||||||
|
vote.VoteID, winner, passed, result.Margin*100)
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// getRequiredVotes 获取所需票数
|
||||||
|
func (ce *ConsensusEngine) getRequiredVotes(vote *Vote, total int) int {
|
||||||
|
switch vote.Type {
|
||||||
|
case ConsensusUnanimity:
|
||||||
|
return total
|
||||||
|
case ConsensusSupermajority:
|
||||||
|
return (total*2)/3 + 1
|
||||||
|
case ConsensusMajority:
|
||||||
|
return total/2 + 1
|
||||||
|
default:
|
||||||
|
return total/2 + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetVote 获取投票信息
|
||||||
|
func (ce *ConsensusEngine) GetVote(voteID string) (*Vote, error) {
|
||||||
|
ce.mu.RLock()
|
||||||
|
defer ce.mu.RUnlock()
|
||||||
|
|
||||||
|
vote, ok := ce.votes[voteID]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("vote %s not found", voteID)
|
||||||
|
}
|
||||||
|
return vote, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAllVotes 获取所有投票
|
||||||
|
func (ce *ConsensusEngine) GetAllVotes() []*Vote {
|
||||||
|
ce.mu.RLock()
|
||||||
|
defer ce.mu.RUnlock()
|
||||||
|
|
||||||
|
votes := make([]*Vote, 0, len(ce.votes))
|
||||||
|
for _, v := range ce.votes {
|
||||||
|
votes = append(votes, v)
|
||||||
|
}
|
||||||
|
return votes
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Arbitration - 仲裁机制
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// Arbitrator 仲裁者
|
||||||
|
type Arbitrator struct {
|
||||||
|
consensusEngine *ConsensusEngine
|
||||||
|
rules []ArbitrationRule
|
||||||
|
mu sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// ArbitrationRule 仲裁规则
|
||||||
|
type ArbitrationRule struct {
|
||||||
|
ID string
|
||||||
|
Name string
|
||||||
|
Description string
|
||||||
|
Priority int
|
||||||
|
Evaluate func(ctx context.Context, dispute *Dispute) (string, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dispute 争议
|
||||||
|
type Dispute struct {
|
||||||
|
DisputeID string
|
||||||
|
Topic string
|
||||||
|
Description string
|
||||||
|
Parties []string
|
||||||
|
Evidence map[string][]byte
|
||||||
|
SubmittedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// ArbitrationResult 仲裁结果
|
||||||
|
type ArbitrationResult struct {
|
||||||
|
DisputeID string
|
||||||
|
Winner string
|
||||||
|
Reason string
|
||||||
|
Evidence []string
|
||||||
|
DecidedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewArbitrator 创建仲裁者
|
||||||
|
func NewArbitrator(consensusEngine *ConsensusEngine) *Arbitrator {
|
||||||
|
return &Arbitrator{
|
||||||
|
consensusEngine: consensusEngine,
|
||||||
|
rules: make([]ArbitrationRule, 0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddRule 添加仲裁规则
|
||||||
|
func (a *Arbitrator) AddRule(rule ArbitrationRule) {
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
|
||||||
|
a.rules = append(a.rules, rule)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Arbitrate 仲裁
|
||||||
|
func (a *Arbitrator) Arbitrate(ctx context.Context, dispute *Dispute) (*ArbitrationResult, error) {
|
||||||
|
a.mu.RLock()
|
||||||
|
defer a.mu.RUnlock()
|
||||||
|
|
||||||
|
log.Printf("[灵鉴] 开始仲裁: %s (%s)", dispute.DisputeID, dispute.Topic)
|
||||||
|
|
||||||
|
// 按优先级执行规则
|
||||||
|
for _, rule := range a.rules {
|
||||||
|
result, err := rule.Evaluate(ctx, dispute)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[灵鉴] 规则 %s 执行失败: %v", rule.Name, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if result != "" {
|
||||||
|
return &ArbitrationResult{
|
||||||
|
DisputeID: dispute.DisputeID,
|
||||||
|
Winner: result,
|
||||||
|
Reason: fmt.Sprintf("规则 %s 判定", rule.Name),
|
||||||
|
DecidedAt: time.Now(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果没有规则匹配,使用投票
|
||||||
|
return a.arbitrateByVote(ctx, dispute)
|
||||||
|
}
|
||||||
|
|
||||||
|
// arbitrateByVote 通过投票仲裁
|
||||||
|
func (a *Arbitrator) arbitrateByVote(ctx context.Context, dispute *Dispute) (*ArbitrationResult, error) {
|
||||||
|
options := make([]VoteOption, len(dispute.Parties))
|
||||||
|
for i, p := range dispute.Parties {
|
||||||
|
options[i] = VoteOption{
|
||||||
|
ID: p,
|
||||||
|
Title: p,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
vote, err := a.consensusEngine.InitiateVote(
|
||||||
|
fmt.Sprintf("arbitration-%s", dispute.DisputeID),
|
||||||
|
dispute.Topic,
|
||||||
|
options,
|
||||||
|
"arbitrator",
|
||||||
|
dispute.Parties,
|
||||||
|
ConsensusMajority,
|
||||||
|
time.Now().Add(5*time.Minute),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := a.consensusEngine.CloseVote(vote.VoteID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &ArbitrationResult{
|
||||||
|
DisputeID: dispute.DisputeID,
|
||||||
|
Winner: result.Winner,
|
||||||
|
Reason: "投票裁决",
|
||||||
|
DecidedAt: time.Now(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Reasoning Mirror - 推理镜面
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
// ReasoningMirror 推理镜面
|
||||||
|
// 让各方 Agent 将推理过程"照"进公共镜面,
|
||||||
|
// 通过对比逻辑链的严密性来达成共识
|
||||||
|
type ReasoningMirror struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
reasonings map[string]*ReasoningChain // chain_id -> 推理链
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReasoningChain 推理链
|
||||||
|
type ReasoningChain struct {
|
||||||
|
ChainID string
|
||||||
|
AgentID string
|
||||||
|
Topic string
|
||||||
|
Steps []ReasoningStep
|
||||||
|
Score float64
|
||||||
|
SubmittedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReasoningStep 推理步骤
|
||||||
|
type ReasoningStep struct {
|
||||||
|
StepID string
|
||||||
|
Description string
|
||||||
|
Evidence []string
|
||||||
|
Confidence float64
|
||||||
|
Next []string // 下一步的ID
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewReasoningMirror 创建推理镜面
|
||||||
|
func NewReasoningMirror() *ReasoningMirror {
|
||||||
|
return &ReasoningMirror{
|
||||||
|
reasonings: make(map[string]*ReasoningChain),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SubmitReasoning 提交推理链
|
||||||
|
func (rm *ReasoningMirror) SubmitReasoning(chain *ReasoningChain) error {
|
||||||
|
if chain == nil {
|
||||||
|
return fmt.Errorf("reasoning chain is nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
rm.mu.Lock()
|
||||||
|
defer rm.mu.Unlock()
|
||||||
|
|
||||||
|
rm.reasonings[chain.ChainID] = chain
|
||||||
|
log.Printf("[灵鉴] %s 提交推理链: %s (步骤: %d)", chain.AgentID, chain.Topic, len(chain.Steps))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CompareReasonings 比较推理链的严密性
|
||||||
|
func (rm *ReasoningMirror) CompareReasonings(chainIDs []string) (string, error) {
|
||||||
|
rm.mu.RLock()
|
||||||
|
defer rm.mu.RUnlock()
|
||||||
|
|
||||||
|
var bestChain string
|
||||||
|
bestScore := -1.0
|
||||||
|
|
||||||
|
for _, id := range chainIDs {
|
||||||
|
chain, ok := rm.reasonings[id]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算推理链得分(简化:平均置信度 * 步骤数权重)
|
||||||
|
if chain.Score > bestScore {
|
||||||
|
bestScore = chain.Score
|
||||||
|
bestChain = id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if bestChain == "" {
|
||||||
|
return "", fmt.Errorf("no valid reasoning chains found")
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("[灵鉴] 推理比较胜出: %s (得分: %.2f)", bestChain, bestScore)
|
||||||
|
return bestChain, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetReasoning 获取推理链
|
||||||
|
func (rm *ReasoningMirror) GetReasoning(chainID string) (*ReasoningChain, error) {
|
||||||
|
rm.mu.RLock()
|
||||||
|
defer rm.mu.RUnlock()
|
||||||
|
|
||||||
|
chain, ok := rm.reasonings[chainID]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("reasoning chain %s not found", chainID)
|
||||||
|
}
|
||||||
|
return chain, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToJSON 导出为 JSON
|
||||||
|
func (v *Vote) ToJSON() string {
|
||||||
|
data, _ := json.MarshalIndent(v, "", " ")
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
512
types/types_test.go
Normal file
512
types/types_test.go
Normal file
@@ -0,0 +1,512 @@
|
|||||||
|
package types
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 基础类型测试
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func TestGenerateMessageID(t *testing.T) {
|
||||||
|
id := GenerateMessageID()
|
||||||
|
|
||||||
|
if id == "" {
|
||||||
|
t.Error("Message ID should not be empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证格式(msg-前缀)
|
||||||
|
if !startsWith(id, "msg-") {
|
||||||
|
t.Errorf("Message ID should have msg- prefix: %s", id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenerateTaskID(t *testing.T) {
|
||||||
|
id := GenerateTaskID()
|
||||||
|
|
||||||
|
if id == "" {
|
||||||
|
t.Error("Task ID should not be empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证格式(task-前缀)
|
||||||
|
if !startsWith(id, "task-") {
|
||||||
|
t.Errorf("Task ID should have task- prefix: %s", id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNowTimestamp(t *testing.T) {
|
||||||
|
ts := NowTimestamp()
|
||||||
|
if ts == "" {
|
||||||
|
t.Error("Timestamp should not be empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证可以解析为时间
|
||||||
|
parsed, err := ts.Time()
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Failed to parse timestamp: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证时间接近当前时间
|
||||||
|
now := time.Now().UTC()
|
||||||
|
diff := now.Sub(parsed)
|
||||||
|
if diff > time.Minute || diff < -time.Minute {
|
||||||
|
t.Errorf("Timestamp difference too large: %v", diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTimestampTime(t *testing.T) {
|
||||||
|
ts := Timestamp("2026-06-27T10:00:00Z")
|
||||||
|
parsed, err := ts.Time()
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Failed to parse timestamp: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
expected := time.Date(2026, 6, 27, 10, 0, 0, 0, time.UTC)
|
||||||
|
if !parsed.Equal(expected) {
|
||||||
|
t.Errorf("Parsed time mismatch: got %v, want %v", parsed, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// AgentEndpoint 测试
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func TestAgentEndpointJSON(t *testing.T) {
|
||||||
|
ep := AgentEndpoint{
|
||||||
|
AgentID: "agent-001",
|
||||||
|
AgentName: "TestAgent",
|
||||||
|
SystemID: "system-001",
|
||||||
|
Endpoint: "http://localhost:8080",
|
||||||
|
Version: "1.0.0",
|
||||||
|
}
|
||||||
|
|
||||||
|
// 序列化
|
||||||
|
data, err := json.Marshal(ep)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Failed to marshal AgentEndpoint: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 反序列化
|
||||||
|
var parsed AgentEndpoint
|
||||||
|
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||||
|
t.Errorf("Failed to unmarshal AgentEndpoint: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if parsed.AgentID != ep.AgentID {
|
||||||
|
t.Errorf("AgentID mismatch: got %s, want %s", parsed.AgentID, ep.AgentID)
|
||||||
|
}
|
||||||
|
if parsed.Endpoint != ep.Endpoint {
|
||||||
|
t.Errorf("Endpoint mismatch: got %s, want %s", parsed.Endpoint, ep.Endpoint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// UnifiedSynapseMessage 测试
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func TestUnifiedSynapseMessageJSON(t *testing.T) {
|
||||||
|
receiver := &AgentEndpoint{
|
||||||
|
AgentID: "agent-002",
|
||||||
|
Endpoint: "http://localhost:8081",
|
||||||
|
}
|
||||||
|
|
||||||
|
msg := UnifiedSynapseMessage{
|
||||||
|
ID: GenerateMessageID(),
|
||||||
|
Version: "1.0.0",
|
||||||
|
Type: string(P2PTaskRequest),
|
||||||
|
Sender: AgentEndpoint{AgentID: "agent-001", Endpoint: "http://localhost:8080"},
|
||||||
|
Receiver: receiver,
|
||||||
|
Payload: json.RawMessage(`{"task": {"id": "task-001"}}`),
|
||||||
|
Timestamp: NowTimestamp(),
|
||||||
|
Priority: PriorityNormal,
|
||||||
|
}
|
||||||
|
|
||||||
|
// 序列化
|
||||||
|
data, err := json.Marshal(msg)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Failed to marshal message: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 反序列化
|
||||||
|
var parsed UnifiedSynapseMessage
|
||||||
|
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||||
|
t.Errorf("Failed to unmarshal message: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if parsed.ID != msg.ID {
|
||||||
|
t.Errorf("Message ID mismatch")
|
||||||
|
}
|
||||||
|
if parsed.Type != msg.Type {
|
||||||
|
t.Errorf("Message type mismatch: got %s, want %s", parsed.Type, msg.Type)
|
||||||
|
}
|
||||||
|
if parsed.Receiver.AgentID != receiver.AgentID {
|
||||||
|
t.Errorf("Receiver AgentID mismatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnifiedSynapseMessageGroupContext(t *testing.T) {
|
||||||
|
msg := UnifiedSynapseMessage{
|
||||||
|
ID: GenerateMessageID(),
|
||||||
|
Version: "1.0.0",
|
||||||
|
Type: string(GroupBroadcast),
|
||||||
|
Sender: AgentEndpoint{AgentID: "agent-001"},
|
||||||
|
GroupID: "group-001",
|
||||||
|
TargetType: "all",
|
||||||
|
Broadcast: true,
|
||||||
|
Payload: json.RawMessage(`{"message": "hello"}`),
|
||||||
|
Timestamp: NowTimestamp(),
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := json.Marshal(msg)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Failed to marshal group message: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var parsed UnifiedSynapseMessage
|
||||||
|
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||||
|
t.Errorf("Failed to unmarshal group message: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if parsed.GroupID != "group-001" {
|
||||||
|
t.Errorf("GroupID mismatch: got %s, want group-001", parsed.GroupID)
|
||||||
|
}
|
||||||
|
if !parsed.Broadcast {
|
||||||
|
t.Error("Broadcast should be true")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// P2P Payload 测试
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func TestTaskRequestPayloadJSON(t *testing.T) {
|
||||||
|
payload := TaskRequestPayload{}
|
||||||
|
payload.Task.ID = "task-001"
|
||||||
|
payload.Task.Type = "text_generation"
|
||||||
|
payload.Task.Priority = PriorityNormal
|
||||||
|
payload.Task.Payload = map[string]interface{}{
|
||||||
|
"prompt": "写一首诗",
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Failed to marshal TaskRequestPayload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var parsed TaskRequestPayload
|
||||||
|
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||||
|
t.Errorf("Failed to unmarshal TaskRequestPayload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if parsed.Task.ID != "task-001" {
|
||||||
|
t.Errorf("Task ID mismatch")
|
||||||
|
}
|
||||||
|
if parsed.Task.Type != "text_generation" {
|
||||||
|
t.Errorf("Task type mismatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTaskConfirmPayloadJSON(t *testing.T) {
|
||||||
|
payload := TaskConfirmPayload{
|
||||||
|
TaskID: "task-001",
|
||||||
|
Confirmed: true,
|
||||||
|
EstimatedDuration: 60,
|
||||||
|
ExpectedCompletion: NowTimestamp(),
|
||||||
|
CapabilitiesUsed: []string{"text_gen"},
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Failed to marshal TaskConfirmPayload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var parsed TaskConfirmPayload
|
||||||
|
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||||
|
t.Errorf("Failed to unmarshal TaskConfirmPayload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if parsed.TaskID != "task-001" {
|
||||||
|
t.Errorf("TaskID mismatch")
|
||||||
|
}
|
||||||
|
if !payload.Confirmed {
|
||||||
|
t.Error("Confirmed should be true")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTaskStatusUpdatePayloadJSON(t *testing.T) {
|
||||||
|
payload := TaskStatusUpdatePayload{
|
||||||
|
TaskID: "task-001",
|
||||||
|
Status: "executing",
|
||||||
|
Progress: 50,
|
||||||
|
Message: "Processing...",
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Failed to marshal TaskStatusUpdatePayload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var parsed TaskStatusUpdatePayload
|
||||||
|
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||||
|
t.Errorf("Failed to unmarshal TaskStatusUpdatePayload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if parsed.Progress != 50 {
|
||||||
|
t.Errorf("Progress mismatch: got %d, want 50", parsed.Progress)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Group Payload 测试
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func TestGroupCreatePayloadJSON(t *testing.T) {
|
||||||
|
payload := GroupCreatePayload{}
|
||||||
|
payload.Group.Name = "TestGroup"
|
||||||
|
payload.Group.Topology = GroupTopologyStar
|
||||||
|
payload.Group.Config = GroupConfig{
|
||||||
|
AllowSelfLeave: true,
|
||||||
|
ConsensusRequired: false,
|
||||||
|
ConsensusThreshold: 0.5,
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Failed to marshal GroupCreatePayload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var parsed GroupCreatePayload
|
||||||
|
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||||
|
t.Errorf("Failed to unmarshal GroupCreatePayload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if parsed.Group.Name != "TestGroup" {
|
||||||
|
t.Errorf("Group name mismatch")
|
||||||
|
}
|
||||||
|
if parsed.Group.Topology != GroupTopologyStar {
|
||||||
|
t.Errorf("Topology mismatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGroupTaskSplitPayloadJSON(t *testing.T) {
|
||||||
|
payload := GroupTaskSplitPayload{}
|
||||||
|
payload.OriginalTask.ID = "task-001"
|
||||||
|
payload.OriginalTask.Type = "video_generation"
|
||||||
|
payload.Subtasks = []Subtask{
|
||||||
|
{
|
||||||
|
ID: "sub-001",
|
||||||
|
Description: "Generate scene 1",
|
||||||
|
AssignedTo: "agent-002",
|
||||||
|
Priority: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
ID: "sub-002",
|
||||||
|
Description: "Generate scene 2",
|
||||||
|
AssignedTo: "agent-003",
|
||||||
|
Priority: 2,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
payload.MergeStrategy = MergeMajority
|
||||||
|
|
||||||
|
data, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Failed to marshal GroupTaskSplitPayload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var parsed GroupTaskSplitPayload
|
||||||
|
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||||
|
t.Errorf("Failed to unmarshal GroupTaskSplitPayload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(parsed.Subtasks) != 2 {
|
||||||
|
t.Errorf("Subtasks count mismatch: got %d, want 2", len(parsed.Subtasks))
|
||||||
|
}
|
||||||
|
if parsed.MergeStrategy != MergeMajority {
|
||||||
|
t.Errorf("MergeStrategy mismatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGroupVotePayloadJSON(t *testing.T) {
|
||||||
|
payload := GroupVotePayload{
|
||||||
|
VoteID: "vote-001",
|
||||||
|
Question: "Which approach is better?",
|
||||||
|
Options: []string{"Option A", "Option B", "Option C"},
|
||||||
|
Voters: []string{"agent-001", "agent-002", "agent-003"},
|
||||||
|
Threshold: 0.5,
|
||||||
|
Status: "open",
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Failed to marshal GroupVotePayload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var parsed GroupVotePayload
|
||||||
|
if err := json.Unmarshal(data, &parsed); err != nil {
|
||||||
|
t.Errorf("Failed to unmarshal GroupVotePayload: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(parsed.Options) != 3 {
|
||||||
|
t.Errorf("Options count mismatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 错误码测试
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func TestSynapseErrorCategory(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
code SynapseErrorCode
|
||||||
|
expected string
|
||||||
|
}{
|
||||||
|
{ErrSystemError, "SYSTEM_ERROR"},
|
||||||
|
{ErrTaskNotFound, "TASK_ERROR"},
|
||||||
|
{ErrRequiredFieldMissing, "INFO_ERROR"},
|
||||||
|
{ErrUnsupportedTaskType, "CAPABILITY_ERROR"},
|
||||||
|
{ErrAuthFailed, "SECURITY_ERROR"},
|
||||||
|
{ErrEndpointUnreachable, "COMMUNICATION_ERROR"},
|
||||||
|
{ErrGroupNotFound, "GROUP_ERROR"},
|
||||||
|
{ErrHumanTimeout, "HIL_ERROR"},
|
||||||
|
{ErrInvalidParams, "VALIDATION_ERROR"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
if got := tt.code.Category(); got != tt.expected {
|
||||||
|
t.Errorf("Category for %d: got %s, want %s", tt.code, got, tt.expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewSynapseError(t *testing.T) {
|
||||||
|
err := NewSynapseError(ErrTaskNotFound, "Task not found", map[string]string{"task_id": "task-001"})
|
||||||
|
|
||||||
|
if err.Code != ErrTaskNotFound {
|
||||||
|
t.Errorf("Error code mismatch")
|
||||||
|
}
|
||||||
|
if err.Message != "Task not found" {
|
||||||
|
t.Errorf("Error message mismatch")
|
||||||
|
}
|
||||||
|
if err.Category != "TASK_ERROR" {
|
||||||
|
t.Errorf("Error category mismatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSynapseErrorToMap(t *testing.T) {
|
||||||
|
err := NewSynapseError(ErrTaskNotFound, "Task not found", nil)
|
||||||
|
m := err.ToMap()
|
||||||
|
|
||||||
|
if m["code"] != ErrTaskNotFound {
|
||||||
|
t.Errorf("Map code mismatch")
|
||||||
|
}
|
||||||
|
if m["category"] != "TASK_ERROR" {
|
||||||
|
t.Errorf("Map category mismatch")
|
||||||
|
}
|
||||||
|
if m["message"] != "Task not found" {
|
||||||
|
t.Errorf("Map message mismatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 状态机测试
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func TestP2PTaskStatusValues(t *testing.T) {
|
||||||
|
statuses := []P2PTaskStatus{
|
||||||
|
P2PStatusIdle,
|
||||||
|
P2PStatusPending,
|
||||||
|
P2PStatusConfirmed,
|
||||||
|
P2PStatusExecuting,
|
||||||
|
P2PStatusCompleted,
|
||||||
|
P2PStatusFailed,
|
||||||
|
P2PStatusCancelled,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, s := range statuses {
|
||||||
|
if s == "" {
|
||||||
|
t.Error("Status should not be empty")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGroupStatusValues(t *testing.T) {
|
||||||
|
statuses := []GroupStatus{
|
||||||
|
GroupStatusCreating,
|
||||||
|
GroupStatusActive,
|
||||||
|
GroupStatusFrozen,
|
||||||
|
GroupStatusDisbanded,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, s := range statuses {
|
||||||
|
if s == "" {
|
||||||
|
t.Error("Status should not be empty")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// 消息类型测试
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
func TestP2PMessageTypes(t *testing.T) {
|
||||||
|
types := []P2PMessageType{
|
||||||
|
P2PTaskRequest,
|
||||||
|
P2PTaskConfirm,
|
||||||
|
P2PTaskReject,
|
||||||
|
P2PTaskNeedInfo,
|
||||||
|
P2PTaskInfoProvided,
|
||||||
|
P2PTaskStatusUpdate,
|
||||||
|
P2PTaskComplete,
|
||||||
|
P2PTaskFailed,
|
||||||
|
P2PTaskCancel,
|
||||||
|
P2PTaskAck,
|
||||||
|
P2PAck,
|
||||||
|
P2PNack,
|
||||||
|
P2PHeartbeat,
|
||||||
|
P2PCapabilityQuery,
|
||||||
|
P2PCapabilityResponse,
|
||||||
|
P2PTaskNeedHuman,
|
||||||
|
P2PHumanDecision,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, mt := range types {
|
||||||
|
if mt == "" {
|
||||||
|
t.Error("Message type should not be empty")
|
||||||
|
}
|
||||||
|
// 验证前缀
|
||||||
|
if !startsWith(string(mt), "p2p:") {
|
||||||
|
t.Errorf("P2P message type should have p2p: prefix: %s", mt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGroupMessageTypes(t *testing.T) {
|
||||||
|
groupTypes := []GroupMessageType{
|
||||||
|
GroupCreate,
|
||||||
|
GroupDisband,
|
||||||
|
GroupJoin,
|
||||||
|
GroupLeave,
|
||||||
|
GroupBroadcast,
|
||||||
|
GroupTaskSplit,
|
||||||
|
GroupTaskAssign,
|
||||||
|
GroupTaskMerge,
|
||||||
|
GroupVote,
|
||||||
|
GroupVoteSubmit,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, mt := range groupTypes {
|
||||||
|
if mt == "" {
|
||||||
|
t.Error("Message type should not be empty")
|
||||||
|
}
|
||||||
|
// 验证前缀
|
||||||
|
if !startsWith(string(mt), "group:") {
|
||||||
|
t.Errorf("Group message type should have group: prefix: %s", mt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func startsWith(s, prefix string) bool {
|
||||||
|
return len(s) >= len(prefix) && s[:len(prefix)] == prefix
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user