灵隙(synapse) v1.0.0 版本
This commit is contained in:
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
|
||||
}
|
||||
Reference in New Issue
Block a user