灵隙(synapse) v1.0.0 版本
This commit is contained in:
794
internal/agent/group/protocol.go
Normal file
794
internal/agent/group/protocol.go
Normal file
@@ -0,0 +1,794 @@
|
||||
package group
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Group Protocol Handler
|
||||
// =============================================================================
|
||||
|
||||
// GroupTaskHandler is the interface for handling group task execution
|
||||
type GroupTaskHandler interface {
|
||||
// ExecuteSubtask executes a subtask and returns the result
|
||||
ExecuteSubtask(ctx context.Context, subtaskID string, payload map[string]interface{}) (any, error)
|
||||
|
||||
// MergeResults merges multiple subtask results
|
||||
MergeResults(results []types.SubtaskResult, strategy types.MergeStrategy) (any, error)
|
||||
|
||||
// ValidateTaskSplit validates if a task can be split
|
||||
ValidateTaskSplit(taskType string, requirements map[string]interface{}) ([]types.Subtask, bool)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// GroupProtocol represents the group protocol handler
|
||||
// =============================================================================
|
||||
|
||||
type GroupProtocol struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
// Agent identity
|
||||
agentEndpoint types.AgentEndpoint
|
||||
|
||||
// Group state
|
||||
groups map[string]*types.AgentGroup
|
||||
|
||||
// Membership
|
||||
memberships map[string]string // groupID -> member's role in group
|
||||
|
||||
// Task handler
|
||||
taskHandler GroupTaskHandler
|
||||
|
||||
// Configuration
|
||||
config *GroupConfig
|
||||
}
|
||||
|
||||
// GroupConfig holds group protocol configuration
|
||||
type GroupConfig struct {
|
||||
MaxGroupSize int
|
||||
MaxSubtasks int
|
||||
ConsensusTimeout time.Duration
|
||||
TaskTimeout time.Duration
|
||||
}
|
||||
|
||||
// DefaultGroupConfig returns default group configuration
|
||||
func DefaultGroupConfig() *GroupConfig {
|
||||
return &GroupConfig{
|
||||
MaxGroupSize: 20,
|
||||
MaxSubtasks: 50,
|
||||
ConsensusTimeout: 5 * time.Minute,
|
||||
TaskTimeout: 10 * time.Minute,
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// NewGroupProtocol creates a new group protocol handler
|
||||
// =============================================================================
|
||||
|
||||
func NewGroupProtocol(agentEndpoint types.AgentEndpoint, config *GroupConfig) *GroupProtocol {
|
||||
if config == nil {
|
||||
config = DefaultGroupConfig()
|
||||
}
|
||||
return &GroupProtocol{
|
||||
agentEndpoint: agentEndpoint,
|
||||
groups: make(map[string]*types.AgentGroup),
|
||||
memberships: make(map[string]string),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// SetTaskHandler sets the group task handler
|
||||
func (g *GroupProtocol) SetTaskHandler(h GroupTaskHandler) {
|
||||
g.taskHandler = h
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// HandleMessage processes an incoming group message
|
||||
// =============================================================================
|
||||
|
||||
func (g *GroupProtocol) HandleMessage(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
|
||||
if err := g.validateMessage(msg); err != nil {
|
||||
a2aErr, ok := err.(*types.SynapseError)
|
||||
if !ok {
|
||||
a2aErr = types.NewSynapseError(types.ErrMessageFormatInvalid, err.Error(), nil)
|
||||
}
|
||||
return g.newErrorResponse(msg, a2aErr)
|
||||
}
|
||||
|
||||
switch types.GroupMessageType(msg.Type) {
|
||||
// Group management
|
||||
case types.GroupCreate:
|
||||
return g.handleGroupCreate(ctx, msg)
|
||||
case types.GroupDisband:
|
||||
return g.handleGroupDisband(ctx, msg)
|
||||
case types.GroupJoin:
|
||||
return g.handleGroupJoin(ctx, msg)
|
||||
case types.GroupLeave:
|
||||
return g.handleGroupLeave(ctx, msg)
|
||||
case types.GroupInvite:
|
||||
return g.handleGroupInvite(ctx, msg)
|
||||
case types.GroupAcceptInvite:
|
||||
return g.handleGroupAcceptInvite(ctx, msg)
|
||||
case types.GroupRejectInvite:
|
||||
return g.handleGroupRejectInvite(ctx, msg)
|
||||
|
||||
// Group communication
|
||||
case types.GroupBroadcast:
|
||||
return g.handleGroupBroadcast(ctx, msg)
|
||||
case types.GroupMulticast:
|
||||
return g.handleGroupMulticast(ctx, msg)
|
||||
case types.GroupDirect:
|
||||
return g.handleGroupDirect(ctx, msg)
|
||||
|
||||
// Task collaboration
|
||||
case types.GroupTaskSplit:
|
||||
return g.handleGroupTaskSplit(ctx, msg)
|
||||
case types.GroupTaskAssign:
|
||||
return g.handleGroupTaskAssign(ctx, msg)
|
||||
case types.GroupTaskMerge:
|
||||
return g.handleGroupTaskMerge(ctx, msg)
|
||||
case types.GroupTaskProgress:
|
||||
return g.handleGroupTaskProgress(ctx, msg)
|
||||
|
||||
// Consensus
|
||||
case types.GroupVote:
|
||||
return g.handleGroupVote(ctx, msg)
|
||||
case types.GroupVoteSubmit:
|
||||
return g.handleGroupVoteSubmit(ctx, msg)
|
||||
|
||||
// Human-in-the-Loop
|
||||
case types.GroupConsensusEscalate:
|
||||
return g.handleGroupConsensusEscalate(ctx, msg)
|
||||
case types.GroupSubtaskEscalate:
|
||||
return g.handleGroupSubtaskEscalate(ctx, msg)
|
||||
case types.GroupHumanDecision:
|
||||
return g.handleGroupHumanDecision(ctx, msg)
|
||||
case types.InterGroupEscalate:
|
||||
return g.handleInterGroupEscalate(ctx, msg)
|
||||
|
||||
default:
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(
|
||||
types.ErrMessageFormatInvalid,
|
||||
fmt.Sprintf("Unknown group message type: %s", msg.Type),
|
||||
nil,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Group Management Handlers
|
||||
// =============================================================================
|
||||
|
||||
func (g *GroupProtocol) handleGroupCreate(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.GroupCreatePayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid create payload", err.Error()))
|
||||
}
|
||||
|
||||
// Check permissions (only coordinator can create)
|
||||
// For now, allow any agent to create
|
||||
|
||||
group := &types.AgentGroup{
|
||||
ID: fmt.Sprintf("group-%d", time.Now().UnixNano()),
|
||||
Name: payload.Group.Name,
|
||||
Topology: payload.Group.Topology,
|
||||
CreatedBy: g.agentEndpoint.AgentID,
|
||||
CreatedAt: types.NowTimestamp(),
|
||||
Config: payload.Group.Config,
|
||||
Members: []types.GroupMember{},
|
||||
Roles: payload.Group.Roles,
|
||||
Status: types.GroupStatusActive,
|
||||
}
|
||||
|
||||
// Add creator as first member
|
||||
creator := types.GroupMember{
|
||||
AgentID: g.agentEndpoint.AgentID,
|
||||
AgentName: g.agentEndpoint.AgentName,
|
||||
Role: "coordinator",
|
||||
JoinedAt: types.NowTimestamp(),
|
||||
Status: types.GroupMemberActive,
|
||||
Capabilities: []string{g.agentEndpoint.Version},
|
||||
LoadFactor: 0.0,
|
||||
}
|
||||
group.Members = append(group.Members, creator)
|
||||
|
||||
g.groups[group.ID] = group
|
||||
g.memberships[group.ID] = "coordinator"
|
||||
|
||||
log.Printf("[Group] Group created: %s (topology: %s)", group.ID, group.Topology)
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"group_id": group.ID,
|
||||
"status": "created",
|
||||
})
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleGroupDisband(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload struct {
|
||||
GroupID string `json:"group_id"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid disband payload", err.Error()))
|
||||
}
|
||||
|
||||
group, ok := g.groups[payload.GroupID]
|
||||
if !ok {
|
||||
return g.newErrorResponse(msg, types.ErrGroupNotFoundError)
|
||||
}
|
||||
|
||||
// Check if sender is coordinator
|
||||
senderRole := g.getMemberRole(payload.GroupID, msg.Sender.AgentID)
|
||||
if senderRole != "coordinator" {
|
||||
return g.newErrorResponse(msg, types.ErrPermissionDeniedError)
|
||||
}
|
||||
|
||||
group.Status = types.GroupStatusDisbanded
|
||||
delete(g.groups, payload.GroupID)
|
||||
delete(g.memberships, payload.GroupID)
|
||||
|
||||
log.Printf("[Group] Group disbanded: %s", payload.GroupID)
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"group_id": payload.GroupID,
|
||||
"status": "disbanded",
|
||||
})
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleGroupJoin(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload struct {
|
||||
GroupID string `json:"group_id"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid join payload", err.Error()))
|
||||
}
|
||||
|
||||
group, ok := g.groups[payload.GroupID]
|
||||
if !ok {
|
||||
return g.newErrorResponse(msg, types.ErrGroupNotFoundError)
|
||||
}
|
||||
|
||||
if group.Status != types.GroupStatusActive {
|
||||
return g.newErrorResponse(msg, types.ErrGroupNotActiveError)
|
||||
}
|
||||
|
||||
// Check if already a member
|
||||
for _, m := range group.Members {
|
||||
if m.AgentID == g.agentEndpoint.AgentID {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrAlreadyMember, "Already a member", nil))
|
||||
}
|
||||
}
|
||||
|
||||
// Check group size
|
||||
if len(group.Members) >= g.config.MaxGroupSize {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrGroupFull, "Group is full", nil))
|
||||
}
|
||||
|
||||
// Add as member
|
||||
member := types.GroupMember{
|
||||
AgentID: g.agentEndpoint.AgentID,
|
||||
AgentName: g.agentEndpoint.AgentName,
|
||||
Role: "worker",
|
||||
JoinedAt: types.NowTimestamp(),
|
||||
Status: types.GroupMemberActive,
|
||||
LoadFactor: 0.0,
|
||||
}
|
||||
group.Members = append(group.Members, member)
|
||||
g.memberships[payload.GroupID] = "worker"
|
||||
|
||||
log.Printf("[Group] Agent %s joined group %s", g.agentEndpoint.AgentID, payload.GroupID)
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"group_id": payload.GroupID,
|
||||
"role": "worker",
|
||||
"member_id": member.AgentID,
|
||||
})
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleGroupLeave(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload struct {
|
||||
GroupID string `json:"group_id"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid leave payload", err.Error()))
|
||||
}
|
||||
|
||||
group, ok := g.groups[payload.GroupID]
|
||||
if !ok {
|
||||
return g.newErrorResponse(msg, types.ErrGroupNotFoundError)
|
||||
}
|
||||
|
||||
// Check if member
|
||||
found := false
|
||||
for i, m := range group.Members {
|
||||
if m.AgentID == g.agentEndpoint.AgentID {
|
||||
group.Members = append(group.Members[:i], group.Members[i+1:]...)
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
return g.newErrorResponse(msg, types.ErrNotGroupMemberError)
|
||||
}
|
||||
|
||||
// Check if can self-leave
|
||||
if !group.Config.AllowSelfLeave && g.getMemberRole(payload.GroupID, g.agentEndpoint.AgentID) == "coordinator" {
|
||||
return g.newErrorResponse(msg, types.ErrPermissionDeniedError)
|
||||
}
|
||||
|
||||
delete(g.memberships, payload.GroupID)
|
||||
|
||||
log.Printf("[Group] Agent %s left group %s", g.agentEndpoint.AgentID, payload.GroupID)
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"group_id": payload.GroupID,
|
||||
"status": "left",
|
||||
})
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleGroupInvite(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.GroupInvitePayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid invite payload", err.Error()))
|
||||
}
|
||||
|
||||
_, ok := g.groups[payload.GroupID]
|
||||
if !ok {
|
||||
return g.newErrorResponse(msg, types.ErrGroupNotFoundError)
|
||||
}
|
||||
|
||||
// Check if inviter is coordinator or has invite permission
|
||||
inviterRole := g.getMemberRole(payload.GroupID, msg.Sender.AgentID)
|
||||
if inviterRole != "coordinator" && inviterRole != "" {
|
||||
return g.newErrorResponse(msg, types.ErrPermissionDeniedError)
|
||||
}
|
||||
|
||||
log.Printf("[Group] Invitation sent to %s for group %s", payload.Invitee.AgentID, payload.GroupID)
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"group_id": payload.GroupID,
|
||||
"invitee": payload.Invitee.AgentID,
|
||||
"status": "invited",
|
||||
})
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleGroupAcceptInvite(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload struct {
|
||||
GroupID string `json:"group_id"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid accept payload", err.Error()))
|
||||
}
|
||||
|
||||
// Join the group
|
||||
return g.handleGroupJoin(ctx, msg)
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleGroupRejectInvite(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload struct {
|
||||
GroupID string `json:"group_id"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid reject payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[Group] Invitation rejected for group %s: %s", payload.GroupID, payload.Reason)
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"group_id": payload.GroupID,
|
||||
"status": "rejected",
|
||||
"reason": payload.Reason,
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Group Communication Handlers
|
||||
// =============================================================================
|
||||
|
||||
func (g *GroupProtocol) handleGroupBroadcast(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
// Broadcast is handled by the transport layer
|
||||
// This just validates the message
|
||||
log.Printf("[Group] Broadcast received in group %s from %s", msg.GroupID, msg.Sender.AgentID)
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"status": "broadcast_received",
|
||||
})
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleGroupMulticast(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
_, ok := g.groups[msg.GroupID]
|
||||
if !ok {
|
||||
return g.newErrorResponse(msg, types.ErrGroupNotFoundError)
|
||||
}
|
||||
|
||||
// Validate targets exist
|
||||
targets := msg.TargetIDs
|
||||
for _, t := range targets {
|
||||
if !g.isMember(msg.GroupID, t) {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMemberNotFound, fmt.Sprintf("Member not found: %s", t), nil))
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("[Group] Multicast in group %s to %d targets", msg.GroupID, len(targets))
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"status": "multicast_scheduled",
|
||||
"target_count": len(targets),
|
||||
})
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleGroupDirect(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
if len(msg.TargetIDs) != 1 {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrInvalidParams, "Direct message requires exactly one target", nil))
|
||||
}
|
||||
|
||||
target := msg.TargetIDs[0]
|
||||
if !g.isMember(msg.GroupID, target) {
|
||||
return g.newErrorResponse(msg, types.ErrMemberNotFoundError)
|
||||
}
|
||||
|
||||
log.Printf("[Group] Direct message in group %s to %s", msg.GroupID, target)
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"status": "direct_scheduled",
|
||||
"target": target,
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Task Collaboration Handlers
|
||||
// =============================================================================
|
||||
|
||||
func (g *GroupProtocol) handleGroupTaskSplit(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.GroupTaskSplitPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid task split payload", err.Error()))
|
||||
}
|
||||
|
||||
_, ok := g.groups[msg.GroupID]
|
||||
if !ok {
|
||||
return g.newErrorResponse(msg, types.ErrGroupNotFoundError)
|
||||
}
|
||||
|
||||
// Check if sender is coordinator
|
||||
if g.getMemberRole(msg.GroupID, msg.Sender.AgentID) != "coordinator" {
|
||||
return g.newErrorResponse(msg, types.ErrPermissionDeniedError)
|
||||
}
|
||||
|
||||
// Validate task split
|
||||
if g.taskHandler != nil {
|
||||
subtasks, valid := g.taskHandler.ValidateTaskSplit(payload.OriginalTask.Type, payload.OriginalTask.Requirements)
|
||||
if !valid {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrInvalidParams, "Task cannot be split", nil))
|
||||
}
|
||||
payload.Subtasks = subtasks
|
||||
}
|
||||
|
||||
// Check subtask count
|
||||
if len(payload.Subtasks) > g.config.MaxSubtasks {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrInvalidParams, fmt.Sprintf("Too many subtasks: %d", len(payload.Subtasks)), nil))
|
||||
}
|
||||
|
||||
// Assign subtasks to members
|
||||
for i := range payload.Subtasks {
|
||||
assignee := payload.Subtasks[i].AssignedTo
|
||||
if !g.isMember(msg.GroupID, assignee) {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMemberNotFound, fmt.Sprintf("Assignee not found: %s", assignee), nil))
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("[Group] Task split in group %s: %d subtasks", msg.GroupID, len(payload.Subtasks))
|
||||
|
||||
// Execute subtasks asynchronously
|
||||
go g.executeSubtasks(context.Background(), msg.GroupID, payload.OriginalTask.ID, payload.Subtasks, payload.MergeStrategy)
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"status": "task_split_initiated",
|
||||
"original_task_id": payload.OriginalTask.ID,
|
||||
"subtask_count": len(payload.Subtasks),
|
||||
})
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) executeSubtasks(ctx context.Context, groupID, originalTaskID string, subtasks []types.Subtask, strategy types.MergeStrategy) {
|
||||
if g.taskHandler == nil {
|
||||
log.Printf("[Group] No task handler configured, skipping subtask execution")
|
||||
return
|
||||
}
|
||||
|
||||
results := make([]types.SubtaskResult, 0, len(subtasks))
|
||||
|
||||
for _, st := range subtasks {
|
||||
result, err := g.taskHandler.ExecuteSubtask(ctx, st.ID, map[string]interface{}{
|
||||
"description": st.Description,
|
||||
"dependencies": st.Dependencies,
|
||||
})
|
||||
|
||||
subtaskResult := types.SubtaskResult{
|
||||
SubtaskID: st.ID,
|
||||
AssignedTo: st.AssignedTo,
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
subtaskResult.Status = "failed"
|
||||
subtaskResult.Error = err.Error()
|
||||
} else {
|
||||
subtaskResult.Status = "success"
|
||||
subtaskResult.Result = result
|
||||
now := types.NowTimestamp()
|
||||
subtaskResult.CompletedAt = &now
|
||||
}
|
||||
|
||||
results = append(results, subtaskResult)
|
||||
}
|
||||
|
||||
// Merge results
|
||||
_, err := g.taskHandler.MergeResults(results, strategy)
|
||||
if err != nil {
|
||||
log.Printf("[Group] Failed to merge results: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("[Group] All subtasks completed, merged result ready")
|
||||
// In a real implementation, this would send a GROUP_TASK_MERGE message
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleGroupTaskAssign(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload struct {
|
||||
SubtaskID string `json:"subtask_id"`
|
||||
AssignTo string `json:"assign_to"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid task assign payload", err.Error()))
|
||||
}
|
||||
|
||||
if !g.isMember(msg.GroupID, payload.AssignTo) {
|
||||
return g.newErrorResponse(msg, types.ErrMemberNotFoundError)
|
||||
}
|
||||
|
||||
log.Printf("[Group] Subtask %s assigned to %s in group %s", payload.SubtaskID, payload.AssignTo, msg.GroupID)
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"status": "assigned",
|
||||
"subtask_id": payload.SubtaskID,
|
||||
"assignee": payload.AssignTo,
|
||||
})
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleGroupTaskMerge(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.GroupTaskMergePayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid task merge payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[Group] Task merge for %s: %d results, consensus: %v",
|
||||
payload.OriginalTaskID, len(payload.SubtaskResults), payload.ConsensusAchieved)
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"status": "merged",
|
||||
"original_task_id": payload.OriginalTaskID,
|
||||
"result_ready": true,
|
||||
})
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleGroupTaskProgress(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload struct {
|
||||
SubtaskID string `json:"subtask_id"`
|
||||
Progress int `json:"progress"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid progress payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[Group] Progress update: subtask %s - %d%% (%s)", payload.SubtaskID, payload.Progress, payload.Message)
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"status": "progress_recorded",
|
||||
"subtask_id": payload.SubtaskID,
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Consensus Handlers
|
||||
// =============================================================================
|
||||
|
||||
func (g *GroupProtocol) handleGroupVote(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.GroupVotePayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid vote payload", err.Error()))
|
||||
}
|
||||
|
||||
// Initialize vote
|
||||
payload.Status = "open"
|
||||
payload.Votes = []types.GroupVoteOption{}
|
||||
|
||||
_, ok := g.groups[msg.GroupID]
|
||||
if !ok {
|
||||
return g.newErrorResponse(msg, types.ErrGroupNotFoundError)
|
||||
}
|
||||
|
||||
// Check if sender is allowed to initiate vote
|
||||
senderRole := g.getMemberRole(msg.GroupID, msg.Sender.AgentID)
|
||||
if senderRole != "coordinator" && senderRole != "reviewer" {
|
||||
return g.newErrorResponse(msg, types.ErrPermissionDeniedError)
|
||||
}
|
||||
|
||||
log.Printf("[Group] Vote initiated in group %s: %s (threshold: %.0f%%)",
|
||||
msg.GroupID, payload.Question, payload.Threshold*100)
|
||||
|
||||
// In a real implementation, this would set up a vote session and notify voters
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"status": "vote_initiated",
|
||||
"vote_id": payload.VoteID,
|
||||
"voters": len(payload.Voters),
|
||||
})
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleGroupVoteSubmit(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload struct {
|
||||
VoteID string `json:"vote_id"`
|
||||
Option string `json:"option"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid vote submit payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[Group] Vote submitted: %s by %s (option: %s)", payload.VoteID, msg.Sender.AgentID, payload.Option)
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"status": "vote_recorded",
|
||||
"vote_id": payload.VoteID,
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Human-in-the-Loop Handlers
|
||||
// =============================================================================
|
||||
|
||||
func (g *GroupProtocol) handleGroupConsensusEscalate(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.GroupConsensusEscalatePayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid consensus escalate payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[Group] Consensus escalation in group %s (level: %d): %s",
|
||||
msg.GroupID, payload.EscalationLevel, payload.EscalateReason.Message)
|
||||
|
||||
// Store escalation and notify human decision makers
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"status": "escalation_recorded",
|
||||
"escalation_id": payload.EscalationID,
|
||||
"human_notified": true,
|
||||
})
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleGroupSubtaskEscalate(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.GroupSubtaskEscalatePayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid subtask escalate payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[Group] Subtask escalation: %s in task %s (level: %d)",
|
||||
payload.Subtask.ID, payload.OriginalTask.ID, payload.EscalationLevel)
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"status": "escalation_recorded",
|
||||
"subtask_id": payload.Subtask.ID,
|
||||
"human_notified": true,
|
||||
})
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleGroupHumanDecision(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.HumanDecisionPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid human decision payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[Group] Human decision for task %s: %s (by %s)",
|
||||
payload.TaskID, payload.Decision.Action, payload.DecidedBy.UserName)
|
||||
|
||||
// Process the decision and resume task execution
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"status": "decision_recorded",
|
||||
"task_id": payload.TaskID,
|
||||
"action": payload.Decision.Action,
|
||||
})
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) handleInterGroupEscalate(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload struct {
|
||||
EscalationID string `json:"escalation_id"`
|
||||
EscalationType string `json:"escalation_type"`
|
||||
// ... other fields
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return g.newErrorResponse(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid inter-group escalate payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[Group] Inter-group escalation: %s (type: %s)", payload.EscalationID, payload.EscalationType)
|
||||
|
||||
return g.newSuccessResponse(msg, map[string]interface{}{
|
||||
"status": "escalation_recorded",
|
||||
"escalation_id": payload.EscalationID,
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Helper Methods
|
||||
// =============================================================================
|
||||
|
||||
func (g *GroupProtocol) validateMessage(msg *types.UnifiedSynapseMessage) error {
|
||||
if msg.GroupID == "" {
|
||||
return types.NewSynapseError(types.ErrMessageFormatInvalid, "Missing group_id", nil)
|
||||
}
|
||||
if msg.Sender.AgentID == "" {
|
||||
return types.NewSynapseError(types.ErrMessageFormatInvalid, "Missing sender agent_id", nil)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) getMemberRole(groupID, agentID string) string {
|
||||
group, ok := g.groups[groupID]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
for _, m := range group.Members {
|
||||
if m.AgentID == agentID {
|
||||
return m.Role
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) isMember(groupID, agentID string) bool {
|
||||
return g.getMemberRole(groupID, agentID) != ""
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) newSuccessResponse(msg *types.UnifiedSynapseMessage, data map[string]interface{}) (*types.UnifiedSynapseMessage, error) {
|
||||
resp := &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.P2PAck),
|
||||
Sender: g.agentEndpoint,
|
||||
CorrelationID: msg.CorrelationID,
|
||||
ReplyTo: msg.ID,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (g *GroupProtocol) newErrorResponse(msg *types.UnifiedSynapseMessage, err *types.SynapseError) (*types.UnifiedSynapseMessage, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// GetGroups returns all groups the agent is a member of
|
||||
func (g *GroupProtocol) GetGroups() []*types.AgentGroup {
|
||||
g.mu.RLock()
|
||||
defer g.mu.RUnlock()
|
||||
|
||||
result := make([]*types.AgentGroup, 0, len(g.groups))
|
||||
for _, group := range g.groups {
|
||||
if g.isMember(group.ID, g.agentEndpoint.AgentID) {
|
||||
result = append(result, group)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// GetGroup returns a specific group
|
||||
func (g *GroupProtocol) GetGroup(groupID string) (*types.AgentGroup, bool) {
|
||||
g.mu.RLock()
|
||||
defer g.mu.RUnlock()
|
||||
group, ok := g.groups[groupID]
|
||||
return group, ok
|
||||
}
|
||||
595
internal/agent/p2p/protocol.go
Normal file
595
internal/agent/p2p/protocol.go
Normal file
@@ -0,0 +1,595 @@
|
||||
package p2p
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// P2P Protocol Handler
|
||||
// =============================================================================
|
||||
|
||||
// TaskHandler is the interface for handling task execution
|
||||
type TaskHandler interface {
|
||||
// ExecuteTask executes a task and returns the result
|
||||
ExecuteTask(ctx context.Context, taskType string, payload map[string]interface{}) (any, error)
|
||||
|
||||
// ValidateTask validates if the task can be executed
|
||||
ValidateTask(taskType string, payload map[string]interface{}) ([]types.MissingField, bool)
|
||||
|
||||
// GetCapabilities returns the agent's capabilities
|
||||
GetCapabilities() []string
|
||||
}
|
||||
|
||||
// MessageHandler is the interface for handling incoming messages
|
||||
type MessageHandler interface {
|
||||
// HandleMessage handles an incoming P2P message
|
||||
HandleMessage(msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error)
|
||||
}
|
||||
|
||||
// CallbackSender is the interface for sending callbacks to remote agents
|
||||
type CallbackSender interface {
|
||||
// SendCallback sends a message to a remote agent
|
||||
SendCallback(ctx context.Context, endpoint string, msg *types.UnifiedSynapseMessage) error
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// P2PProtocol represents the P2P protocol handler
|
||||
// =============================================================================
|
||||
|
||||
// P2PProtocol handles point-to-point Synapse communication
|
||||
type P2PProtocol struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
// Agent identity
|
||||
agentEndpoint types.AgentEndpoint
|
||||
|
||||
// Task state
|
||||
tasks map[string]*types.P2PTaskStatus
|
||||
|
||||
// Handlers
|
||||
taskHandler TaskHandler
|
||||
callbackSender CallbackSender
|
||||
|
||||
// Configuration
|
||||
config *P2PConfig
|
||||
}
|
||||
|
||||
// P2PConfig holds P2P protocol configuration
|
||||
type P2PConfig struct {
|
||||
MaxRetries int // Max callback retries
|
||||
RetryBaseDelay time.Duration // Base delay for retries
|
||||
TaskTimeout time.Duration // Task execution timeout
|
||||
HeartbeatInterval time.Duration // Heartbeat interval
|
||||
}
|
||||
|
||||
// DefaultP2PConfig returns default P2P configuration
|
||||
func DefaultP2PConfig() *P2PConfig {
|
||||
return &P2PConfig{
|
||||
MaxRetries: 5,
|
||||
RetryBaseDelay: 2 * time.Second,
|
||||
TaskTimeout: 5 * time.Minute,
|
||||
HeartbeatInterval: 30 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// P2PTask represents an active task
|
||||
// =============================================================================
|
||||
|
||||
type P2PTask struct {
|
||||
ID string
|
||||
Type string
|
||||
Priority types.Priority
|
||||
Status types.P2PTaskStatus
|
||||
Payload map[string]interface{}
|
||||
Sender types.AgentEndpoint
|
||||
Receiver types.AgentEndpoint
|
||||
CorrelationID string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
CompletedAt *time.Time
|
||||
Result any
|
||||
Error *types.SynapseError
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// NewP2PProtocol creates a new P2P protocol handler
|
||||
// =============================================================================
|
||||
|
||||
func NewP2PProtocol(agentEndpoint types.AgentEndpoint, config *P2PConfig) *P2PProtocol {
|
||||
if config == nil {
|
||||
config = DefaultP2PConfig()
|
||||
}
|
||||
return &P2PProtocol{
|
||||
agentEndpoint: agentEndpoint,
|
||||
tasks: make(map[string]*types.P2PTaskStatus),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// SetTaskHandler sets the task handler
|
||||
func (p *P2PProtocol) SetTaskHandler(h TaskHandler) {
|
||||
p.taskHandler = h
|
||||
}
|
||||
|
||||
// SetCallbackSender sets the callback sender
|
||||
func (p *P2PProtocol) SetCallbackSender(s CallbackSender) {
|
||||
p.callbackSender = s
|
||||
}
|
||||
|
||||
// AgentEndpoint returns the agent's endpoint
|
||||
func (p *P2PProtocol) AgentEndpoint() types.AgentEndpoint {
|
||||
return p.agentEndpoint
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// HandleMessage processes an incoming P2P message
|
||||
// =============================================================================
|
||||
|
||||
func (p *P2PProtocol) HandleMessage(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
// Validate message
|
||||
if err := p.validateMessage(msg); err != nil {
|
||||
a2aErr, ok := err.(*types.SynapseError)
|
||||
if !ok {
|
||||
a2aErr = types.NewSynapseError(types.ErrMessageFormatInvalid, err.Error(), nil)
|
||||
}
|
||||
return p.newNACK(msg, a2aErr)
|
||||
}
|
||||
|
||||
// Route based on message type
|
||||
switch types.P2PMessageType(msg.Type) {
|
||||
case types.P2PTaskRequest:
|
||||
return p.handleTaskRequest(ctx, msg)
|
||||
case types.P2PTaskConfirm:
|
||||
return p.handleTaskConfirm(ctx, msg)
|
||||
case types.P2PTaskReject:
|
||||
return p.handleTaskReject(ctx, msg)
|
||||
case types.P2PTaskNeedInfo:
|
||||
return p.handleTaskNeedInfo(ctx, msg)
|
||||
case types.P2PTaskInfoProvided:
|
||||
return p.handleTaskInfoProvided(ctx, msg)
|
||||
case types.P2PTaskStatusUpdate:
|
||||
return p.handleTaskStatusUpdate(ctx, msg)
|
||||
case types.P2PTaskComplete:
|
||||
return p.handleTaskComplete(ctx, msg)
|
||||
case types.P2PTaskFailed:
|
||||
return p.handleTaskFailed(ctx, msg)
|
||||
case types.P2PTaskCancel:
|
||||
return p.handleTaskCancel(ctx, msg)
|
||||
case types.P2PTaskAck:
|
||||
return p.handleTaskAck(ctx, msg)
|
||||
case types.P2PTaskNeedHuman:
|
||||
return p.handleTaskNeedHuman(ctx, msg)
|
||||
case types.P2PHumanDecision:
|
||||
return p.handleHumanDecision(ctx, msg)
|
||||
case types.P2PAck:
|
||||
return p.handleAck(ctx, msg)
|
||||
case types.P2PNack:
|
||||
return p.handleNack(ctx, msg)
|
||||
case types.P2PHeartbeat:
|
||||
return p.handleHeartbeat(ctx, msg)
|
||||
default:
|
||||
return p.newNACK(msg, types.NewSynapseError(
|
||||
types.ErrMessageFormatInvalid,
|
||||
fmt.Sprintf("Unknown message type: %s", msg.Type),
|
||||
nil,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Message Handlers
|
||||
// =============================================================================
|
||||
|
||||
// handleTaskRequest handles incoming task requests
|
||||
func (p *P2PProtocol) handleTaskRequest(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.TaskRequestPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return p.newNACK(msg, types.NewSynapseError(
|
||||
types.ErrMessageFormatInvalid,
|
||||
"Invalid task request payload",
|
||||
err.Error(),
|
||||
))
|
||||
}
|
||||
|
||||
taskID := payload.Task.ID
|
||||
log.Printf("[P2P] Task request received: %s (type: %s)", taskID, payload.Task.Type)
|
||||
|
||||
// Check if we have a task handler
|
||||
if p.taskHandler == nil {
|
||||
return p.newReject(msg, taskID, "agent_not_ready", "Task handler not configured", nil)
|
||||
}
|
||||
|
||||
// Validate the task
|
||||
missingFields, canHandle := p.taskHandler.ValidateTask(payload.Task.Type, payload.Task.Payload)
|
||||
if !canHandle {
|
||||
if len(missingFields) > 0 {
|
||||
// Need more info
|
||||
return p.newNeedInfo(msg, taskID, missingFields)
|
||||
}
|
||||
return p.newReject(msg, taskID, "capability_lacking", "Agent cannot handle this task type", nil)
|
||||
}
|
||||
|
||||
// Create task context
|
||||
taskCtx, cancel := context.WithTimeout(ctx, p.config.TaskTimeout)
|
||||
defer cancel()
|
||||
|
||||
// Execute task asynchronously
|
||||
go p.executeTask(taskCtx, msg, taskID, payload.Task.Type, payload.Task.Payload)
|
||||
|
||||
// Return immediate confirmation
|
||||
return p.newAck(msg, taskID, "task_accepted")
|
||||
}
|
||||
|
||||
// executeTask executes a task and handles callbacks
|
||||
func (p *P2PProtocol) executeTask(ctx context.Context, origMsg *types.UnifiedSynapseMessage, taskID, taskType string, payload map[string]interface{}) {
|
||||
// Send initial status update
|
||||
p.sendStatusUpdate(ctx, taskID, types.P2PStatusExecuting, 0, "Task started")
|
||||
|
||||
// Execute the task
|
||||
result, err := p.taskHandler.ExecuteTask(ctx, taskType, payload)
|
||||
|
||||
if err != nil {
|
||||
// Task failed
|
||||
p.sendTaskFailed(ctx, taskID, "execution_failed", err.Error(), true, nil)
|
||||
return
|
||||
}
|
||||
|
||||
// Task completed
|
||||
p.sendTaskComplete(ctx, taskID, result)
|
||||
}
|
||||
|
||||
// sendStatusUpdate sends a status update to the sender
|
||||
func (p *P2PProtocol) sendStatusUpdate(ctx context.Context, taskID string, status types.P2PTaskStatus, progress int, message string) {
|
||||
if p.callbackSender == nil {
|
||||
return
|
||||
}
|
||||
|
||||
payload := types.TaskStatusUpdatePayload{
|
||||
TaskID: taskID,
|
||||
Status: string(status),
|
||||
Progress: progress,
|
||||
Message: message,
|
||||
}
|
||||
|
||||
payloadBytes, _ := json.Marshal(payload)
|
||||
|
||||
response := &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.P2PTaskStatusUpdate),
|
||||
Sender: p.agentEndpoint,
|
||||
Payload: payloadBytes,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}
|
||||
|
||||
if err := p.callbackSender.SendCallback(ctx, "", response); err != nil {
|
||||
log.Printf("[P2P] Failed to send status update: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// sendTaskComplete sends task completion notification
|
||||
func (p *P2PProtocol) sendTaskComplete(ctx context.Context, taskID string, result any) {
|
||||
if p.callbackSender == nil {
|
||||
return
|
||||
}
|
||||
|
||||
payload := types.TaskCompletePayload{}
|
||||
payload.TaskID = taskID
|
||||
payload.Result.OutputType = "task_result"
|
||||
payload.Result.Output = result
|
||||
|
||||
payloadBytes, _ := json.Marshal(payload)
|
||||
|
||||
response := &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.P2PTaskComplete),
|
||||
Sender: p.agentEndpoint,
|
||||
Payload: payloadBytes,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}
|
||||
|
||||
if err := p.callbackSender.SendCallback(ctx, "", response); err != nil {
|
||||
log.Printf("[P2P] Failed to send task complete: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// sendTaskFailed sends task failure notification
|
||||
func (p *P2PProtocol) sendTaskFailed(ctx context.Context, taskID, errorCode, errorMessage string, recoverable bool, partialResult any) {
|
||||
if p.callbackSender == nil {
|
||||
return
|
||||
}
|
||||
|
||||
payload := types.TaskFailedPayload{}
|
||||
payload.TaskID = taskID
|
||||
payload.Error.Code = errorCode
|
||||
payload.Error.Message = errorMessage
|
||||
payload.Error.Recoverable = recoverable
|
||||
payload.PartialResult = partialResult
|
||||
|
||||
payloadBytes, _ := json.Marshal(payload)
|
||||
|
||||
response := &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.P2PTaskFailed),
|
||||
Sender: p.agentEndpoint,
|
||||
Payload: payloadBytes,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}
|
||||
|
||||
if err := p.callbackSender.SendCallback(ctx, "", response); err != nil {
|
||||
log.Printf("[P2P] Failed to send task failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// handleTaskConfirm handles task confirmation from receiver
|
||||
func (p *P2PProtocol) handleTaskConfirm(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.TaskConfirmPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid confirm payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[P2P] Task confirmed: %s (estimated: %ds)", payload.TaskID, payload.EstimatedDuration)
|
||||
return p.newAck(msg, payload.TaskID, "confirmed")
|
||||
}
|
||||
|
||||
// handleTaskReject handles task rejection from receiver
|
||||
func (p *P2PProtocol) handleTaskReject(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.TaskRejectPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid reject payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[P2P] Task rejected: %s (%s: %s)", payload.TaskID, payload.Reason.Code, payload.Reason.Message)
|
||||
return p.newAck(msg, payload.TaskID, "rejected")
|
||||
}
|
||||
|
||||
// handleTaskNeedInfo handles information request from receiver
|
||||
func (p *P2PProtocol) handleTaskNeedInfo(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.TaskNeedInfoPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid need info payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[P2P] Information requested: %s (missing %d fields)", payload.TaskID, len(payload.MissingFields))
|
||||
|
||||
// This would typically be handled by the application logic
|
||||
// For now, just acknowledge
|
||||
return p.newAck(msg, payload.TaskID, "info_request_received")
|
||||
}
|
||||
|
||||
// handleTaskInfoProvided handles information provided by sender
|
||||
func (p *P2PProtocol) handleTaskInfoProvided(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.TaskInfoProvidedPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid info provided payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[P2P] Information provided: %s (%d fields)", payload.TaskID, len(payload.ProvidedInfo))
|
||||
return p.newAck(msg, payload.TaskID, "info_received")
|
||||
}
|
||||
|
||||
// handleTaskStatusUpdate handles status updates from receiver
|
||||
func (p *P2PProtocol) handleTaskStatusUpdate(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.TaskStatusUpdatePayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid status update payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[P2P] Status update: %s - %s (progress: %d%%)", payload.TaskID, payload.Status, payload.Progress)
|
||||
return p.newAck(msg, payload.TaskID, "status_received")
|
||||
}
|
||||
|
||||
// handleTaskComplete handles task completion notification
|
||||
func (p *P2PProtocol) handleTaskComplete(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.TaskCompletePayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid complete payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[P2P] Task completed: %s", payload.TaskID)
|
||||
return p.newAck(msg, payload.TaskID, "completed")
|
||||
}
|
||||
|
||||
// handleTaskFailed handles task failure notification
|
||||
func (p *P2PProtocol) handleTaskFailed(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.TaskFailedPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid failed payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[P2P] Task failed: %s (%s: %s)", payload.TaskID, payload.Error.Code, payload.Error.Message)
|
||||
return p.newAck(msg, payload.TaskID, "failure_noted")
|
||||
}
|
||||
|
||||
// handleTaskCancel handles task cancellation
|
||||
func (p *P2PProtocol) handleTaskCancel(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.TaskCancelPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid cancel payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[P2P] Task cancelled: %s (by %s)", payload.TaskID, payload.CancelledBy)
|
||||
return p.newAck(msg, payload.TaskID, "cancelled")
|
||||
}
|
||||
|
||||
// handleTaskAck handles task-level acknowledgment
|
||||
func (p *P2PProtocol) handleTaskAck(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
log.Printf("[P2P] Task ACK received for message: %s", msg.ReplyTo)
|
||||
return nil, nil // No response needed for ACK
|
||||
}
|
||||
|
||||
// handleTaskNeedHuman handles human intervention request
|
||||
func (p *P2PProtocol) handleTaskNeedHuman(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.TaskNeedHumanPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid need human payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[P2P] Human intervention needed: %s (level: %d)", payload.TaskID, payload.EscalationLevel)
|
||||
|
||||
// Store the HiL request and wait for human decision
|
||||
// This would typically be handled by a HiL manager
|
||||
|
||||
return p.newAck(msg, payload.TaskID, "human_intervention_requested")
|
||||
}
|
||||
|
||||
// handleHumanDecision handles human decision response
|
||||
func (p *P2PProtocol) handleHumanDecision(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
var payload types.HumanDecisionPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return p.newNACK(msg, types.NewSynapseError(types.ErrMessageFormatInvalid, "Invalid human decision payload", err.Error()))
|
||||
}
|
||||
|
||||
log.Printf("[P2P] Human decision: %s (action: %s, by %s)", payload.TaskID, payload.Decision.Action, payload.DecidedBy.UserName)
|
||||
|
||||
// Process the human decision
|
||||
// This would resume the task execution with the decision
|
||||
|
||||
return p.newAck(msg, payload.TaskID, "decision_received")
|
||||
}
|
||||
|
||||
// handleAck handles generic ACK
|
||||
func (p *P2PProtocol) handleAck(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
log.Printf("[P2P] ACK received for: %s", msg.ReplyTo)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// handleNack handles generic NACK
|
||||
func (p *P2PProtocol) handleNack(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
log.Printf("[P2P] NACK received for: %s", msg.ReplyTo)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// handleHeartbeat handles heartbeat
|
||||
func (p *P2PProtocol) handleHeartbeat(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
return p.newAck(msg, "", "alive")
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Response Builders
|
||||
// =============================================================================
|
||||
|
||||
// newAck creates an ACK response
|
||||
func (p *P2PProtocol) newAck(msg *types.UnifiedSynapseMessage, taskID, note string) (*types.UnifiedSynapseMessage, error) {
|
||||
return &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.P2PAck),
|
||||
Sender: p.agentEndpoint,
|
||||
Receiver: &msg.Sender,
|
||||
CorrelationID: msg.CorrelationID,
|
||||
ReplyTo: msg.ID,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// newNACK creates a NACK response
|
||||
func (p *P2PProtocol) newNACK(msg *types.UnifiedSynapseMessage, err *types.SynapseError) (*types.UnifiedSynapseMessage, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// newReject creates a task rejection response
|
||||
func (p *P2PProtocol) newReject(msg *types.UnifiedSynapseMessage, taskID, reasonCode, reasonMessage string, alternatives *struct {
|
||||
SuggestedAgentID string `json:"suggested_agent_id,omitempty"`
|
||||
RetryAfter int `json:"retry_after,omitempty"`
|
||||
PartialSupport bool `json:"partial_support,omitempty"`
|
||||
}) (*types.UnifiedSynapseMessage, error) {
|
||||
payload := types.TaskRejectPayload{}
|
||||
payload.TaskID = taskID
|
||||
payload.Reason.Code = reasonCode
|
||||
payload.Reason.Message = reasonMessage
|
||||
if alternatives != nil {
|
||||
payload.Alternatives = alternatives
|
||||
}
|
||||
|
||||
payloadBytes, _ := json.Marshal(payload)
|
||||
|
||||
return &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.P2PTaskReject),
|
||||
Sender: p.agentEndpoint,
|
||||
Receiver: &msg.Sender,
|
||||
CorrelationID: msg.CorrelationID,
|
||||
ReplyTo: msg.ID,
|
||||
Payload: payloadBytes,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// newNeedInfo creates a need info response
|
||||
func (p *P2PProtocol) newNeedInfo(msg *types.UnifiedSynapseMessage, taskID string, missingFields []types.MissingField) (*types.UnifiedSynapseMessage, error) {
|
||||
payload := types.TaskNeedInfoPayload{}
|
||||
payload.TaskID = taskID
|
||||
payload.MissingFields = missingFields
|
||||
|
||||
payloadBytes, _ := json.Marshal(payload)
|
||||
|
||||
return &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.P2PTaskNeedInfo),
|
||||
Sender: p.agentEndpoint,
|
||||
Receiver: &msg.Sender,
|
||||
CorrelationID: msg.CorrelationID,
|
||||
ReplyTo: msg.ID,
|
||||
Payload: payloadBytes,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Validation
|
||||
// =============================================================================
|
||||
|
||||
func (p *P2PProtocol) validateMessage(msg *types.UnifiedSynapseMessage) error {
|
||||
if msg.ID == "" {
|
||||
return types.ErrMessageFormatInvalidError
|
||||
}
|
||||
if msg.Sender.AgentID == "" {
|
||||
return types.NewSynapseError(types.ErrMessageFormatInvalid, "Missing sender agent_id", nil)
|
||||
}
|
||||
if msg.Sender.Endpoint == "" {
|
||||
return types.NewSynapseError(types.ErrMessageFormatInvalid, "Missing sender endpoint", nil)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Task Management
|
||||
// =============================================================================
|
||||
|
||||
// GetTaskStatus returns the status of a task
|
||||
func (p *P2PProtocol) GetTaskStatus(taskID string) (types.P2PTaskStatus, bool) {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
status, ok := p.tasks[taskID]
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
return *status, true
|
||||
}
|
||||
|
||||
// ListTasks returns all tasks
|
||||
func (p *P2PProtocol) ListTasks() map[string]types.P2PTaskStatus {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
result := make(map[string]types.P2PTaskStatus)
|
||||
for k, v := range p.tasks {
|
||||
result[k] = *v
|
||||
}
|
||||
return result
|
||||
}
|
||||
494
internal/agent/p2p/protocol_test.go
Normal file
494
internal/agent/p2p/protocol_test.go
Normal file
@@ -0,0 +1,494 @@
|
||||
package p2p
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/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")
|
||||
}
|
||||
}
|
||||
621
internal/api/externalapi/handler.go
Normal file
621
internal/api/externalapi/handler.go
Normal file
@@ -0,0 +1,621 @@
|
||||
package externalapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// External API Layer - 非Agent调用者API
|
||||
// =============================================================================
|
||||
//
|
||||
// 这一层为非Agent调用者(如普通服务、前端、第三方应用)提供了更简单的RESTful API,
|
||||
// 隐藏了Synapse协议的复杂性。
|
||||
//
|
||||
// 与Synapse协议的区别:
|
||||
// - 使用API Key认证,而非HMAC签名
|
||||
// - 简化的请求/响应格式
|
||||
// - 支持回调和轮询两种模式
|
||||
// - 无需注册为Agent即可调用
|
||||
// =============================================================================
|
||||
|
||||
// =============================================================================
|
||||
// API Handler
|
||||
// =============================================================================
|
||||
|
||||
// ExternalAPIHandler 处理外部API请求
|
||||
type ExternalAPIHandler struct {
|
||||
// TaskExecutor 任务执行器
|
||||
TaskExecutor TaskExecutor
|
||||
|
||||
// APIKey API密钥(如果为空则不验证)
|
||||
APIKey string
|
||||
|
||||
// MaxFileSize 最大文件大小
|
||||
MaxFileSize int64
|
||||
}
|
||||
|
||||
// TaskExecutor 任务执行器接口
|
||||
type TaskExecutor interface {
|
||||
// SubmitTask 提交任务
|
||||
SubmitTask(ctx context.Context, taskType string, payload map[string]any, externalTaskID string, priority string, callbackURL string, callbackToken string) (string, string, error)
|
||||
|
||||
// GetTaskStatus 获取任务状态
|
||||
GetTaskStatus(ctx context.Context, taskID string) (*types.TaskInfo, error)
|
||||
|
||||
// ListTasks 列出任务
|
||||
ListTasks(ctx context.Context, status string, limit, offset int) ([]types.TaskInfo, int, error)
|
||||
|
||||
// CancelTask 取消任务
|
||||
CancelTask(ctx context.Context, taskID string) error
|
||||
}
|
||||
|
||||
// NewExternalAPIHandler 创建外部API处理器
|
||||
func NewExternalAPIHandler(executor TaskExecutor, apiKey string) *ExternalAPIHandler {
|
||||
return &ExternalAPIHandler{
|
||||
TaskExecutor: executor,
|
||||
APIKey: apiKey,
|
||||
MaxFileSize: 100 << 20, // 100MB
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterRoutes 注册路由
|
||||
func (h *ExternalAPIHandler) RegisterRoutes(mux *http.ServeMux, prefix string) {
|
||||
// 任务相关
|
||||
mux.HandleFunc(prefix+"/task", h.withAuth(h.handleTaskCreate))
|
||||
mux.HandleFunc(prefix+"/task/", h.withAuth(h.handleTaskDetail))
|
||||
mux.HandleFunc(prefix+"/tasks", h.withAuth(h.handleTaskList))
|
||||
|
||||
// 多部分表单提交
|
||||
mux.HandleFunc(prefix+"/task/multipart", h.withAuth(h.handleTaskMultipart))
|
||||
|
||||
// 能力查询
|
||||
mux.HandleFunc(prefix+"/capabilities", h.withAuth(h.handleCapabilities))
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 认证中间件
|
||||
// =============================================================================
|
||||
|
||||
func (h *ExternalAPIHandler) withAuth(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// 如果没有配置API Key,跳过验证
|
||||
if h.APIKey != "" {
|
||||
key := r.Header.Get("X-API-Key")
|
||||
if key == "" {
|
||||
key = r.URL.Query().Get("api_key")
|
||||
}
|
||||
if key != h.APIKey {
|
||||
h.writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or missing API key")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// CORS
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, X-API-Key")
|
||||
|
||||
if r.Method == "OPTIONS" {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 任务创建
|
||||
// =============================================================================
|
||||
|
||||
// ExternalTaskRequest 外部任务请求
|
||||
type ExternalTaskRequest 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"`
|
||||
}
|
||||
|
||||
func (h *ExternalAPIHandler) handleTaskCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
h.writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "only POST is supported")
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
h.writeError(w, http.StatusBadRequest, "bad_request", "failed to read body")
|
||||
return
|
||||
}
|
||||
|
||||
var req ExternalTaskRequest
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
h.writeError(w, http.StatusBadRequest, "bad_request", "invalid JSON format")
|
||||
return
|
||||
}
|
||||
|
||||
// 验证必填字段
|
||||
if req.TaskType == "" {
|
||||
h.writeError(w, http.StatusBadRequest, "bad_request", "task_type is required")
|
||||
return
|
||||
}
|
||||
if req.Payload == nil {
|
||||
h.writeError(w, http.StatusBadRequest, "bad_request", "payload is required")
|
||||
return
|
||||
}
|
||||
|
||||
// 默认优先级
|
||||
if req.Priority == "" {
|
||||
req.Priority = "normal"
|
||||
}
|
||||
|
||||
// 提交任务
|
||||
taskID, status, err := h.TaskExecutor.SubmitTask(
|
||||
r.Context(),
|
||||
req.TaskType,
|
||||
req.Payload,
|
||||
req.ExternalTaskID,
|
||||
req.Priority,
|
||||
req.CallbackURL,
|
||||
req.CallbackToken,
|
||||
)
|
||||
if err != nil {
|
||||
log.Printf("[ExternalAPI] 任务提交失败: %v", err)
|
||||
h.writeError(w, http.StatusInternalServerError, "task_submission_failed", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("[ExternalAPI] 任务提交成功: type=%s, task_id=%s", req.TaskType, taskID)
|
||||
|
||||
h.writeJSON(w, http.StatusAccepted, map[string]any{
|
||||
"success": true,
|
||||
"task_id": taskID,
|
||||
"status": status,
|
||||
"message": "任务已接收,正在处理中",
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Multipart任务创建(带文件)
|
||||
// =============================================================================
|
||||
|
||||
func (h *ExternalAPIHandler) handleTaskMultipart(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
h.writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "only POST is supported")
|
||||
return
|
||||
}
|
||||
|
||||
// 限制请求大小
|
||||
r.Body = http.MaxBytesReader(w, r.Body, h.MaxFileSize)
|
||||
|
||||
if err := r.ParseMultipartForm(h.MaxFileSize); err != nil {
|
||||
h.writeError(w, http.StatusBadRequest, "bad_request", "failed to parse multipart form: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 获取请求JSON
|
||||
requestStr := r.FormValue("request")
|
||||
if requestStr == "" {
|
||||
h.writeError(w, http.StatusBadRequest, "bad_request", "missing 'request' field")
|
||||
return
|
||||
}
|
||||
|
||||
var req ExternalTaskRequest
|
||||
if err := json.Unmarshal([]byte(requestStr), &req); err != nil {
|
||||
h.writeError(w, http.StatusBadRequest, "bad_request", "invalid request JSON")
|
||||
return
|
||||
}
|
||||
|
||||
// 提取文件
|
||||
files := make(map[string][]byte)
|
||||
if r.MultipartForm != nil {
|
||||
for fieldName, fileHeaders := range r.MultipartForm.File {
|
||||
if fieldName == "request" {
|
||||
continue
|
||||
}
|
||||
for _, fh := range fileHeaders {
|
||||
file, err := fh.Open()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
data, err := io.ReadAll(file)
|
||||
file.Close()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
files[fieldName] = data
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 将文件信息加入payload
|
||||
if len(files) > 0 {
|
||||
if req.Payload == nil {
|
||||
req.Payload = make(map[string]any)
|
||||
}
|
||||
req.Payload["__files"] = files
|
||||
}
|
||||
|
||||
// 提交任务
|
||||
taskID, status, err := h.TaskExecutor.SubmitTask(
|
||||
r.Context(),
|
||||
req.TaskType,
|
||||
req.Payload,
|
||||
req.ExternalTaskID,
|
||||
req.Priority,
|
||||
req.CallbackURL,
|
||||
req.CallbackToken,
|
||||
)
|
||||
if err != nil {
|
||||
h.writeError(w, http.StatusInternalServerError, "task_submission_failed", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
h.writeJSON(w, http.StatusAccepted, map[string]any{
|
||||
"success": true,
|
||||
"task_id": taskID,
|
||||
"status": status,
|
||||
"message": "任务已接收,正在处理中",
|
||||
"files_uploaded": len(files),
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 任务详情/状态
|
||||
// =============================================================================
|
||||
|
||||
func (h *ExternalAPIHandler) handleTaskDetail(w http.ResponseWriter, r *http.Request) {
|
||||
path := strings.TrimPrefix(r.URL.Path, "/api/v1/synapse/task/")
|
||||
parts := strings.SplitN(path, "/", 2)
|
||||
taskID := parts[0]
|
||||
|
||||
if taskID == "" {
|
||||
h.writeError(w, http.StatusNotFound, "not_found", "task_id is required")
|
||||
return
|
||||
}
|
||||
|
||||
// /task/{id}/status
|
||||
if len(parts) == 2 {
|
||||
switch parts[1] {
|
||||
case "status":
|
||||
h.handleTaskStatus(w, r, taskID)
|
||||
return
|
||||
case "cancel":
|
||||
h.handleTaskCancel(w, r, taskID)
|
||||
return
|
||||
default:
|
||||
h.writeError(w, http.StatusNotFound, "not_found", "unknown subpath")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// /task/{id} (GET)
|
||||
if r.Method != http.MethodGet {
|
||||
h.writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "only GET is supported")
|
||||
return
|
||||
}
|
||||
|
||||
task, err := h.TaskExecutor.GetTaskStatus(r.Context(), taskID)
|
||||
if err != nil {
|
||||
h.writeError(w, http.StatusNotFound, "task_not_found", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
h.writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"task": task,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ExternalAPIHandler) handleTaskStatus(w http.ResponseWriter, r *http.Request, taskID string) {
|
||||
if r.Method != http.MethodGet {
|
||||
h.writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "only GET is supported")
|
||||
return
|
||||
}
|
||||
|
||||
task, err := h.TaskExecutor.GetTaskStatus(r.Context(), taskID)
|
||||
if err != nil {
|
||||
h.writeError(w, http.StatusNotFound, "task_not_found", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
h.writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"task_id": task.ID,
|
||||
"status": task.Status,
|
||||
"progress": task.Progress,
|
||||
"message": task.Message,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ExternalAPIHandler) handleTaskCancel(w http.ResponseWriter, r *http.Request, taskID string) {
|
||||
if r.Method != http.MethodPost {
|
||||
h.writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "only POST is supported")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.TaskExecutor.CancelTask(r.Context(), taskID); err != nil {
|
||||
h.writeError(w, http.StatusInternalServerError, "cancel_failed", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
h.writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"task_id": taskID,
|
||||
"status": "cancelled",
|
||||
"message": "任务已取消",
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 任务列表
|
||||
// =============================================================================
|
||||
|
||||
func (h *ExternalAPIHandler) handleTaskList(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
h.writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "only GET is supported")
|
||||
return
|
||||
}
|
||||
|
||||
status := r.URL.Query().Get("status")
|
||||
limitStr := r.URL.Query().Get("limit")
|
||||
offsetStr := r.URL.Query().Get("offset")
|
||||
|
||||
limit := 20
|
||||
offset := 0
|
||||
if limitStr != "" {
|
||||
if n, err := strconv.Atoi(limitStr); err == nil && n > 0 && n <= 100 {
|
||||
limit = n
|
||||
}
|
||||
}
|
||||
if offsetStr != "" {
|
||||
if n, err := strconv.Atoi(offsetStr); err == nil && n >= 0 {
|
||||
offset = n
|
||||
}
|
||||
}
|
||||
|
||||
tasks, total, err := h.TaskExecutor.ListTasks(r.Context(), status, limit, offset)
|
||||
if err != nil {
|
||||
h.writeError(w, http.StatusInternalServerError, "list_failed", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
hasMore := offset+limit < total
|
||||
|
||||
h.writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"tasks": tasks,
|
||||
"total": total,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
"has_more": hasMore,
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 能力查询
|
||||
// =============================================================================
|
||||
|
||||
// CapabilitiesProvider 能力提供者接口
|
||||
type CapabilitiesProvider interface {
|
||||
GetCapabilities(ctx context.Context) (*CapabilitiesInfo, error)
|
||||
}
|
||||
|
||||
// CapabilitiesInfo 能力信息
|
||||
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"`
|
||||
SupportedContentTypes []string `json:"supported_content_types"`
|
||||
SupportedTransportModes []string `json:"supported_transport_modes"`
|
||||
MaxFileSize int64 `json:"max_file_size"`
|
||||
MaxConcurrentTasks int `json:"max_concurrent_tasks"`
|
||||
MaxTaskDuration int `json:"max_task_duration_seconds"`
|
||||
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"`
|
||||
Capabilities []string `json:"capabilities,omitempty"`
|
||||
}
|
||||
|
||||
// CapabilitiesProviderField 能力提供者字段(可选注入)
|
||||
var CapabilitiesProviderField CapabilitiesProvider
|
||||
|
||||
func (h *ExternalAPIHandler) handleCapabilities(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
h.writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "only GET is supported")
|
||||
return
|
||||
}
|
||||
|
||||
// 如果有注入的能力提供者,使用它
|
||||
if CapabilitiesProviderField != nil {
|
||||
caps, err := CapabilitiesProviderField.GetCapabilities(r.Context())
|
||||
if err != nil {
|
||||
h.writeError(w, http.StatusInternalServerError, "capabilities_error", err.Error())
|
||||
return
|
||||
}
|
||||
h.writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"capabilities": caps,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 默认能力信息
|
||||
caps := &CapabilitiesInfo{
|
||||
AgentID: "synapse-agent",
|
||||
AgentName: "Synapse Agent",
|
||||
SystemID: "synapse",
|
||||
ProtocolVersion: "1.0.0",
|
||||
SupportedTaskTypes: []SupportedTaskType{},
|
||||
SupportedContentTypes: []string{"application/json", "text/plain", "application/octet-stream"},
|
||||
SupportedTransportModes: []string{"callback", "polling"},
|
||||
MaxFileSize: h.MaxFileSize,
|
||||
MaxConcurrentTasks: 10,
|
||||
MaxTaskDuration: 300,
|
||||
SupportProgressUpdates: true,
|
||||
SupportStreaming: false,
|
||||
SupportHiL: true,
|
||||
SupportGroups: true,
|
||||
}
|
||||
|
||||
h.writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"capabilities": caps,
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 回调发送器
|
||||
// =============================================================================
|
||||
|
||||
// CallbackSender 发送回调通知
|
||||
type CallbackSender struct {
|
||||
HTTPClient *http.Client
|
||||
}
|
||||
|
||||
// NewCallbackSender 创建回调发送器
|
||||
func NewCallbackSender() *CallbackSender {
|
||||
return &CallbackSender{
|
||||
HTTPClient: &http.Client{Timeout: 10 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
// CallbackPayload 回调负载
|
||||
type CallbackPayload struct {
|
||||
MessageID string `json:"message_id"`
|
||||
MessageType string `json:"message_type"` // task_status, task_complete, task_failed
|
||||
TaskID string `json:"task_id"`
|
||||
Status string `json:"status"`
|
||||
Progress int `json:"progress"`
|
||||
Result map[string]any `json:"result,omitempty"`
|
||||
Error *CallbackError `json:"error,omitempty"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
}
|
||||
|
||||
// CallbackError 回调错误
|
||||
type CallbackError struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// SendCallback 发送回调
|
||||
func (s *CallbackSender) SendCallback(ctx context.Context, callbackURL, callbackToken string, payload *CallbackPayload) error {
|
||||
if callbackURL == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", callbackURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if callbackToken != "" {
|
||||
req.Header.Set("X-Callback-Token", callbackToken)
|
||||
}
|
||||
|
||||
resp, err := s.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 400 {
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("callback returned HTTP %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 辅助函数
|
||||
// =============================================================================
|
||||
|
||||
func (h *ExternalAPIHandler) writeJSON(w http.ResponseWriter, status int, data map[string]any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
func (h *ExternalAPIHandler) writeError(w http.ResponseWriter, status int, code, message string) {
|
||||
h.writeJSON(w, status, map[string]any{
|
||||
"success": false,
|
||||
"error": code,
|
||||
"message": message,
|
||||
})
|
||||
}
|
||||
|
||||
// FileInfo 上传的文件信息
|
||||
type FileInfo struct {
|
||||
Fieldname string
|
||||
Filename string
|
||||
Size int64
|
||||
Data []byte
|
||||
Header multipart.FileHeader
|
||||
}
|
||||
|
||||
// ExtractFiles 从multipart请求中提取文件
|
||||
func ExtractFiles(r *http.Request) ([]FileInfo, error) {
|
||||
if r.MultipartForm == nil {
|
||||
if err := r.ParseMultipartForm(32 << 20); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
var files []FileInfo
|
||||
for fieldName, fileHeaders := range r.MultipartForm.File {
|
||||
for _, fh := range fileHeaders {
|
||||
file, err := fh.Open()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
data, err := io.ReadAll(file)
|
||||
file.Close()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
files = append(files, FileInfo{
|
||||
Fieldname: fieldName,
|
||||
Filename: fh.Filename,
|
||||
Size: fh.Size,
|
||||
Data: data,
|
||||
Header: *fh,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return files, nil
|
||||
}
|
||||
706
internal/api/grpcapi/client.go
Normal file
706
internal/api/grpcapi/client.go
Normal file
@@ -0,0 +1,706 @@
|
||||
package grpcapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/protobuf/types/known/anypb"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// gRPC Client SDK for Synapse Protocol
|
||||
// =============================================================================
|
||||
|
||||
// GRPCClient is a high-level client for Synapse gRPC services
|
||||
type GRPCClient struct {
|
||||
conn *grpc.ClientConn
|
||||
taskClient TaskServiceClient
|
||||
messageClient A2AMessageServiceClient
|
||||
capsClient CapabilitiesServiceClient
|
||||
groupClient GroupServiceClient
|
||||
healthClient HealthServiceClient
|
||||
|
||||
// Configuration
|
||||
apiKey string
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
// GRPCClientConfig client configuration
|
||||
type GRPCClientConfig struct {
|
||||
Address string
|
||||
APIKey string
|
||||
Timeout time.Duration
|
||||
Insecure bool // For development only
|
||||
}
|
||||
|
||||
// NewGRPCClient creates a new gRPC client
|
||||
func NewGRPCClient(config GRPCClientConfig) (*GRPCClient, error) {
|
||||
if config.Timeout == 0 {
|
||||
config.Timeout = 30 * time.Second
|
||||
}
|
||||
|
||||
var opts []grpc.DialOption
|
||||
|
||||
if config.Insecure {
|
||||
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
}
|
||||
|
||||
// Add interceptor for API key
|
||||
opts = append(opts, grpc.WithUnaryInterceptor(apiKeyInterceptor(config.APIKey)))
|
||||
opts = append(opts, grpc.WithStreamInterceptor(apiKeyStreamInterceptor(config.APIKey)))
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), config.Timeout)
|
||||
defer cancel()
|
||||
|
||||
conn, err := grpc.DialContext(ctx, config.Address, opts...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to connect: %w", err)
|
||||
}
|
||||
|
||||
return &GRPCClient{
|
||||
conn: conn,
|
||||
taskClient: NewTaskServiceClient(conn),
|
||||
messageClient: NewA2AMessageServiceClient(conn),
|
||||
capsClient: NewCapabilitiesServiceClient(conn),
|
||||
groupClient: NewGroupServiceClient(conn),
|
||||
healthClient: NewHealthServiceClient(conn),
|
||||
apiKey: config.APIKey,
|
||||
timeout: config.Timeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Close closes the client connection
|
||||
func (c *GRPCClient) Close() error {
|
||||
return c.conn.Close()
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Interceptors
|
||||
// =============================================================================
|
||||
|
||||
func apiKeyInterceptor(apiKey string) grpc.UnaryClientInterceptor {
|
||||
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
|
||||
if apiKey != "" {
|
||||
ctx = metadata.AppendToOutgoingContext(ctx, "x-api-key", apiKey)
|
||||
}
|
||||
return invoker(ctx, method, req, reply, cc, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
func apiKeyStreamInterceptor(apiKey string) grpc.StreamClientInterceptor {
|
||||
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
|
||||
if apiKey != "" {
|
||||
ctx = metadata.AppendToOutgoingContext(ctx, "x-api-key", apiKey)
|
||||
}
|
||||
return streamer(ctx, desc, cc, method, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Task Operations
|
||||
// =============================================================================
|
||||
|
||||
// SubmitTask submits a new task
|
||||
func (c *GRPCClient) SubmitTask(ctx context.Context, taskType string, payload map[string]any, opts ...TaskOption) (*SubmitTaskResponse, error) {
|
||||
req := &SubmitTaskRequest{
|
||||
TaskType: taskType,
|
||||
Priority: "normal",
|
||||
}
|
||||
|
||||
// Apply options
|
||||
for _, opt := range opts {
|
||||
opt(req)
|
||||
}
|
||||
|
||||
// Convert payload to Any
|
||||
if payload != nil {
|
||||
// In real implementation, use protojson.Marshal
|
||||
req.Payload = &anypb.Any{
|
||||
Value: []byte(fmt.Sprintf("%v", payload)),
|
||||
}
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
return c.taskClient.SubmitTask(ctx, req)
|
||||
}
|
||||
|
||||
// TaskOption configures task submission
|
||||
type TaskOption func(*SubmitTaskRequest)
|
||||
|
||||
func WithExternalTaskID(id string) TaskOption {
|
||||
return func(r *SubmitTaskRequest) {
|
||||
r.ExternalTaskId = id
|
||||
}
|
||||
}
|
||||
|
||||
func WithPriority(priority string) TaskOption {
|
||||
return func(r *SubmitTaskRequest) {
|
||||
r.Priority = priority
|
||||
}
|
||||
}
|
||||
|
||||
func WithCallback(url, token string) TaskOption {
|
||||
return func(r *SubmitTaskRequest) {
|
||||
r.CallbackUrl = url
|
||||
r.CallbackToken = token
|
||||
}
|
||||
}
|
||||
|
||||
func WithTransportMode(mode TransportMode) TaskOption {
|
||||
return func(r *SubmitTaskRequest) {
|
||||
r.PreferredTransport = mode
|
||||
}
|
||||
}
|
||||
|
||||
// GetTask gets task details
|
||||
func (c *GRPCClient) GetTask(ctx context.Context, taskID string) (*TaskInfo, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
resp, err := c.taskClient.GetTask(ctx, &GetTaskRequest{TaskId: taskID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !resp.Success {
|
||||
return nil, fmt.Errorf("task query failed: %s", resp.ErrorMessage)
|
||||
}
|
||||
|
||||
return resp.Task, nil
|
||||
}
|
||||
|
||||
// GetTaskStatus gets simplified task status
|
||||
func (c *GRPCClient) GetTaskStatus(ctx context.Context, taskID string) (*TaskInfo, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
resp, err := c.taskClient.GetTaskStatus(ctx, &GetTaskRequest{TaskId: taskID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !resp.Success {
|
||||
return nil, fmt.Errorf("status query failed: %s", resp.ErrorMessage)
|
||||
}
|
||||
|
||||
return resp.Task, nil
|
||||
}
|
||||
|
||||
// ListTasks lists tasks with filtering
|
||||
func (c *GRPCClient) ListTasks(ctx context.Context, status string, limit, offset int) (*ListTasksResponse, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
return c.taskClient.ListTasks(ctx, &ListTasksRequest{
|
||||
Status: status,
|
||||
Limit: int32(limit),
|
||||
Offset: int32(offset),
|
||||
})
|
||||
}
|
||||
|
||||
// CancelTask cancels a task
|
||||
func (c *GRPCClient) CancelTask(ctx context.Context, taskID string) (*CancelTaskResponse, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
return c.taskClient.CancelTask(ctx, &CancelTaskRequest{TaskId: taskID})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Streaming Operations
|
||||
// =============================================================================
|
||||
|
||||
// StreamTaskStatus streams task status updates
|
||||
func (c *GRPCClient) StreamTaskStatus(ctx context.Context, taskID string) (<-chan *TaskStatusUpdate, error) {
|
||||
stream, err := c.taskClient.StreamTaskStatus(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to start stream: %w", err)
|
||||
}
|
||||
|
||||
// Send subscription request
|
||||
if err := stream.Send(&TaskStatusStreamRequest{
|
||||
TaskId: taskID,
|
||||
Subscribe: true,
|
||||
}); err != nil {
|
||||
return nil, fmt.Errorf("failed to subscribe: %w", err)
|
||||
}
|
||||
|
||||
updateChan := make(chan *TaskStatusUpdate, 100)
|
||||
|
||||
go func() {
|
||||
defer close(updateChan)
|
||||
for {
|
||||
update, err := stream.Recv()
|
||||
if err == io.EOF {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("[gRPC Stream] Receive error: %v", err)
|
||||
return
|
||||
}
|
||||
updateChan <- update
|
||||
}
|
||||
}()
|
||||
|
||||
return updateChan, nil
|
||||
}
|
||||
|
||||
// StreamMessages opens a bidirectional message stream
|
||||
func (c *GRPCClient) StreamMessages(ctx context.Context) (chan<- *A2AMessage, <-chan *A2AMessage, error) {
|
||||
stream, err := c.messageClient.StreamMessages(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to start message stream: %w", err)
|
||||
}
|
||||
|
||||
sendChan := make(chan *A2AMessage, 100)
|
||||
recvChan := make(chan *A2AMessage, 100)
|
||||
|
||||
// Send goroutine
|
||||
go func() {
|
||||
for msg := range sendChan {
|
||||
if err := stream.Send(msg); err != nil {
|
||||
log.Printf("[gRPC Stream] Send error: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Receive goroutine
|
||||
go func() {
|
||||
defer close(recvChan)
|
||||
for {
|
||||
msg, err := stream.Recv()
|
||||
if err == io.EOF {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("[gRPC Stream] Receive error: %v", err)
|
||||
return
|
||||
}
|
||||
recvChan <- msg
|
||||
}
|
||||
}()
|
||||
|
||||
return sendChan, recvChan, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Message Operations
|
||||
// =============================================================================
|
||||
|
||||
// SendMessage sends a single Synapse message
|
||||
func (c *GRPCClient) SendMessage(ctx context.Context, msg *A2AMessage) (*SendMessageResponse, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
return c.messageClient.SendMessage(ctx, &SendMessageRequest{Message: msg})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Capabilities Operations
|
||||
// =============================================================================
|
||||
|
||||
// GetCapabilities gets agent capabilities
|
||||
func (c *GRPCClient) GetCapabilities(ctx context.Context) (*AgentCapabilities, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
resp, err := c.capsClient.GetCapabilities(ctx, &emptypb.Empty{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !resp.Success {
|
||||
return nil, fmt.Errorf("capabilities query failed: %s", resp.Error)
|
||||
}
|
||||
|
||||
return resp.Capabilities, nil
|
||||
}
|
||||
|
||||
// ListAgents lists available agents
|
||||
func (c *GRPCClient) ListAgents(ctx context.Context) ([]*AgentInfo, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
resp, err := c.capsClient.ListAgents(ctx, &emptypb.Empty{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !resp.Success {
|
||||
return nil, fmt.Errorf("agent list failed")
|
||||
}
|
||||
|
||||
return resp.Agents, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Group Operations
|
||||
// =============================================================================
|
||||
|
||||
// CreateGroup creates a new group
|
||||
func (c *GRPCClient) CreateGroup(ctx context.Context, name, description, coordinatorID string, initialMembers []string) (*GroupInfo, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
resp, err := c.groupClient.CreateGroup(ctx, &CreateGroupRequest{
|
||||
Name: name,
|
||||
Description: description,
|
||||
CoordinatorId: coordinatorID,
|
||||
InitialMembers: initialMembers,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !resp.Success {
|
||||
return nil, fmt.Errorf("group creation failed: %s", resp.Error)
|
||||
}
|
||||
|
||||
return resp.Group, nil
|
||||
}
|
||||
|
||||
// JoinGroup joins an existing group
|
||||
func (c *GRPCClient) JoinGroup(ctx context.Context, groupID string, agent *AgentEndpoint) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
resp, err := c.groupClient.JoinGroup(ctx, &JoinGroupRequest{
|
||||
GroupId: groupID,
|
||||
Agent: agent,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !resp.Success {
|
||||
return fmt.Errorf("join failed: %s", resp.Error)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// LeaveGroup leaves a group
|
||||
func (c *GRPCClient) LeaveGroup(ctx context.Context, groupID, agentID string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
resp, err := c.groupClient.LeaveGroup(ctx, &LeaveGroupRequest{
|
||||
GroupId: groupID,
|
||||
AgentId: agentID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !resp.Success {
|
||||
return fmt.Errorf("leave failed: %s", resp.Error)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListGroupMembers lists group members
|
||||
func (c *GRPCClient) ListGroupMembers(ctx context.Context, groupID string) ([]*GroupMember, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
resp, err := c.groupClient.ListGroupMembers(ctx, &ListGroupMembersRequest{GroupId: groupID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !resp.Success {
|
||||
return nil, fmt.Errorf("member list failed")
|
||||
}
|
||||
|
||||
return resp.Members, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Voting Operations (Group Protocol)
|
||||
// =============================================================================
|
||||
|
||||
// InitiateVote initiates a vote in a group
|
||||
func (c *GRPCClient) InitiateVote(ctx context.Context, groupID, initiatorID, question string, options []string, threshold float64, timeoutSeconds int32) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
resp, err := c.groupClient.InitiateVote(ctx, &VoteRequest{
|
||||
GroupId: groupID,
|
||||
InitiatorId: initiatorID,
|
||||
Question: question,
|
||||
Options: options,
|
||||
Threshold: threshold,
|
||||
TimeoutSeconds: timeoutSeconds,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if !resp.Success {
|
||||
return "", fmt.Errorf("initiate vote failed: %s", resp.Error)
|
||||
}
|
||||
|
||||
return resp.VoteId, nil
|
||||
}
|
||||
|
||||
// SubmitVote submits a vote
|
||||
func (c *GRPCClient) SubmitVote(ctx context.Context, voteID, agentID, option, reason string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
resp, err := c.groupClient.SubmitVote(ctx, &SubmitVoteRequest{
|
||||
VoteId: voteID,
|
||||
AgentId: agentID,
|
||||
Option: option,
|
||||
Reason: reason,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !resp.Success {
|
||||
return fmt.Errorf("submit vote failed: %s", resp.Error)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetVoteStatus gets the current status of a vote
|
||||
func (c *GRPCClient) GetVoteStatus(ctx context.Context, voteID string) (*VoteStatusResponse, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
return c.groupClient.GetVoteStatus(ctx, &GetVoteStatusRequest{VoteId: voteID})
|
||||
}
|
||||
|
||||
// WaitForVote waits for a vote to complete
|
||||
func (c *GRPCClient) WaitForVote(ctx context.Context, voteID string, interval time.Duration) (*VoteStatusResponse, error) {
|
||||
if interval == 0 {
|
||||
interval = 2 * time.Second
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-ticker.C:
|
||||
status, err := c.GetVoteStatus(ctx, voteID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if status.Status == "decided" || status.Status == "expired" {
|
||||
return status, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Task Split & Merge Operations (Group Protocol)
|
||||
// =============================================================================
|
||||
|
||||
// SplitTask splits a task into subtasks
|
||||
func (c *GRPCClient) SplitTask(ctx context.Context, groupID, taskID, taskType, requirements string, strategy SplitStrategy) ([]*SubtaskInfo, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
resp, err := c.groupClient.SplitTask(ctx, &SplitTaskRequest{
|
||||
GroupId: groupID,
|
||||
TaskId: taskID,
|
||||
TaskType: taskType,
|
||||
Requirements: requirements,
|
||||
Strategy: strategy,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !resp.Success {
|
||||
return nil, fmt.Errorf("split task failed: %s", resp.Error)
|
||||
}
|
||||
|
||||
return resp.Subtasks, nil
|
||||
}
|
||||
|
||||
// MergeResults merges subtask results
|
||||
func (c *GRPCClient) MergeResults(ctx context.Context, groupID, parentTaskID string, strategy MergeStrategy) (*MergeResultsResponse, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
return c.groupClient.MergeResults(ctx, &MergeResultsRequest{
|
||||
GroupId: groupID,
|
||||
ParentTaskId: parentTaskID,
|
||||
Strategy: strategy,
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Health Operations
|
||||
// =============================================================================
|
||||
|
||||
// HealthCheck checks server health
|
||||
func (c *GRPCClient) HealthCheck(ctx context.Context) (*HealthCheckResponse, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
return c.healthClient.HealthCheck(ctx, &emptypb.Empty{})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// High-Level Helpers
|
||||
// =============================================================================
|
||||
|
||||
// CreateAndWait creates a task and waits for completion via streaming
|
||||
func (c *GRPCClient) CreateAndWait(ctx context.Context, taskType string, payload map[string]any, timeout time.Duration) (*TaskInfo, error) {
|
||||
// Submit task
|
||||
resp, err := c.SubmitTask(ctx, taskType, payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !resp.Success {
|
||||
return nil, fmt.Errorf("task submission failed: %s", resp.Message)
|
||||
}
|
||||
|
||||
// Stream status until completion
|
||||
updateChan, err := c.StreamTaskStatus(ctx, resp.TaskId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Wait with timeout
|
||||
if timeout == 0 {
|
||||
timeout = 5 * time.Minute
|
||||
}
|
||||
timer := time.NewTimer(timeout)
|
||||
defer timer.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case update := <-updateChan:
|
||||
if update == nil {
|
||||
return nil, fmt.Errorf("stream closed unexpectedly")
|
||||
}
|
||||
|
||||
switch update.Status {
|
||||
case TaskStatus_TASK_STATUS_COMPLETED:
|
||||
return &TaskInfo{
|
||||
Id: resp.TaskId,
|
||||
Status: update.Status,
|
||||
Progress: update.Progress,
|
||||
Message: update.Message,
|
||||
}, nil
|
||||
case TaskStatus_TASK_STATUS_FAILED, TaskStatus_TASK_STATUS_CANCELLED:
|
||||
return nil, fmt.Errorf("task failed: %s", update.Message)
|
||||
}
|
||||
|
||||
case <-timer.C:
|
||||
return nil, fmt.Errorf("timeout waiting for task completion")
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WaitForTask waits for a task to complete using polling
|
||||
func (c *GRPCClient) 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:
|
||||
task, err := c.GetTaskStatus(ctx, taskID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
switch task.Status {
|
||||
case TaskStatus_TASK_STATUS_COMPLETED:
|
||||
return task, nil
|
||||
case TaskStatus_TASK_STATUS_FAILED, TaskStatus_TASK_STATUS_CANCELLED:
|
||||
return task, fmt.Errorf("task failed: %s", task.Message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Builder Pattern for A2AMessage
|
||||
// =============================================================================
|
||||
|
||||
// MessageBuilder builds Synapse messages
|
||||
type MessageBuilder struct {
|
||||
msg *A2AMessage
|
||||
}
|
||||
|
||||
// NewMessage creates a new message builder
|
||||
func NewMessage() *MessageBuilder {
|
||||
return &MessageBuilder{
|
||||
msg: &A2AMessage{
|
||||
Id: generateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Timestamp: timestamppb.Now(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (b *MessageBuilder) Type(msgType MessageType) *MessageBuilder {
|
||||
b.msg.Type = msgType
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MessageBuilder) From(sender *AgentEndpoint) *MessageBuilder {
|
||||
b.msg.Sender = sender
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MessageBuilder) To(receiver *AgentEndpoint) *MessageBuilder {
|
||||
b.msg.Receiver = receiver
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MessageBuilder) CorrelationID(id string) *MessageBuilder {
|
||||
b.msg.CorrelationId = id
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MessageBuilder) GroupID(id string) *MessageBuilder {
|
||||
b.msg.GroupId = id
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MessageBuilder) Payload(payload []byte) *MessageBuilder {
|
||||
b.msg.Payload = &anypb.Any{Value: payload}
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *MessageBuilder) Build() *A2AMessage {
|
||||
return b.msg
|
||||
}
|
||||
|
||||
func generateMessageID() string {
|
||||
return fmt.Sprintf("msg-%d", time.Now().UnixNano())
|
||||
}
|
||||
861
internal/api/grpcapi/server.go
Normal file
861
internal/api/grpcapi/server.go
Normal file
@@ -0,0 +1,861 @@
|
||||
package grpcapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/types/known/anypb"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// gRPC Server Implementation
|
||||
// =============================================================================
|
||||
|
||||
// GRPCServer wraps the gRPC server and gateway
|
||||
type GRPCServer struct {
|
||||
grpcServer *grpc.Server
|
||||
gateway *http.Server
|
||||
mu sync.RWMutex
|
||||
|
||||
// Services
|
||||
taskService *TaskServiceImpl
|
||||
messageService *MessageServiceImpl
|
||||
capabilitiesService *CapabilitiesServiceImpl
|
||||
groupService *GroupServiceImpl
|
||||
healthService *HealthServiceImpl
|
||||
|
||||
// Dependencies
|
||||
taskExecutor TaskExecutor
|
||||
msgRouter MessageRouter
|
||||
capsProvider CapabilitiesProvider
|
||||
groupManager GroupManager
|
||||
}
|
||||
|
||||
// TaskExecutor interface for task operations
|
||||
type TaskExecutor interface {
|
||||
SubmitTask(ctx context.Context, taskType string, payload map[string]any, externalTaskID, priority, callbackURL, callbackToken string) (string, string, error)
|
||||
GetTaskStatus(ctx context.Context, taskID string) (*types.TaskInfo, error)
|
||||
ListTasks(ctx context.Context, status string, limit, offset int) ([]types.TaskInfo, int, error)
|
||||
CancelTask(ctx context.Context, taskID string) error
|
||||
}
|
||||
|
||||
type MessageRouter interface {
|
||||
RouteMessage(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error)
|
||||
}
|
||||
|
||||
type CapabilitiesProvider interface {
|
||||
GetCapabilities(ctx context.Context) (*types.AgentCapabilities, error)
|
||||
}
|
||||
|
||||
type GroupManager interface {
|
||||
CreateGroup(ctx context.Context, name, description, coordinatorID string, initialMembers []string) (string, error)
|
||||
JoinGroup(ctx context.Context, groupID string, agent *types.AgentEndpoint) error
|
||||
LeaveGroup(ctx context.Context, groupID, agentID string) error
|
||||
DisbandGroup(ctx context.Context, groupID string) error
|
||||
ListMembers(ctx context.Context, groupID string) ([]types.GroupMember, error)
|
||||
|
||||
// Voting operations
|
||||
InitiateVote(ctx context.Context, groupID, initiatorID, question string, options []string, threshold float64, timeoutSeconds int32) (string, error)
|
||||
SubmitVote(ctx context.Context, voteID, agentID, option, reason string) error
|
||||
GetVoteStatus(ctx context.Context, voteID string) (*VoteStatus, error)
|
||||
|
||||
// Task split and merge
|
||||
SplitTask(ctx context.Context, groupID, taskID, taskType, requirements string, strategy SplitStrategy) ([]*SubtaskInfo, error)
|
||||
MergeResults(ctx context.Context, groupID, parentTaskID string, strategy MergeStrategy) (*anypb.Any, string, error)
|
||||
}
|
||||
|
||||
// VoteStatus represents the status of a vote
|
||||
type VoteStatus struct {
|
||||
VoteID string
|
||||
Status string // open, decided, expired
|
||||
Question string
|
||||
TotalVotes int
|
||||
RequiredVotes int
|
||||
WinningOption string
|
||||
Votes map[string]string // agentID -> option
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Server Constructor
|
||||
// =============================================================================
|
||||
|
||||
// NewGRPCServer creates a new gRPC server
|
||||
func NewGRPCServer(taskExec TaskExecutor, msgRouter MessageRouter, capsProvider CapabilitiesProvider, groupManager GroupManager) *GRPCServer {
|
||||
return &GRPCServer{
|
||||
taskExecutor: taskExec,
|
||||
msgRouter: msgRouter,
|
||||
capsProvider: capsProvider,
|
||||
groupManager: groupManager,
|
||||
taskService: &TaskServiceImpl{},
|
||||
messageService: &MessageServiceImpl{},
|
||||
capabilitiesService: &CapabilitiesServiceImpl{},
|
||||
groupService: &GroupServiceImpl{},
|
||||
healthService: &HealthServiceImpl{},
|
||||
}
|
||||
}
|
||||
|
||||
// Start starts both gRPC and gateway servers
|
||||
func (s *GRPCServer) Start(grpcPort, gatewayPort int) error {
|
||||
// Start gRPC server
|
||||
go func() {
|
||||
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", grpcPort))
|
||||
if err != nil {
|
||||
log.Fatalf("[gRPC] Failed to listen: %v", err)
|
||||
}
|
||||
|
||||
// Create gRPC server with interceptors
|
||||
opts := []grpc.ServerOption{
|
||||
grpc.UnaryInterceptor(s.unaryInterceptor),
|
||||
grpc.StreamInterceptor(s.streamInterceptor),
|
||||
}
|
||||
s.grpcServer = grpc.NewServer(opts...)
|
||||
|
||||
// Register services
|
||||
// Note: These would be generated from proto
|
||||
// RegisterTaskServiceServer(s.grpcServer, s.taskService)
|
||||
// RegisterA2AMessageServiceServer(s.grpcServer, s.messageService)
|
||||
// ... etc
|
||||
|
||||
log.Printf("[gRPC] Server started on port %d", grpcPort)
|
||||
if err := s.grpcServer.Serve(lis); err != nil {
|
||||
log.Fatalf("[gRPC] Failed to serve: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Start gRPC-Gateway
|
||||
go func() {
|
||||
_ = context.Background() // ctx reserved for future gateway handler registration
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// Register gateway handlers
|
||||
// Note: These would be generated from proto by grpc-gateway
|
||||
// err := RegisterTaskServiceHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%d", grpcPort), opts)
|
||||
// ... etc
|
||||
|
||||
s.gateway = &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", gatewayPort),
|
||||
Handler: mux,
|
||||
}
|
||||
|
||||
log.Printf("[Gateway] HTTP server started on port %d", gatewayPort)
|
||||
if err := s.gateway.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("[Gateway] Failed to serve: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop gracefully stops both servers
|
||||
func (s *GRPCServer) Stop() {
|
||||
if s.grpcServer != nil {
|
||||
s.grpcServer.GracefulStop()
|
||||
}
|
||||
if s.gateway != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
s.gateway.Shutdown(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Interceptors
|
||||
// =============================================================================
|
||||
|
||||
func (s *GRPCServer) unaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
|
||||
// Extract metadata
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if ok {
|
||||
// Check API key
|
||||
apiKeys := md.Get("x-api-key")
|
||||
if len(apiKeys) > 0 {
|
||||
// Validate API key
|
||||
log.Printf("[gRPC] API Key: %s", apiKeys[0])
|
||||
}
|
||||
}
|
||||
|
||||
// Call handler
|
||||
return handler(ctx, req)
|
||||
}
|
||||
|
||||
func (s *GRPCServer) streamInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
|
||||
// Extract metadata
|
||||
md, ok := metadata.FromIncomingContext(ss.Context())
|
||||
if ok {
|
||||
apiKeys := md.Get("x-api-key")
|
||||
if len(apiKeys) > 0 {
|
||||
log.Printf("[gRPC Stream] API Key: %s", apiKeys[0])
|
||||
}
|
||||
}
|
||||
|
||||
return handler(srv, ss)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Task Service Implementation
|
||||
// =============================================================================
|
||||
|
||||
type TaskServiceImpl struct {
|
||||
UnimplementedTaskServiceServer
|
||||
taskExecutor TaskExecutor
|
||||
mu sync.RWMutex
|
||||
streamClients map[string]chan *TaskStatusUpdate
|
||||
}
|
||||
|
||||
func (s *TaskServiceImpl) SubmitTask(ctx context.Context, req *SubmitTaskRequest) (*SubmitTaskResponse, error) {
|
||||
// Convert payload
|
||||
payload := make(map[string]any)
|
||||
if req.Payload != nil {
|
||||
// Unpack Any to map
|
||||
// This would use protojson or similar
|
||||
}
|
||||
|
||||
taskID, status, err := s.taskExecutor.SubmitTask(
|
||||
ctx,
|
||||
req.TaskType,
|
||||
payload,
|
||||
req.ExternalTaskId,
|
||||
req.Priority,
|
||||
req.CallbackUrl,
|
||||
req.CallbackToken,
|
||||
)
|
||||
if err != nil {
|
||||
return &SubmitTaskResponse{
|
||||
Success: false,
|
||||
ErrorCode: "TASK_SUBMISSION_FAILED",
|
||||
Message: err.Error(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &SubmitTaskResponse{
|
||||
Success: true,
|
||||
TaskId: taskID,
|
||||
Status: parseTaskStatus(status),
|
||||
Message: "任务已接收",
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *TaskServiceImpl) SubmitTaskWithFiles(ctx context.Context, req *SubmitTaskWithFilesRequest) (*SubmitTaskResponse, error) {
|
||||
// Handle file uploads
|
||||
// Convert files and call SubmitTask
|
||||
return s.SubmitTask(ctx, req.Request)
|
||||
}
|
||||
|
||||
func (s *TaskServiceImpl) GetTask(ctx context.Context, req *GetTaskRequest) (*TaskStatusResponse, error) {
|
||||
task, err := s.taskExecutor.GetTaskStatus(ctx, req.TaskId)
|
||||
if err != nil {
|
||||
return &TaskStatusResponse{
|
||||
Success: false,
|
||||
ErrorCode: "TASK_NOT_FOUND",
|
||||
ErrorMessage: err.Error(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &TaskStatusResponse{
|
||||
Success: true,
|
||||
Task: convertTaskInfo(task),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *TaskServiceImpl) GetTaskStatus(ctx context.Context, req *GetTaskRequest) (*TaskStatusResponse, error) {
|
||||
return s.GetTask(ctx, req)
|
||||
}
|
||||
|
||||
func (s *TaskServiceImpl) ListTasks(ctx context.Context, req *ListTasksRequest) (*ListTasksResponse, error) {
|
||||
tasks, total, err := s.taskExecutor.ListTasks(ctx, req.Status, int(req.Limit), int(req.Offset))
|
||||
if err != nil {
|
||||
return &ListTasksResponse{
|
||||
Success: false,
|
||||
}, err
|
||||
}
|
||||
|
||||
var protoTasks []*TaskInfo
|
||||
for _, t := range tasks {
|
||||
protoTasks = append(protoTasks, convertTaskInfo(&t))
|
||||
}
|
||||
|
||||
return &ListTasksResponse{
|
||||
Success: true,
|
||||
Tasks: protoTasks,
|
||||
Total: int32(total),
|
||||
Limit: req.Limit,
|
||||
Offset: req.Offset,
|
||||
HasMore: int(req.Offset+req.Limit) < total,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *TaskServiceImpl) CancelTask(ctx context.Context, req *CancelTaskRequest) (*CancelTaskResponse, error) {
|
||||
if err := s.taskExecutor.CancelTask(ctx, req.TaskId); err != nil {
|
||||
return &CancelTaskResponse{
|
||||
Success: false,
|
||||
Message: err.Error(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &CancelTaskResponse{
|
||||
Success: true,
|
||||
TaskId: req.TaskId,
|
||||
Status: TaskStatus_TASK_STATUS_CANCELLED,
|
||||
Message: "任务已取消",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// StreamTaskStatus implements bidirectional streaming for task status updates
|
||||
func (s *TaskServiceImpl) StreamTaskStatus(stream TaskService_StreamTaskStatusServer) error {
|
||||
// Register client
|
||||
clientID := fmt.Sprintf("stream-%d", time.Now().UnixNano())
|
||||
statusChan := make(chan *TaskStatusUpdate, 100)
|
||||
|
||||
s.mu.Lock()
|
||||
s.streamClients[clientID] = statusChan
|
||||
s.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
s.mu.Lock()
|
||||
delete(s.streamClients, clientID)
|
||||
s.mu.Unlock()
|
||||
close(statusChan)
|
||||
}()
|
||||
|
||||
// Goroutine to send status updates
|
||||
go func() {
|
||||
for update := range statusChan {
|
||||
if err := stream.Send(update); err != nil {
|
||||
log.Printf("[gRPC Stream] Send error: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Receive subscription requests
|
||||
for {
|
||||
req, err := stream.Recv()
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if req.Subscribe {
|
||||
log.Printf("[gRPC Stream] Client %s subscribed to task %s", clientID, req.TaskId)
|
||||
// Start watching task status
|
||||
go s.watchTaskStatus(req.TaskId, statusChan)
|
||||
} else {
|
||||
log.Printf("[gRPC Stream] Client %s unsubscribed from task %s", clientID, req.TaskId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TaskServiceImpl) watchTaskStatus(taskID string, ch chan *TaskStatusUpdate) {
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for range ticker.C {
|
||||
task, err := s.taskExecutor.GetTaskStatus(context.Background(), taskID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
ch <- &TaskStatusUpdate{
|
||||
TaskId: taskID,
|
||||
Status: parseTaskStatus(task.Status),
|
||||
Progress: int32(task.Progress),
|
||||
Message: task.Message,
|
||||
}
|
||||
|
||||
// Stop if terminal state
|
||||
if task.Status == "completed" || task.Status == "failed" || task.Status == "cancelled" {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Message Service Implementation
|
||||
// =============================================================================
|
||||
|
||||
type MessageServiceImpl struct {
|
||||
UnimplementedA2AMessageServiceServer
|
||||
msgRouter MessageRouter
|
||||
}
|
||||
|
||||
func (s *MessageServiceImpl) SendMessage(ctx context.Context, req *SendMessageRequest) (*SendMessageResponse, error) {
|
||||
// Convert proto message to internal format
|
||||
msg := convertProtoToInternalMessage(req.Message)
|
||||
|
||||
resp, err := s.msgRouter.RouteMessage(ctx, msg)
|
||||
if err != nil {
|
||||
return &SendMessageResponse{
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &SendMessageResponse{
|
||||
Success: true,
|
||||
MessageId: resp.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// StreamMessages implements bidirectional streaming for Synapse messages
|
||||
func (s *MessageServiceImpl) StreamMessages(stream A2AMessageService_StreamMessagesServer) error {
|
||||
ctx := stream.Context()
|
||||
clientID := fmt.Sprintf("msg-stream-%d", time.Now().UnixNano())
|
||||
|
||||
log.Printf("[gRPC Stream] New message stream: %s", clientID)
|
||||
|
||||
// Goroutine to receive messages
|
||||
go func() {
|
||||
for {
|
||||
msg, err := stream.Recv()
|
||||
if err == io.EOF {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("[gRPC Stream] Receive error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
internalMsg := convertProtoToInternalMessage(msg)
|
||||
resp, err := s.msgRouter.RouteMessage(ctx, internalMsg)
|
||||
if err != nil {
|
||||
log.Printf("[gRPC Stream] Route error: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
protoResp := convertInternalToProtoMessage(resp)
|
||||
if err := stream.Send(protoResp); err != nil {
|
||||
log.Printf("[gRPC Stream] Send error: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Keep stream alive
|
||||
<-ctx.Done()
|
||||
log.Printf("[gRPC Stream] Message stream closed: %s", clientID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *MessageServiceImpl) ReceiveCallback(req *emptypb.Empty, stream A2AMessageService_ReceiveCallbackServer) error {
|
||||
// This would be used by agents to receive callback messages via gRPC stream
|
||||
// Implementation depends on callback routing mechanism
|
||||
return status.Error(codes.Unimplemented, "not implemented")
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Capabilities Service Implementation
|
||||
// =============================================================================
|
||||
|
||||
type CapabilitiesServiceImpl struct {
|
||||
UnimplementedCapabilitiesServiceServer
|
||||
provider CapabilitiesProvider
|
||||
}
|
||||
|
||||
func (s *CapabilitiesServiceImpl) GetCapabilities(ctx context.Context, req *emptypb.Empty) (*CapabilitiesResponse, error) {
|
||||
caps, err := s.provider.GetCapabilities(ctx)
|
||||
if err != nil {
|
||||
return &CapabilitiesResponse{
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &CapabilitiesResponse{
|
||||
Success: true,
|
||||
Capabilities: convertAgentCapabilities(caps),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *CapabilitiesServiceImpl) QueryAgent(ctx context.Context, req *QueryAgentRequest) (*CapabilitiesResponse, error) {
|
||||
// Query specific agent's capabilities
|
||||
return s.GetCapabilities(ctx, nil)
|
||||
}
|
||||
|
||||
func (s *CapabilitiesServiceImpl) ListAgents(ctx context.Context, req *emptypb.Empty) (*ListAgentsResponse, error) {
|
||||
return &ListAgentsResponse{
|
||||
Success: true,
|
||||
Agents: []*AgentInfo{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Group Service Implementation
|
||||
// =============================================================================
|
||||
|
||||
type GroupServiceImpl struct {
|
||||
UnimplementedGroupServiceServer
|
||||
groupManager GroupManager
|
||||
}
|
||||
|
||||
func (s *GroupServiceImpl) CreateGroup(ctx context.Context, req *CreateGroupRequest) (*CreateGroupResponse, error) {
|
||||
groupID, err := s.groupManager.CreateGroup(ctx, req.Name, req.Description, req.CoordinatorId, req.InitialMembers)
|
||||
if err != nil {
|
||||
return &CreateGroupResponse{
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &CreateGroupResponse{
|
||||
Success: true,
|
||||
GroupId: groupID,
|
||||
Group: &GroupInfo{
|
||||
Id: groupID,
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
CoordinatorId: req.CoordinatorId,
|
||||
Status: "active",
|
||||
CreatedAt: timestamppb.Now(),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *GroupServiceImpl) JoinGroup(ctx context.Context, req *JoinGroupRequest) (*JoinGroupResponse, error) {
|
||||
err := s.groupManager.JoinGroup(ctx, req.GroupId, convertProtoEndpoint(req.Agent))
|
||||
if err != nil {
|
||||
return &JoinGroupResponse{Success: false, Error: err.Error()}, nil
|
||||
}
|
||||
return &JoinGroupResponse{Success: true}, nil
|
||||
}
|
||||
|
||||
func (s *GroupServiceImpl) LeaveGroup(ctx context.Context, req *LeaveGroupRequest) (*LeaveGroupResponse, error) {
|
||||
err := s.groupManager.LeaveGroup(ctx, req.GroupId, req.AgentId)
|
||||
if err != nil {
|
||||
return &LeaveGroupResponse{Success: false, Error: err.Error()}, nil
|
||||
}
|
||||
return &LeaveGroupResponse{Success: true}, nil
|
||||
}
|
||||
|
||||
func (s *GroupServiceImpl) DisbandGroup(ctx context.Context, req *DisbandGroupRequest) (*DisbandGroupResponse, error) {
|
||||
err := s.groupManager.DisbandGroup(ctx, req.GroupId)
|
||||
if err != nil {
|
||||
return &DisbandGroupResponse{Success: false, Error: err.Error()}, nil
|
||||
}
|
||||
return &DisbandGroupResponse{Success: true}, nil
|
||||
}
|
||||
|
||||
func (s *GroupServiceImpl) ListGroupMembers(ctx context.Context, req *ListGroupMembersRequest) (*ListGroupMembersResponse, error) {
|
||||
members, err := s.groupManager.ListMembers(ctx, req.GroupId)
|
||||
if err != nil {
|
||||
return &ListGroupMembersResponse{Success: false}, nil
|
||||
}
|
||||
|
||||
var protoMembers []*GroupMember
|
||||
for _, m := range members {
|
||||
protoMembers = append(protoMembers, &GroupMember{
|
||||
AgentId: m.AgentID,
|
||||
AgentName: m.AgentName,
|
||||
Role: m.Role,
|
||||
Status: string(m.Status),
|
||||
JoinedAt: timestamppb.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
return &ListGroupMembersResponse{
|
||||
Success: true,
|
||||
Members: protoMembers,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// StreamGroupMessages implements bidirectional streaming for group messages
|
||||
func (s *GroupServiceImpl) StreamGroupMessages(stream GroupService_StreamGroupMessagesServer) error {
|
||||
ctx := stream.Context()
|
||||
clientID := fmt.Sprintf("group-stream-%d", time.Now().UnixNano())
|
||||
|
||||
log.Printf("[gRPC Stream] New group stream: %s", clientID)
|
||||
|
||||
go func() {
|
||||
for {
|
||||
msg, err := stream.Recv()
|
||||
if err == io.EOF {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("[gRPC Stream] Receive error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("[gRPC Stream] Group message received: group=%s, type=%v", msg.GroupId, msg.Type)
|
||||
|
||||
// Echo back for now
|
||||
if err := stream.Send(msg); err != nil {
|
||||
log.Printf("[gRPC Stream] Send error: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
<-ctx.Done()
|
||||
log.Printf("[gRPC Stream] Group stream closed: %s", clientID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// InitiateVote initiates a voting process in the group
|
||||
func (s *GroupServiceImpl) InitiateVote(ctx context.Context, req *VoteRequest) (*VoteResponse, error) {
|
||||
voteID, err := s.groupManager.InitiateVote(ctx, req.GroupId, req.InitiatorId, req.Question, req.Options, req.Threshold, req.TimeoutSeconds)
|
||||
if err != nil {
|
||||
return &VoteResponse{
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &VoteResponse{
|
||||
Success: true,
|
||||
VoteId: voteID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SubmitVote submits a vote in an ongoing voting process
|
||||
func (s *GroupServiceImpl) SubmitVote(ctx context.Context, req *SubmitVoteRequest) (*SubmitVoteResponse, error) {
|
||||
err := s.groupManager.SubmitVote(ctx, req.VoteId, req.AgentId, req.Option, req.Reason)
|
||||
if err != nil {
|
||||
return &SubmitVoteResponse{
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &SubmitVoteResponse{
|
||||
Success: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetVoteStatus gets the current status of a vote
|
||||
func (s *GroupServiceImpl) GetVoteStatus(ctx context.Context, req *GetVoteStatusRequest) (*VoteStatusResponse, error) {
|
||||
status, err := s.groupManager.GetVoteStatus(ctx, req.VoteId)
|
||||
if err != nil {
|
||||
return &VoteStatusResponse{
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &VoteStatusResponse{
|
||||
Success: true,
|
||||
VoteId: status.VoteID,
|
||||
Status: status.Status,
|
||||
Question: status.Question,
|
||||
TotalVotes: int32(status.TotalVotes),
|
||||
RequiredVotes: int32(status.RequiredVotes),
|
||||
WinningOption: status.WinningOption,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SplitTask splits a task into subtasks across group members
|
||||
func (s *GroupServiceImpl) SplitTask(ctx context.Context, req *SplitTaskRequest) (*SplitTaskResponse, error) {
|
||||
subtasks, err := s.groupManager.SplitTask(ctx, req.GroupId, req.TaskId, req.TaskType, req.Requirements, req.Strategy)
|
||||
if err != nil {
|
||||
return &SplitTaskResponse{
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &SplitTaskResponse{
|
||||
Success: true,
|
||||
GroupId: req.GroupId,
|
||||
ParentTaskId: req.TaskId,
|
||||
Subtasks: subtasks,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// MergeResults merges results from subtasks
|
||||
func (s *GroupServiceImpl) MergeResults(ctx context.Context, req *MergeResultsRequest) (*MergeResultsResponse, error) {
|
||||
mergedResult, summary, err := s.groupManager.MergeResults(ctx, req.GroupId, req.ParentTaskId, req.Strategy)
|
||||
if err != nil {
|
||||
return &MergeResultsResponse{
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &MergeResultsResponse{
|
||||
Success: true,
|
||||
ParentTaskId: req.ParentTaskId,
|
||||
MergedResult: mergedResult,
|
||||
Summary: summary,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Health Service Implementation
|
||||
// =============================================================================
|
||||
|
||||
type HealthServiceImpl struct {
|
||||
UnimplementedHealthServiceServer
|
||||
}
|
||||
|
||||
func (s *HealthServiceImpl) HealthCheck(ctx context.Context, req *emptypb.Empty) (*HealthCheckResponse, error) {
|
||||
return &HealthCheckResponse{
|
||||
Status: "healthy",
|
||||
Version: "1.0.0",
|
||||
UptimeSeconds: 3600,
|
||||
ActiveTasks: 0,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Conversion Helpers
|
||||
// =============================================================================
|
||||
|
||||
func parseTaskStatus(status string) TaskStatus {
|
||||
switch status {
|
||||
case "received":
|
||||
return TaskStatus_TASK_STATUS_RECEIVED
|
||||
case "processing":
|
||||
return TaskStatus_TASK_STATUS_PROCESSING
|
||||
case "completed":
|
||||
return TaskStatus_TASK_STATUS_COMPLETED
|
||||
case "failed":
|
||||
return TaskStatus_TASK_STATUS_FAILED
|
||||
case "cancelled":
|
||||
return TaskStatus_TASK_STATUS_CANCELLED
|
||||
case "rejected":
|
||||
return TaskStatus_TASK_STATUS_REJECTED
|
||||
case "waiting":
|
||||
return TaskStatus_TASK_STATUS_WAITING
|
||||
default:
|
||||
return TaskStatus_TASK_STATUS_UNSPECIFIED
|
||||
}
|
||||
}
|
||||
|
||||
func convertTaskInfo(task *types.TaskInfo) *TaskInfo {
|
||||
if task == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var result *anypb.Any
|
||||
if task.Result != nil {
|
||||
result, _ = anypb.New(&anypb.Any{Value: []byte(fmt.Sprintf("%v", task.Result))})
|
||||
}
|
||||
|
||||
return &TaskInfo{
|
||||
Id: task.ID,
|
||||
Type: task.Type,
|
||||
Status: parseTaskStatus(task.Status),
|
||||
Progress: int32(task.Progress),
|
||||
Message: task.Message,
|
||||
CreatedAt: timestamppb.Now(),
|
||||
UpdatedAt: timestamppb.Now(),
|
||||
Result: result,
|
||||
}
|
||||
}
|
||||
|
||||
func convertAgentCapabilities(caps *types.AgentCapabilities) *AgentCapabilities {
|
||||
if caps == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var taskTypes []*SupportedTaskType
|
||||
for _, tt := range caps.SupportedTaskTypes {
|
||||
taskTypes = append(taskTypes, &SupportedTaskType{
|
||||
Type: tt.Type,
|
||||
Name: tt.Name,
|
||||
Description: tt.Description,
|
||||
EstimatedTime: tt.EstimatedTime,
|
||||
InputSchema: tt.InputSchema,
|
||||
OutputSchema: tt.OutputSchema,
|
||||
Capabilities: tt.Capabilities,
|
||||
})
|
||||
}
|
||||
|
||||
var transportModes []TransportMode
|
||||
for _, tm := range caps.SupportedTransportModes {
|
||||
transportModes = append(transportModes, TransportMode(TransportMode_value[string(tm)]))
|
||||
}
|
||||
|
||||
return &AgentCapabilities{
|
||||
AgentId: caps.AgentID,
|
||||
AgentName: caps.AgentName,
|
||||
SystemId: caps.SystemID,
|
||||
ProtocolVersion: caps.ProtocolVersion,
|
||||
SupportedTaskTypes: taskTypes,
|
||||
SupportedContentTypes: caps.SupportedContentTypes,
|
||||
SupportedTransportModes: transportModes,
|
||||
MaxFileSize: caps.MaxFileSize,
|
||||
MaxConcurrentTasks: int32(caps.MaxConcurrentTasks),
|
||||
MaxTaskDurationSeconds: int32(caps.MaxTaskDuration),
|
||||
SupportProgressUpdates: caps.SupportProgressUpdates,
|
||||
SupportStreaming: caps.SupportStreaming,
|
||||
SupportHil: caps.SupportHiL,
|
||||
SupportGroups: caps.SupportGroups,
|
||||
}
|
||||
}
|
||||
|
||||
func convertProtoToInternalMessage(msg *A2AMessage) *types.UnifiedSynapseMessage {
|
||||
if msg == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var payload []byte
|
||||
if msg.Payload != nil {
|
||||
payload = msg.Payload.Value
|
||||
}
|
||||
|
||||
return &types.UnifiedSynapseMessage{
|
||||
ID: msg.Id,
|
||||
Version: msg.Version,
|
||||
Type: string(MessageType_name[int32(msg.Type)]),
|
||||
Sender: types.AgentEndpoint{AgentID: msg.Sender.AgentId},
|
||||
CorrelationID: msg.CorrelationId,
|
||||
ReplyTo: msg.ReplyTo,
|
||||
GroupID: msg.GroupId,
|
||||
Timestamp: types.Timestamp(msg.Timestamp.AsTime().Format(time.RFC3339)),
|
||||
Payload: payload,
|
||||
Signature: msg.Signature,
|
||||
}
|
||||
}
|
||||
|
||||
func convertInternalToProtoMessage(msg *types.UnifiedSynapseMessage) *A2AMessage {
|
||||
if msg == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var payload *anypb.Any
|
||||
if len(msg.Payload) > 0 {
|
||||
payload = &anypb.Any{Value: msg.Payload}
|
||||
}
|
||||
|
||||
return &A2AMessage{
|
||||
Id: msg.ID,
|
||||
Version: msg.Version,
|
||||
Type: MessageType(MessageType_value[msg.Type]),
|
||||
Sender: &AgentEndpoint{AgentId: msg.Sender.AgentID},
|
||||
CorrelationId: msg.CorrelationID,
|
||||
ReplyTo: msg.ReplyTo,
|
||||
GroupId: msg.GroupID,
|
||||
Timestamp: timestamppb.Now(),
|
||||
Payload: payload,
|
||||
Signature: msg.Signature,
|
||||
}
|
||||
}
|
||||
|
||||
func convertProtoEndpoint(endpoint *AgentEndpoint) *types.AgentEndpoint {
|
||||
if endpoint == nil {
|
||||
return nil
|
||||
}
|
||||
return &types.AgentEndpoint{
|
||||
AgentID: endpoint.AgentId,
|
||||
AgentName: endpoint.AgentName,
|
||||
SystemID: endpoint.SystemId,
|
||||
Endpoint: endpoint.Endpoint,
|
||||
Version: endpoint.Version,
|
||||
}
|
||||
}
|
||||
850
internal/api/grpcapi/synapse.pb.go
Normal file
850
internal/api/grpcapi/synapse.pb.go
Normal file
@@ -0,0 +1,850 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// version: proto synapse v1.0.0
|
||||
// This file contains manually created stubs matching proto/synapse.proto
|
||||
|
||||
package grpcapi
|
||||
|
||||
import (
|
||||
fmt "fmt"
|
||||
proto "github.com/golang/protobuf/proto"
|
||||
anypb "google.golang.org/protobuf/types/known/anypb"
|
||||
timestamp "google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
// TransportMode represents the transport mode
|
||||
type TransportMode int32
|
||||
|
||||
const (
|
||||
TransportMode_TRANSPORT_MODE_UNSPECIFIED TransportMode = 0
|
||||
TransportMode_TRANSPORT_MODE_CALLBACK TransportMode = 1
|
||||
TransportMode_TRANSPORT_MODE_POLLING TransportMode = 2
|
||||
TransportMode_TRANSPORT_MODE_SYNC TransportMode = 3
|
||||
TransportMode_TRANSPORT_MODE_HYBRID TransportMode = 4
|
||||
)
|
||||
|
||||
var TransportMode_name = map[int32]string{
|
||||
0: "TRANSPORT_MODE_UNSPECIFIED",
|
||||
1: "TRANSPORT_MODE_CALLBACK",
|
||||
2: "TRANSPORT_MODE_POLLING",
|
||||
3: "TRANSPORT_MODE_SYNC",
|
||||
4: "TRANSPORT_MODE_HYBRID",
|
||||
}
|
||||
|
||||
var TransportMode_value = map[string]int32{
|
||||
"TRANSPORT_MODE_UNSPECIFIED": 0,
|
||||
"TRANSPORT_MODE_CALLBACK": 1,
|
||||
"TRANSPORT_MODE_POLLING": 2,
|
||||
"TRANSPORT_MODE_SYNC": 3,
|
||||
"TRANSPORT_MODE_HYBRID": 4,
|
||||
}
|
||||
|
||||
// MessageType represents the type of Synapse message
|
||||
type MessageType int32
|
||||
|
||||
const (
|
||||
MessageType_MESSAGE_TYPE_UNSPECIFIED MessageType = 0
|
||||
MessageType_MESSAGE_TYPE_P2P_TASK_REQUEST MessageType = 1
|
||||
MessageType_MESSAGE_TYPE_P2P_TASK_COMPLETE MessageType = 2
|
||||
MessageType_MESSAGE_TYPE_P2P_TASK_FAILED MessageType = 3
|
||||
MessageType_MESSAGE_TYPE_P2P_STATUS_UPDATE MessageType = 4
|
||||
MessageType_MESSAGE_TYPE_P2P_INFO_MISSING MessageType = 5
|
||||
MessageType_MESSAGE_TYPE_P2P_ACK MessageType = 6
|
||||
MessageType_MESSAGE_TYPE_P2P_NACK MessageType = 7
|
||||
MessageType_MESSAGE_TYPE_GROUP_INVITE MessageType = 8
|
||||
MessageType_MESSAGE_TYPE_GROUP_JOIN MessageType = 9
|
||||
MessageType_MESSAGE_TYPE_GROUP_LEAVE MessageType = 10
|
||||
MessageType_MESSAGE_TYPE_GROUP_TASK_SPLIT MessageType = 11
|
||||
MessageType_MESSAGE_TYPE_GROUP_SUBTASK_RESULT MessageType = 12
|
||||
MessageType_MESSAGE_TYPE_GROUP_RESULT_MERGE MessageType = 13
|
||||
MessageType_MESSAGE_TYPE_GROUP_VOTE_INITIATE MessageType = 14
|
||||
MessageType_MESSAGE_TYPE_GROUP_VOTE_SUBMIT MessageType = 15
|
||||
MessageType_MESSAGE_TYPE_GROUP_VOTE_RESULT MessageType = 16
|
||||
MessageType_MESSAGE_TYPE_HIL_DECISION_REQUEST MessageType = 17
|
||||
MessageType_MESSAGE_TYPE_HIL_DECISION_RESPONSE MessageType = 18
|
||||
MessageType_MESSAGE_TYPE_HEARTBEAT MessageType = 19
|
||||
)
|
||||
|
||||
var MessageType_name = map[int32]string{
|
||||
0: "MESSAGE_TYPE_UNSPECIFIED",
|
||||
1: "MESSAGE_TYPE_P2P_TASK_REQUEST",
|
||||
2: "MESSAGE_TYPE_P2P_TASK_COMPLETE",
|
||||
3: "MESSAGE_TYPE_P2P_TASK_FAILED",
|
||||
4: "MESSAGE_TYPE_P2P_STATUS_UPDATE",
|
||||
5: "MESSAGE_TYPE_P2P_INFO_MISSING",
|
||||
6: "MESSAGE_TYPE_P2P_ACK",
|
||||
7: "MESSAGE_TYPE_P2P_NACK",
|
||||
8: "MESSAGE_TYPE_GROUP_INVITE",
|
||||
9: "MESSAGE_TYPE_GROUP_JOIN",
|
||||
10: "MESSAGE_TYPE_GROUP_LEAVE",
|
||||
11: "MESSAGE_TYPE_GROUP_TASK_SPLIT",
|
||||
12: "MESSAGE_TYPE_GROUP_SUBTASK_RESULT",
|
||||
13: "MESSAGE_TYPE_GROUP_RESULT_MERGE",
|
||||
14: "MESSAGE_TYPE_GROUP_VOTE_INITIATE",
|
||||
15: "MESSAGE_TYPE_GROUP_VOTE_SUBMIT",
|
||||
16: "MESSAGE_TYPE_GROUP_VOTE_RESULT",
|
||||
17: "MESSAGE_TYPE_HIL_DECISION_REQUEST",
|
||||
18: "MESSAGE_TYPE_HIL_DECISION_RESPONSE",
|
||||
19: "MESSAGE_TYPE_HEARTBEAT",
|
||||
}
|
||||
|
||||
var MessageType_value = map[string]int32{
|
||||
"MESSAGE_TYPE_UNSPECIFIED": 0,
|
||||
"MESSAGE_TYPE_P2P_TASK_REQUEST": 1,
|
||||
"MESSAGE_TYPE_P2P_TASK_COMPLETE": 2,
|
||||
"MESSAGE_TYPE_P2P_TASK_FAILED": 3,
|
||||
"MESSAGE_TYPE_P2P_STATUS_UPDATE": 4,
|
||||
"MESSAGE_TYPE_P2P_INFO_MISSING": 5,
|
||||
"MESSAGE_TYPE_P2P_ACK": 6,
|
||||
"MESSAGE_TYPE_P2P_NACK": 7,
|
||||
"MESSAGE_TYPE_GROUP_INVITE": 8,
|
||||
"MESSAGE_TYPE_GROUP_JOIN": 9,
|
||||
"MESSAGE_TYPE_GROUP_LEAVE": 10,
|
||||
"MESSAGE_TYPE_GROUP_TASK_SPLIT": 11,
|
||||
"MESSAGE_TYPE_GROUP_SUBTASK_RESULT": 12,
|
||||
"MESSAGE_TYPE_GROUP_RESULT_MERGE": 13,
|
||||
"MESSAGE_TYPE_GROUP_VOTE_INITIATE": 14,
|
||||
"MESSAGE_TYPE_GROUP_VOTE_SUBMIT": 15,
|
||||
"MESSAGE_TYPE_GROUP_VOTE_RESULT": 16,
|
||||
"MESSAGE_TYPE_HIL_DECISION_REQUEST": 17,
|
||||
"MESSAGE_TYPE_HIL_DECISION_RESPONSE": 18,
|
||||
"MESSAGE_TYPE_HEARTBEAT": 19,
|
||||
}
|
||||
|
||||
// TaskStatus represents the status of a task
|
||||
type TaskStatus int32
|
||||
|
||||
const (
|
||||
TaskStatus_TASK_STATUS_UNSPECIFIED TaskStatus = 0
|
||||
TaskStatus_TASK_STATUS_RECEIVED TaskStatus = 1
|
||||
TaskStatus_TASK_STATUS_PROCESSING TaskStatus = 2
|
||||
TaskStatus_TASK_STATUS_COMPLETED TaskStatus = 3
|
||||
TaskStatus_TASK_STATUS_FAILED TaskStatus = 4
|
||||
TaskStatus_TASK_STATUS_CANCELLED TaskStatus = 5
|
||||
TaskStatus_TASK_STATUS_REJECTED TaskStatus = 6
|
||||
TaskStatus_TASK_STATUS_WAITING TaskStatus = 7
|
||||
)
|
||||
|
||||
var TaskStatus_name = map[int32]string{
|
||||
0: "TASK_STATUS_UNSPECIFIED",
|
||||
1: "TASK_STATUS_RECEIVED",
|
||||
2: "TASK_STATUS_PROCESSING",
|
||||
3: "TASK_STATUS_COMPLETED",
|
||||
4: "TASK_STATUS_FAILED",
|
||||
5: "TASK_STATUS_CANCELLED",
|
||||
6: "TASK_STATUS_REJECTED",
|
||||
7: "TASK_STATUS_WAITING",
|
||||
}
|
||||
|
||||
var TaskStatus_value = map[string]int32{
|
||||
"TASK_STATUS_UNSPECIFIED": 0,
|
||||
"TASK_STATUS_RECEIVED": 1,
|
||||
"TASK_STATUS_PROCESSING": 2,
|
||||
"TASK_STATUS_COMPLETED": 3,
|
||||
"TASK_STATUS_FAILED": 4,
|
||||
"TASK_STATUS_CANCELLED": 5,
|
||||
"TASK_STATUS_REJECTED": 6,
|
||||
"TASK_STATUS_WAITING": 7,
|
||||
}
|
||||
|
||||
func (x TransportMode) String() string { return fmt.Sprintf("%v", x) }
|
||||
func (x MessageType) String() string { return fmt.Sprintf("%v", x) }
|
||||
func (x TaskStatus) String() string { return fmt.Sprintf("%v", x) }
|
||||
|
||||
func init() {
|
||||
proto.RegisterEnum("a2a.TransportMode", TransportMode_name, TransportMode_value)
|
||||
proto.RegisterEnum("a2a.MessageType", MessageType_name, MessageType_value)
|
||||
proto.RegisterEnum("a2a.TaskStatus", TaskStatus_name, TaskStatus_value)
|
||||
}
|
||||
|
||||
// AgentEndpoint represents an agent's endpoint
|
||||
type AgentEndpoint struct {
|
||||
AgentId string `protobuf:"bytes,1,opt,name=agent_id,json=agentId" json:"agent_id,omitempty"`
|
||||
AgentName string `protobuf:"bytes,2,opt,name=agent_name,json=agentName" json:"agent_name,omitempty"`
|
||||
SystemId string `protobuf:"bytes,3,opt,name=system_id,json=systemId" json:"system_id,omitempty"`
|
||||
Endpoint string `protobuf:"bytes,4,opt,name=endpoint" json:"endpoint,omitempty"`
|
||||
Version string `protobuf:"bytes,5,opt,name=version" json:"version,omitempty"`
|
||||
}
|
||||
|
||||
func (m *AgentEndpoint) Reset() { *m = AgentEndpoint{} }
|
||||
func (m *AgentEndpoint) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*AgentEndpoint) ProtoMessage() {}
|
||||
|
||||
func (m *AgentEndpoint) GetAgentId() string {
|
||||
if m != nil {
|
||||
return m.AgentId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// A2AMessage represents a complete Synapse message
|
||||
type A2AMessage struct {
|
||||
Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
|
||||
Version string `protobuf:"bytes,2,opt,name=version" json:"version,omitempty"`
|
||||
Type MessageType `protobuf:"varint,3,opt,name=type,enum=a2a.MessageType" json:"type,omitempty"`
|
||||
Sender *AgentEndpoint `protobuf:"bytes,4,opt,name=sender" json:"sender,omitempty"`
|
||||
Receiver *AgentEndpoint `protobuf:"bytes,5,opt,name=receiver" json:"receiver,omitempty"`
|
||||
CorrelationId string `protobuf:"bytes,6,opt,name=correlation_id,json=correlationId" json:"correlation_id,omitempty"`
|
||||
ReplyTo string `protobuf:"bytes,7,opt,name=reply_to,json=replyTo" json:"reply_to,omitempty"`
|
||||
GroupId string `protobuf:"bytes,8,opt,name=group_id,json=groupId" json:"group_id,omitempty"`
|
||||
Timestamp *timestamp.Timestamp `protobuf:"bytes,9,opt,name=timestamp" json:"timestamp,omitempty"`
|
||||
Payload *anypb.Any `protobuf:"bytes,10,opt,name=payload" json:"payload,omitempty"`
|
||||
Signature string `protobuf:"bytes,11,opt,name=signature" json:"signature,omitempty"`
|
||||
}
|
||||
|
||||
func (m *A2AMessage) Reset() { *m = A2AMessage{} }
|
||||
func (m *A2AMessage) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*A2AMessage) ProtoMessage() {}
|
||||
|
||||
// TaskPayload represents task submission payload
|
||||
type TaskPayload struct {
|
||||
TaskId string `protobuf:"bytes,1,opt,name=task_id,json=taskId" json:"task_id,omitempty"`
|
||||
TaskType string `protobuf:"bytes,2,opt,name=task_type,json=taskType" json:"task_type,omitempty"`
|
||||
Payload *anypb.Any `protobuf:"bytes,3,opt,name=payload" json:"payload,omitempty"`
|
||||
ExternalTaskId string `protobuf:"bytes,4,opt,name=external_task_id,json=externalTaskId" json:"external_task_id,omitempty"`
|
||||
}
|
||||
|
||||
func (m *TaskPayload) Reset() { *m = TaskPayload{} }
|
||||
func (m *TaskPayload) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*TaskPayload) ProtoMessage() {}
|
||||
|
||||
// TaskResult represents task result
|
||||
type TaskResult struct {
|
||||
TaskId string `protobuf:"bytes,1,opt,name=task_id,json=taskId" json:"task_id,omitempty"`
|
||||
Type string `protobuf:"bytes,2,opt,name=type" json:"type,omitempty"`
|
||||
Result *anypb.Any `protobuf:"bytes,3,opt,name=result" json:"result,omitempty"`
|
||||
Summary string `protobuf:"bytes,4,opt,name=summary" json:"summary,omitempty"`
|
||||
}
|
||||
|
||||
func (m *TaskResult) Reset() { *m = TaskResult{} }
|
||||
func (m *TaskResult) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*TaskResult) ProtoMessage() {}
|
||||
|
||||
// TaskStatusUpdate represents task status update
|
||||
type TaskStatusUpdate struct {
|
||||
TaskId string `protobuf:"bytes,1,opt,name=task_id,json=taskId" json:"task_id,omitempty"`
|
||||
Status TaskStatus `protobuf:"varint,2,opt,name=status,enum=a2a.TaskStatus" json:"status,omitempty"`
|
||||
Progress int32 `protobuf:"varint,3,opt,name=progress" json:"progress,omitempty"`
|
||||
Message string `protobuf:"bytes,4,opt,name=message" json:"message,omitempty"`
|
||||
Details *anypb.Any `protobuf:"bytes,5,opt,name=details" json:"details,omitempty"`
|
||||
}
|
||||
|
||||
func (m *TaskStatusUpdate) Reset() { *m = TaskStatusUpdate{} }
|
||||
func (m *TaskStatusUpdate) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*TaskStatusUpdate) ProtoMessage() {}
|
||||
|
||||
// =============================================================================
|
||||
// Task Service Messages
|
||||
// =============================================================================
|
||||
|
||||
// SubmitTaskRequest is the request for submitting a task
|
||||
type SubmitTaskRequest struct {
|
||||
TaskType string `protobuf:"bytes,1,opt,name=task_type,json=taskType" json:"task_type,omitempty"`
|
||||
Payload *anypb.Any `protobuf:"bytes,2,opt,name=payload" json:"payload,omitempty"`
|
||||
ExternalTaskId string `protobuf:"bytes,3,opt,name=external_task_id,json=externalTaskId" json:"external_task_id,omitempty"`
|
||||
Priority string `protobuf:"bytes,4,opt,name=priority" json:"priority,omitempty"`
|
||||
CallbackUrl string `protobuf:"bytes,5,opt,name=callback_url,json=callbackUrl" json:"callback_url,omitempty"`
|
||||
CallbackToken string `protobuf:"bytes,6,opt,name=callback_token,json=callbackToken" json:"callback_token,omitempty"`
|
||||
PreferredTransport TransportMode `protobuf:"varint,7,opt,name=preferred_transport,json=preferredTransport" json:"preferred_transport,omitempty"`
|
||||
}
|
||||
|
||||
func (m *SubmitTaskRequest) Reset() { *m = SubmitTaskRequest{} }
|
||||
func (m *SubmitTaskRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*SubmitTaskRequest) ProtoMessage() {}
|
||||
|
||||
func (m *SubmitTaskRequest) GetTaskType() string {
|
||||
if m != nil {
|
||||
return m.TaskType
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// SubmitTaskResponse is the response for task submission
|
||||
type SubmitTaskResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
TaskId string `protobuf:"bytes,2,opt,name=task_id,json=taskId" json:"task_id,omitempty"`
|
||||
Status TaskStatus `protobuf:"varint,3,opt,name=status,enum=a2a.TaskStatus" json:"status,omitempty"`
|
||||
Message string `protobuf:"bytes,4,opt,name=message" json:"message,omitempty"`
|
||||
ErrorCode string `protobuf:"bytes,5,opt,name=error_code,json=errorCode" json:"error_code,omitempty"`
|
||||
}
|
||||
|
||||
func (m *SubmitTaskResponse) Reset() { *m = SubmitTaskResponse{} }
|
||||
func (m *SubmitTaskResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*SubmitTaskResponse) ProtoMessage() {}
|
||||
|
||||
// SubmitTaskWithFilesRequest is the request for submitting a task with files
|
||||
type SubmitTaskWithFilesRequest struct {
|
||||
Request *SubmitTaskRequest `protobuf:"bytes,1,opt,name=request" json:"request,omitempty"`
|
||||
Files []*FileUpload `protobuf:"bytes,2,rep,name=files" json:"files,omitempty"`
|
||||
}
|
||||
|
||||
func (m *SubmitTaskWithFilesRequest) Reset() { *m = SubmitTaskWithFilesRequest{} }
|
||||
func (m *SubmitTaskWithFilesRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*SubmitTaskWithFilesRequest) ProtoMessage() {}
|
||||
|
||||
// FileUpload represents an uploaded file
|
||||
type FileUpload struct {
|
||||
FieldName string `protobuf:"bytes,1,opt,name=field_name,json=fieldName" json:"field_name,omitempty"`
|
||||
Filename string `protobuf:"bytes,2,opt,name=filename" json:"filename,omitempty"`
|
||||
MimeType string `protobuf:"bytes,3,opt,name=mime_type,json=mimeType" json:"mime_type,omitempty"`
|
||||
Data []byte `protobuf:"bytes,4,opt,name=data" json:"data,omitempty"`
|
||||
}
|
||||
|
||||
func (m *FileUpload) Reset() { *m = FileUpload{} }
|
||||
func (m *FileUpload) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*FileUpload) ProtoMessage() {}
|
||||
|
||||
// GetTaskRequest is the request for getting task details
|
||||
type GetTaskRequest struct {
|
||||
TaskId string `protobuf:"bytes,1,opt,name=task_id,json=taskId" json:"task_id,omitempty"`
|
||||
}
|
||||
|
||||
func (m *GetTaskRequest) Reset() { *m = GetTaskRequest{} }
|
||||
func (m *GetTaskRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*GetTaskRequest) ProtoMessage() {}
|
||||
|
||||
// TaskStatusResponse is the response for task status query
|
||||
type TaskStatusResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
Task *TaskInfo `protobuf:"bytes,2,opt,name=task" json:"task,omitempty"`
|
||||
ErrorCode string `protobuf:"bytes,3,opt,name=error_code,json=errorCode" json:"error_code,omitempty"`
|
||||
ErrorMessage string `protobuf:"bytes,4,opt,name=error_message,json=errorMessage" json:"error_message,omitempty"`
|
||||
}
|
||||
|
||||
func (m *TaskStatusResponse) Reset() { *m = TaskStatusResponse{} }
|
||||
func (m *TaskStatusResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*TaskStatusResponse) ProtoMessage() {}
|
||||
|
||||
// TaskInfo represents task information
|
||||
type TaskInfo struct {
|
||||
Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
|
||||
Type string `protobuf:"bytes,2,opt,name=type" json:"type,omitempty"`
|
||||
Status TaskStatus `protobuf:"varint,3,opt,name=status,enum=a2a.TaskStatus" json:"status,omitempty"`
|
||||
Progress int32 `protobuf:"varint,4,opt,name=progress" json:"progress,omitempty"`
|
||||
Message string `protobuf:"bytes,5,opt,name=message" json:"message,omitempty"`
|
||||
CreatedAt *timestamp.Timestamp `protobuf:"bytes,6,opt,name=created_at,json=createdAt" json:"created_at,omitempty"`
|
||||
UpdatedAt *timestamp.Timestamp `protobuf:"bytes,7,opt,name=updated_at,json=updatedAt" json:"updated_at,omitempty"`
|
||||
CompletedAt *timestamp.Timestamp `protobuf:"bytes,8,opt,name=completed_at,json=completedAt" json:"completed_at,omitempty"`
|
||||
ETA *timestamp.Timestamp `protobuf:"bytes,9,opt,name=e_t_a,json=eta" json:"eta,omitempty"`
|
||||
Result *anypb.Any `protobuf:"bytes,10,opt,name=result" json:"result,omitempty"`
|
||||
Error *TaskError `protobuf:"bytes,11,opt,name=error" json:"error,omitempty"`
|
||||
ExternalTaskId string `protobuf:"bytes,12,opt,name=external_task_id,json=externalTaskId" json:"external_task_id,omitempty"`
|
||||
}
|
||||
|
||||
func (m *TaskInfo) Reset() { *m = TaskInfo{} }
|
||||
func (m *TaskInfo) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*TaskInfo) ProtoMessage() {}
|
||||
|
||||
// TaskError represents a task error
|
||||
type TaskError struct {
|
||||
Code string `protobuf:"bytes,1,opt,name=code" json:"code,omitempty"`
|
||||
Message string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"`
|
||||
}
|
||||
|
||||
func (m *TaskError) Reset() { *m = TaskError{} }
|
||||
func (m *TaskError) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*TaskError) ProtoMessage() {}
|
||||
|
||||
// ListTasksRequest is the request for listing tasks
|
||||
type ListTasksRequest struct {
|
||||
Status string `protobuf:"bytes,1,opt,name=status" json:"status,omitempty"`
|
||||
Limit int32 `protobuf:"varint,2,opt,name=limit" json:"limit,omitempty"`
|
||||
Offset int32 `protobuf:"varint,3,opt,name=offset" json:"offset,omitempty"`
|
||||
}
|
||||
|
||||
func (m *ListTasksRequest) Reset() { *m = ListTasksRequest{} }
|
||||
func (m *ListTasksRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*ListTasksRequest) ProtoMessage() {}
|
||||
|
||||
// ListTasksResponse is the response for listing tasks
|
||||
type ListTasksResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
Tasks []*TaskInfo `protobuf:"bytes,2,rep,name=tasks" json:"tasks,omitempty"`
|
||||
Total int32 `protobuf:"varint,3,opt,name=total" json:"total,omitempty"`
|
||||
Limit int32 `protobuf:"varint,4,opt,name=limit" json:"limit,omitempty"`
|
||||
Offset int32 `protobuf:"varint,5,opt,name=offset" json:"offset,omitempty"`
|
||||
HasMore bool `protobuf:"varint,6,opt,name=has_more,json=hasMore" json:"has_more,omitempty"`
|
||||
}
|
||||
|
||||
func (m *ListTasksResponse) Reset() { *m = ListTasksResponse{} }
|
||||
func (m *ListTasksResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*ListTasksResponse) ProtoMessage() {}
|
||||
|
||||
// CancelTaskRequest is the request for cancelling a task
|
||||
type CancelTaskRequest struct {
|
||||
TaskId string `protobuf:"bytes,1,opt,name=task_id,json=taskId" json:"task_id,omitempty"`
|
||||
}
|
||||
|
||||
func (m *CancelTaskRequest) Reset() { *m = CancelTaskRequest{} }
|
||||
func (m *CancelTaskRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*CancelTaskRequest) ProtoMessage() {}
|
||||
|
||||
// CancelTaskResponse is the response for cancelling a task
|
||||
type CancelTaskResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
TaskId string `protobuf:"bytes,2,opt,name=task_id,json=taskId" json:"task_id,omitempty"`
|
||||
Status TaskStatus `protobuf:"varint,3,opt,name=status,enum=a2a.TaskStatus" json:"status,omitempty"`
|
||||
Message string `protobuf:"bytes,4,opt,name=message" json:"message,omitempty"`
|
||||
}
|
||||
|
||||
func (m *CancelTaskResponse) Reset() { *m = CancelTaskResponse{} }
|
||||
func (m *CancelTaskResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*CancelTaskResponse) ProtoMessage() {}
|
||||
|
||||
// TaskStatusStreamRequest is the request for streaming task status
|
||||
type TaskStatusStreamRequest struct {
|
||||
TaskId string `protobuf:"bytes,1,opt,name=task_id,json=taskId" json:"task_id,omitempty"`
|
||||
Subscribe bool `protobuf:"varint,2,opt,name=subscribe" json:"subscribe,omitempty"`
|
||||
}
|
||||
|
||||
func (m *TaskStatusStreamRequest) Reset() { *m = TaskStatusStreamRequest{} }
|
||||
func (m *TaskStatusStreamRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*TaskStatusStreamRequest) ProtoMessage() {}
|
||||
|
||||
// =============================================================================
|
||||
// Synapse Message Service Messages
|
||||
// =============================================================================
|
||||
|
||||
// SendMessageRequest is the request for sending an Synapse message
|
||||
type SendMessageRequest struct {
|
||||
Message *A2AMessage `protobuf:"bytes,1,opt,name=message" json:"message,omitempty"`
|
||||
}
|
||||
|
||||
func (m *SendMessageRequest) Reset() { *m = SendMessageRequest{} }
|
||||
func (m *SendMessageRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*SendMessageRequest) ProtoMessage() {}
|
||||
|
||||
// SendMessageResponse is the response for sending an Synapse message
|
||||
type SendMessageResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
MessageId string `protobuf:"bytes,2,opt,name=message_id,json=messageId" json:"message_id,omitempty"`
|
||||
Error string `protobuf:"bytes,3,opt,name=error" json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (m *SendMessageResponse) Reset() { *m = SendMessageResponse{} }
|
||||
func (m *SendMessageResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*SendMessageResponse) ProtoMessage() {}
|
||||
|
||||
// =============================================================================
|
||||
// Capabilities Service Messages
|
||||
// =============================================================================
|
||||
|
||||
// CapabilitiesResponse is the response for capabilities query
|
||||
type CapabilitiesResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
Capabilities *AgentCapabilities `protobuf:"bytes,2,opt,name=capabilities" json:"capabilities,omitempty"`
|
||||
Error string `protobuf:"bytes,3,opt,name=error" json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (m *CapabilitiesResponse) Reset() { *m = CapabilitiesResponse{} }
|
||||
func (m *CapabilitiesResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*CapabilitiesResponse) ProtoMessage() {}
|
||||
|
||||
// AgentCapabilities represents agent capabilities
|
||||
type AgentCapabilities struct {
|
||||
AgentId string `protobuf:"bytes,1,opt,name=agent_id,json=agentId" json:"agent_id,omitempty"`
|
||||
AgentName string `protobuf:"bytes,2,opt,name=agent_name,json=agentName" json:"agent_name,omitempty"`
|
||||
SystemId string `protobuf:"bytes,3,opt,name=system_id,json=systemId" json:"system_id,omitempty"`
|
||||
ProtocolVersion string `protobuf:"bytes,4,opt,name=protocol_version,json=protocolVersion" json:"protocol_version,omitempty"`
|
||||
SupportedTaskTypes []*SupportedTaskType `protobuf:"bytes,5,rep,name=supported_task_types,json=supportedTaskTypes" json:"supported_task_types,omitempty"`
|
||||
SupportedContentTypes []string `protobuf:"bytes,6,rep,name=supported_content_types,json=supportedContentTypes" json:"supported_content_types,omitempty"`
|
||||
SupportedTransportModes []TransportMode `protobuf:"varint,7,rep,name=supported_transport_modes,json=supportedTransportModes" json:"supported_transport_modes,omitempty"`
|
||||
MaxFileSize int64 `protobuf:"varint,8,opt,name=max_file_size,json=maxFileSize" json:"max_file_size,omitempty"`
|
||||
MaxConcurrentTasks int32 `protobuf:"varint,9,opt,name=max_concurrent_tasks,json=maxConcurrentTasks" json:"max_concurrent_tasks,omitempty"`
|
||||
MaxTaskDurationSeconds int32 `protobuf:"varint,10,opt,name=max_task_duration_seconds,json=maxTaskDurationSeconds" json:"max_task_duration_seconds,omitempty"`
|
||||
SupportProgressUpdates bool `protobuf:"varint,11,opt,name=support_progress_updates,json=supportProgressUpdates" json:"support_progress_updates,omitempty"`
|
||||
SupportStreaming bool `protobuf:"varint,12,opt,name=support_streaming,json=supportStreaming" json:"support_streaming,omitempty"`
|
||||
SupportHil bool `protobuf:"varint,13,opt,name=support_hil,json=supportHil" json:"support_hil,omitempty"`
|
||||
SupportGroups bool `protobuf:"varint,14,opt,name=support_groups,json=supportGroups" json:"support_groups,omitempty"`
|
||||
}
|
||||
|
||||
func (m *AgentCapabilities) Reset() { *m = AgentCapabilities{} }
|
||||
func (m *AgentCapabilities) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*AgentCapabilities) ProtoMessage() {}
|
||||
|
||||
// SupportedTaskType represents a supported task type
|
||||
type SupportedTaskType struct {
|
||||
Type string `protobuf:"bytes,1,opt,name=type" json:"type,omitempty"`
|
||||
Name string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"`
|
||||
Description string `protobuf:"bytes,3,opt,name=description" json:"description,omitempty"`
|
||||
EstimatedTime string `protobuf:"bytes,4,opt,name=estimated_time,json=estimatedTime" json:"estimated_time,omitempty"`
|
||||
InputSchema string `protobuf:"bytes,5,opt,name=input_schema,json=inputSchema" json:"input_schema,omitempty"`
|
||||
OutputSchema string `protobuf:"bytes,6,opt,name=output_schema,json=outputSchema" json:"output_schema,omitempty"`
|
||||
Capabilities []string `protobuf:"bytes,7,rep,name=capabilities" json:"capabilities,omitempty"`
|
||||
}
|
||||
|
||||
func (m *SupportedTaskType) Reset() { *m = SupportedTaskType{} }
|
||||
func (m *SupportedTaskType) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*SupportedTaskType) ProtoMessage() {}
|
||||
|
||||
// QueryAgentRequest is the request for querying an agent
|
||||
type QueryAgentRequest struct {
|
||||
AgentId string `protobuf:"bytes,1,opt,name=agent_id,json=agentId" json:"agent_id,omitempty"`
|
||||
}
|
||||
|
||||
func (m *QueryAgentRequest) Reset() { *m = QueryAgentRequest{} }
|
||||
func (m *QueryAgentRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*QueryAgentRequest) ProtoMessage() {}
|
||||
|
||||
// ListAgentsResponse is the response for listing agents
|
||||
type ListAgentsResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
Agents []*AgentInfo `protobuf:"bytes,2,rep,name=agents" json:"agents,omitempty"`
|
||||
Total int32 `protobuf:"varint,3,opt,name=total" json:"total,omitempty"`
|
||||
}
|
||||
|
||||
func (m *ListAgentsResponse) Reset() { *m = ListAgentsResponse{} }
|
||||
func (m *ListAgentsResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*ListAgentsResponse) ProtoMessage() {}
|
||||
|
||||
// AgentInfo represents agent information
|
||||
type AgentInfo struct {
|
||||
Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
|
||||
AgentId string `protobuf:"bytes,2,opt,name=agent_id,json=agentId" json:"agent_id,omitempty"`
|
||||
AgentName string `protobuf:"bytes,3,opt,name=agent_name,json=agentName" json:"agent_name,omitempty"`
|
||||
SystemId string `protobuf:"bytes,4,opt,name=system_id,json=systemId" json:"system_id,omitempty"`
|
||||
Endpoint string `protobuf:"bytes,5,opt,name=endpoint" json:"endpoint,omitempty"`
|
||||
IsActive bool `protobuf:"varint,6,opt,name=is_active,json=isActive" json:"is_active,omitempty"`
|
||||
TrustLevel int32 `protobuf:"varint,7,opt,name=trust_level,json=trustLevel" json:"trust_level,omitempty"`
|
||||
}
|
||||
|
||||
func (m *AgentInfo) Reset() { *m = AgentInfo{} }
|
||||
func (m *AgentInfo) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*AgentInfo) ProtoMessage() {}
|
||||
|
||||
// =============================================================================
|
||||
// Group Service Messages
|
||||
// =============================================================================
|
||||
|
||||
// CreateGroupRequest is the request for creating a group
|
||||
type CreateGroupRequest struct {
|
||||
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
|
||||
Description string `protobuf:"bytes,2,opt,name=description" json:"description,omitempty"`
|
||||
CoordinatorId string `protobuf:"bytes,3,opt,name=coordinator_id,json=coordinatorId" json:"coordinator_id,omitempty"`
|
||||
InitialMembers []string `protobuf:"bytes,4,rep,name=initial_members,json=initialMembers" json:"initial_members,omitempty"`
|
||||
}
|
||||
|
||||
func (m *CreateGroupRequest) Reset() { *m = CreateGroupRequest{} }
|
||||
func (m *CreateGroupRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*CreateGroupRequest) ProtoMessage() {}
|
||||
|
||||
// CreateGroupResponse is the response for creating a group
|
||||
type CreateGroupResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
GroupId string `protobuf:"bytes,2,opt,name=group_id,json=groupId" json:"group_id,omitempty"`
|
||||
Group *GroupInfo `protobuf:"bytes,3,opt,name=group" json:"group,omitempty"`
|
||||
Error string `protobuf:"bytes,4,opt,name=error" json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (m *CreateGroupResponse) Reset() { *m = CreateGroupResponse{} }
|
||||
func (m *CreateGroupResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*CreateGroupResponse) ProtoMessage() {}
|
||||
|
||||
// GroupInfo represents group information
|
||||
type GroupInfo struct {
|
||||
Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
|
||||
Name string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"`
|
||||
Description string `protobuf:"bytes,3,opt,name=description" json:"description,omitempty"`
|
||||
CoordinatorId string `protobuf:"bytes,4,opt,name=coordinator_id,json=coordinatorId" json:"coordinator_id,omitempty"`
|
||||
Status string `protobuf:"bytes,5,opt,name=status" json:"status,omitempty"`
|
||||
CreatedAt *timestamp.Timestamp `protobuf:"bytes,6,opt,name=created_at,json=createdAt" json:"created_at,omitempty"`
|
||||
}
|
||||
|
||||
func (m *GroupInfo) Reset() { *m = GroupInfo{} }
|
||||
func (m *GroupInfo) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*GroupInfo) ProtoMessage() {}
|
||||
|
||||
// JoinGroupRequest is the request for joining a group
|
||||
type JoinGroupRequest struct {
|
||||
GroupId string `protobuf:"bytes,1,opt,name=group_id,json=groupId" json:"group_id,omitempty"`
|
||||
Agent *AgentEndpoint `protobuf:"bytes,2,opt,name=agent" json:"agent,omitempty"`
|
||||
}
|
||||
|
||||
func (m *JoinGroupRequest) Reset() { *m = JoinGroupRequest{} }
|
||||
func (m *JoinGroupRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*JoinGroupRequest) ProtoMessage() {}
|
||||
|
||||
// JoinGroupResponse is the response for joining a group
|
||||
type JoinGroupResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
Error string `protobuf:"bytes,2,opt,name=error" json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (m *JoinGroupResponse) Reset() { *m = JoinGroupResponse{} }
|
||||
func (m *JoinGroupResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*JoinGroupResponse) ProtoMessage() {}
|
||||
|
||||
// LeaveGroupRequest is the request for leaving a group
|
||||
type LeaveGroupRequest struct {
|
||||
GroupId string `protobuf:"bytes,1,opt,name=group_id,json=groupId" json:"group_id,omitempty"`
|
||||
AgentId string `protobuf:"bytes,2,opt,name=agent_id,json=agentId" json:"agent_id,omitempty"`
|
||||
}
|
||||
|
||||
func (m *LeaveGroupRequest) Reset() { *m = LeaveGroupRequest{} }
|
||||
func (m *LeaveGroupRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*LeaveGroupRequest) ProtoMessage() {}
|
||||
|
||||
// LeaveGroupResponse is the response for leaving a group
|
||||
type LeaveGroupResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
Error string `protobuf:"bytes,2,opt,name=error" json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (m *LeaveGroupResponse) Reset() { *m = LeaveGroupResponse{} }
|
||||
func (m *LeaveGroupResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*LeaveGroupResponse) ProtoMessage() {}
|
||||
|
||||
// DisbandGroupRequest is the request for disbanding a group
|
||||
type DisbandGroupRequest struct {
|
||||
GroupId string `protobuf:"bytes,1,opt,name=group_id,json=groupId" json:"group_id,omitempty"`
|
||||
}
|
||||
|
||||
func (m *DisbandGroupRequest) Reset() { *m = DisbandGroupRequest{} }
|
||||
func (m *DisbandGroupRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*DisbandGroupRequest) ProtoMessage() {}
|
||||
|
||||
// DisbandGroupResponse is the response for disbanding a group
|
||||
type DisbandGroupResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
Error string `protobuf:"bytes,2,opt,name=error" json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (m *DisbandGroupResponse) Reset() { *m = DisbandGroupResponse{} }
|
||||
func (m *DisbandGroupResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*DisbandGroupResponse) ProtoMessage() {}
|
||||
|
||||
// ListGroupMembersRequest is the request for listing group members
|
||||
type ListGroupMembersRequest struct {
|
||||
GroupId string `protobuf:"bytes,1,opt,name=group_id,json=groupId" json:"group_id,omitempty"`
|
||||
}
|
||||
|
||||
func (m *ListGroupMembersRequest) Reset() { *m = ListGroupMembersRequest{} }
|
||||
func (m *ListGroupMembersRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*ListGroupMembersRequest) ProtoMessage() {}
|
||||
|
||||
// ListGroupMembersResponse is the response for listing group members
|
||||
type ListGroupMembersResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
Members []*GroupMember `protobuf:"bytes,2,rep,name=members" json:"members,omitempty"`
|
||||
}
|
||||
|
||||
func (m *ListGroupMembersResponse) Reset() { *m = ListGroupMembersResponse{} }
|
||||
func (m *ListGroupMembersResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*ListGroupMembersResponse) ProtoMessage() {}
|
||||
|
||||
// GroupMember represents a group member
|
||||
type GroupMember struct {
|
||||
AgentId string `protobuf:"bytes,1,opt,name=agent_id,json=agentId" json:"agent_id,omitempty"`
|
||||
AgentName string `protobuf:"bytes,2,opt,name=agent_name,json=agentName" json:"agent_name,omitempty"`
|
||||
Role string `protobuf:"bytes,3,opt,name=role" json:"role,omitempty"`
|
||||
Status string `protobuf:"bytes,4,opt,name=status" json:"status,omitempty"`
|
||||
JoinedAt *timestamp.Timestamp `protobuf:"bytes,5,opt,name=joined_at,json=joinedAt" json:"joined_at,omitempty"`
|
||||
}
|
||||
|
||||
func (m *GroupMember) Reset() { *m = GroupMember{} }
|
||||
func (m *GroupMember) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*GroupMember) ProtoMessage() {}
|
||||
|
||||
// =============================================================================
|
||||
// Group Voting Messages (NEW!)
|
||||
// =============================================================================
|
||||
|
||||
// VoteRequest is the request for initiating a vote
|
||||
type VoteRequest struct {
|
||||
GroupId string `protobuf:"bytes,1,opt,name=group_id,json=groupId" json:"group_id,omitempty"`
|
||||
InitiatorId string `protobuf:"bytes,2,opt,name=initiator_id,json=initiatorId" json:"initiator_id,omitempty"`
|
||||
Question string `protobuf:"bytes,3,opt,name=question" json:"question,omitempty"`
|
||||
Options []string `protobuf:"bytes,4,rep,name=options" json:"options,omitempty"`
|
||||
Threshold float64 `protobuf:"fixed64,5,opt,name=threshold" json:"threshold,omitempty"`
|
||||
TimeoutSeconds int32 `protobuf:"varint,6,opt,name=timeout_seconds,json=timeoutSeconds" json:"timeout_seconds,omitempty"`
|
||||
}
|
||||
|
||||
func (m *VoteRequest) Reset() { *m = VoteRequest{} }
|
||||
func (m *VoteRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*VoteRequest) ProtoMessage() {}
|
||||
|
||||
// VoteResponse is the response for initiating a vote
|
||||
type VoteResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
VoteId string `protobuf:"bytes,2,opt,name=vote_id,json=voteId" json:"vote_id,omitempty"`
|
||||
Error string `protobuf:"bytes,3,opt,name=error" json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (m *VoteResponse) Reset() { *m = VoteResponse{} }
|
||||
func (m *VoteResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*VoteResponse) ProtoMessage() {}
|
||||
|
||||
// SubmitVoteRequest is the request for submitting a vote
|
||||
type SubmitVoteRequest struct {
|
||||
VoteId string `protobuf:"bytes,1,opt,name=vote_id,json=voteId" json:"vote_id,omitempty"`
|
||||
AgentId string `protobuf:"bytes,2,opt,name=agent_id,json=agentId" json:"agent_id,omitempty"`
|
||||
Option string `protobuf:"bytes,3,opt,name=option" json:"option,omitempty"`
|
||||
Reason string `protobuf:"bytes,4,opt,name=reason" json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
func (m *SubmitVoteRequest) Reset() { *m = SubmitVoteRequest{} }
|
||||
func (m *SubmitVoteRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*SubmitVoteRequest) ProtoMessage() {}
|
||||
|
||||
// SubmitVoteResponse is the response for submitting a vote
|
||||
type SubmitVoteResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
Error string `protobuf:"bytes,2,opt,name=error" json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (m *SubmitVoteResponse) Reset() { *m = SubmitVoteResponse{} }
|
||||
func (m *SubmitVoteResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*SubmitVoteResponse) ProtoMessage() {}
|
||||
|
||||
// GetVoteStatusRequest is the request for getting vote status
|
||||
type GetVoteStatusRequest struct {
|
||||
VoteId string `protobuf:"bytes,1,opt,name=vote_id,json=voteId" json:"vote_id,omitempty"`
|
||||
}
|
||||
|
||||
func (m *GetVoteStatusRequest) Reset() { *m = GetVoteStatusRequest{} }
|
||||
func (m *GetVoteStatusRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*GetVoteStatusRequest) ProtoMessage() {}
|
||||
|
||||
// VoteStatusResponse is the response for vote status
|
||||
type VoteStatusResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
VoteId string `protobuf:"bytes,2,opt,name=vote_id,json=voteId" json:"vote_id,omitempty"`
|
||||
Status string `protobuf:"bytes,3,opt,name=status" json:"status,omitempty"` // open, decided, expired
|
||||
Question string `protobuf:"bytes,4,opt,name=question" json:"question,omitempty"`
|
||||
TotalVotes int32 `protobuf:"varint,5,opt,name=total_votes,json=totalVotes" json:"total_votes,omitempty"`
|
||||
RequiredVotes int32 `protobuf:"varint,6,opt,name=required_votes,json=requiredVotes" json:"required_votes,omitempty"`
|
||||
WinningOption string `protobuf:"bytes,7,opt,name=winning_option,json=winningOption" json:"winning_option,omitempty"`
|
||||
Error string `protobuf:"bytes,8,opt,name=error" json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (m *VoteStatusResponse) Reset() { *m = VoteStatusResponse{} }
|
||||
func (m *VoteStatusResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*VoteStatusResponse) ProtoMessage() {}
|
||||
|
||||
// =============================================================================
|
||||
// Task Split Messages (NEW!)
|
||||
// =============================================================================
|
||||
|
||||
// SplitTaskRequest is the request for splitting a task
|
||||
type SplitTaskRequest struct {
|
||||
GroupId string `protobuf:"bytes,1,opt,name=group_id,json=groupId" json:"group_id,omitempty"`
|
||||
TaskId string `protobuf:"bytes,2,opt,name=task_id,json=taskId" json:"task_id,omitempty"`
|
||||
TaskType string `protobuf:"bytes,3,opt,name=task_type,json=taskType" json:"task_type,omitempty"`
|
||||
Requirements string `protobuf:"bytes,4,opt,name=requirements" json:"requirements,omitempty"`
|
||||
Strategy SplitStrategy `protobuf:"varint,5,opt,name=strategy,enum=a2a.SplitStrategy" json:"strategy,omitempty"`
|
||||
}
|
||||
|
||||
func (m *SplitTaskRequest) Reset() { *m = SplitTaskRequest{} }
|
||||
func (m *SplitTaskRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*SplitTaskRequest) ProtoMessage() {}
|
||||
|
||||
type SplitStrategy int32
|
||||
|
||||
const (
|
||||
SplitStrategy_SPLIT_BY_TYPE SplitStrategy = 0
|
||||
SplitStrategy_SPLIT_BY_DATA SplitStrategy = 1
|
||||
SplitStrategy_SPLIT_BY_REGION SplitStrategy = 2
|
||||
SplitStrategy_SPLIT_BY_ROUNDROBIN SplitStrategy = 3
|
||||
)
|
||||
|
||||
// SplitTaskResponse is the response for splitting a task
|
||||
type SplitTaskResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
GroupId string `protobuf:"bytes,2,opt,name=group_id,json=groupId" json:"group_id,omitempty"`
|
||||
ParentTaskId string `protobuf:"bytes,3,opt,name=parent_task_id,json=parentTaskId" json:"parent_task_id,omitempty"`
|
||||
Subtasks []*SubtaskInfo `protobuf:"bytes,4,rep,name=subtasks" json:"subtasks,omitempty"`
|
||||
Error string `protobuf:"bytes,5,opt,name=error" json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (m *SplitTaskResponse) Reset() { *m = SplitTaskResponse{} }
|
||||
func (m *SplitTaskResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*SplitTaskResponse) ProtoMessage() {}
|
||||
|
||||
type SubtaskInfo struct {
|
||||
SubtaskId string `protobuf:"bytes,1,opt,name=subtask_id,json=subtaskId" json:"subtask_id,omitempty"`
|
||||
Assignee string `protobuf:"bytes,2,opt,name=assignee" json:"assignee,omitempty"`
|
||||
Scope string `protobuf:"bytes,3,opt,name=scope" json:"scope,omitempty"`
|
||||
Dependencies []string `protobuf:"bytes,4,rep,name=dependencies" json:"dependencies,omitempty"`
|
||||
}
|
||||
|
||||
func (m *SubtaskInfo) Reset() { *m = SubtaskInfo{} }
|
||||
func (m *SubtaskInfo) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*SubtaskInfo) ProtoMessage() {}
|
||||
|
||||
// MergeResultsRequest is the request for merging results
|
||||
type MergeResultsRequest struct {
|
||||
GroupId string `protobuf:"bytes,1,opt,name=group_id,json=groupId" json:"group_id,omitempty"`
|
||||
ParentTaskId string `protobuf:"bytes,2,opt,name=parent_task_id,json=parentTaskId" json:"parent_task_id,omitempty"`
|
||||
Strategy MergeStrategy `protobuf:"varint,3,opt,name=strategy,enum=a2a.MergeStrategy" json:"strategy,omitempty"`
|
||||
}
|
||||
|
||||
func (m *MergeResultsRequest) Reset() { *m = MergeResultsRequest{} }
|
||||
func (m *MergeResultsRequest) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*MergeResultsRequest) ProtoMessage() {}
|
||||
|
||||
type MergeStrategy int32
|
||||
|
||||
const (
|
||||
MergeStrategy_MERGE_ALL MergeStrategy = 0
|
||||
MergeStrategy_MERGE_BEST MergeStrategy = 1
|
||||
MergeStrategy_MERGE_CONSENSUS MergeStrategy = 2
|
||||
MergeStrategy_MERGE_AGGREGATE MergeStrategy = 3
|
||||
)
|
||||
|
||||
// MergeResultsResponse is the response for merging results
|
||||
type MergeResultsResponse struct {
|
||||
Success bool `protobuf:"varint,1,opt,name=success" json:"success,omitempty"`
|
||||
ParentTaskId string `protobuf:"bytes,2,opt,name=parent_task_id,json=parentTaskId" json:"parent_task_id,omitempty"`
|
||||
MergedResult *anypb.Any `protobuf:"bytes,3,opt,name=merged_result,json=mergedResult" json:"merged_result,omitempty"`
|
||||
Summary string `protobuf:"bytes,4,opt,name=summary" json:"summary,omitempty"`
|
||||
Error string `protobuf:"bytes,5,opt,name=error" json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (m *MergeResultsResponse) Reset() { *m = MergeResultsResponse{} }
|
||||
func (m *MergeResultsResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*MergeResultsResponse) ProtoMessage() {}
|
||||
|
||||
// =============================================================================
|
||||
// Health Service Messages
|
||||
// =============================================================================
|
||||
|
||||
// HealthCheckResponse is the response for health check
|
||||
type HealthCheckResponse struct {
|
||||
Status string `protobuf:"bytes,1,opt,name=status" json:"status,omitempty"`
|
||||
Version string `protobuf:"bytes,2,opt,name=version" json:"version,omitempty"`
|
||||
UptimeSeconds int64 `protobuf:"varint,3,opt,name=uptime_seconds,json=uptimeSeconds" json:"uptime_seconds,omitempty"`
|
||||
ActiveTasks int32 `protobuf:"varint,4,opt,name=active_tasks,json=activeTasks" json:"active_tasks,omitempty"`
|
||||
}
|
||||
|
||||
func (m *HealthCheckResponse) Reset() { *m = HealthCheckResponse{} }
|
||||
func (m *HealthCheckResponse) String() string { return fmt.Sprintf("%+v", m) }
|
||||
func (*HealthCheckResponse) ProtoMessage() {}
|
||||
|
||||
// =============================================================================
|
||||
// Unimplemented types for proto compatibility
|
||||
// =============================================================================
|
||||
|
||||
// Ensure proto compatibility
|
||||
var _ proto.Message = (*AgentEndpoint)(nil)
|
||||
var _ proto.Message = (*A2AMessage)(nil)
|
||||
var _ proto.Message = (*SubmitTaskRequest)(nil)
|
||||
var _ proto.Message = (*SubmitTaskResponse)(nil)
|
||||
var _ proto.Message = (*GetTaskRequest)(nil)
|
||||
var _ proto.Message = (*TaskStatusResponse)(nil)
|
||||
var _ proto.Message = (*ListTasksRequest)(nil)
|
||||
var _ proto.Message = (*ListTasksResponse)(nil)
|
||||
var _ proto.Message = (*CancelTaskRequest)(nil)
|
||||
var _ proto.Message = (*CancelTaskResponse)(nil)
|
||||
var _ proto.Message = (*SendMessageRequest)(nil)
|
||||
var _ proto.Message = (*SendMessageResponse)(nil)
|
||||
var _ proto.Message = (*CapabilitiesResponse)(nil)
|
||||
var _ proto.Message = (*CreateGroupRequest)(nil)
|
||||
var _ proto.Message = (*CreateGroupResponse)(nil)
|
||||
var _ proto.Message = (*JoinGroupRequest)(nil)
|
||||
var _ proto.Message = (*JoinGroupResponse)(nil)
|
||||
var _ proto.Message = (*LeaveGroupRequest)(nil)
|
||||
var _ proto.Message = (*LeaveGroupResponse)(nil)
|
||||
var _ proto.Message = (*DisbandGroupRequest)(nil)
|
||||
var _ proto.Message = (*DisbandGroupResponse)(nil)
|
||||
var _ proto.Message = (*ListGroupMembersRequest)(nil)
|
||||
var _ proto.Message = (*ListGroupMembersResponse)(nil)
|
||||
var _ proto.Message = (*HealthCheckResponse)(nil)
|
||||
1145
internal/api/grpcapi/synapse_grpc.pb.go
Normal file
1145
internal/api/grpcapi/synapse_grpc.pb.go
Normal file
File diff suppressed because it is too large
Load Diff
546
internal/capabilities/provider.go
Normal file
546
internal/capabilities/provider.go
Normal file
@@ -0,0 +1,546 @@
|
||||
package capabilities
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Capabilities Provider Interface
|
||||
// =============================================================================
|
||||
|
||||
// CapabilitiesProvider 定义Agent暴露自身能力的接口
|
||||
// 所有Agent都应该实现此接口以便其他Agent查询其能力
|
||||
type CapabilitiesProvider interface {
|
||||
// GetCapabilities 返回Agent的完整能力描述
|
||||
GetCapabilities(ctx context.Context) (*types.AgentCapabilities, error)
|
||||
|
||||
// GetSupportedInterfaces 返回Agent实现的接口列表
|
||||
GetSupportedInterfaces() []ImplementedInterface
|
||||
|
||||
// GetTaskTypeCapabilities 返回特定任务类型的详细能力
|
||||
GetTaskTypeCapabilities(taskType string) (*types.SupportedTaskType, error)
|
||||
}
|
||||
|
||||
// ImplementedInterface 定义Agent实现的接口
|
||||
type ImplementedInterface struct {
|
||||
// InterfaceName 接口名称
|
||||
Name string `json:"name"`
|
||||
|
||||
// Category 接口分类
|
||||
Category InterfaceCategory `json:"category"`
|
||||
|
||||
// Version 接口版本
|
||||
Version string `json:"version"`
|
||||
|
||||
// ComplianceLevel 合规级别 (basic, complete, advanced)
|
||||
ComplianceLevel string `json:"compliance_level"`
|
||||
|
||||
// Description 接口描述
|
||||
Description string `json:"description"`
|
||||
|
||||
// Methods 接口支持的方法
|
||||
Methods []InterfaceMethod `json:"methods,omitempty"`
|
||||
|
||||
// Status 接口状态 (implemented, partial, planned)
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// InterfaceCategory 接口分类
|
||||
type InterfaceCategory string
|
||||
|
||||
const (
|
||||
CategoryCore InterfaceCategory = "core" // 核心接口
|
||||
CategoryP2P InterfaceCategory = "p2p" // P2P接口
|
||||
CategoryGroup InterfaceCategory = "group" // 群组接口
|
||||
CategoryHiL InterfaceCategory = "hil" // 人工介入接口
|
||||
CategoryTransport InterfaceCategory = "transport" // 传输接口
|
||||
CategorySecurity InterfaceCategory = "security" // 安全接口
|
||||
CategoryManagement InterfaceCategory = "management" // 管理接口
|
||||
)
|
||||
|
||||
// InterfaceMethod 接口方法
|
||||
type InterfaceMethod struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputType string `json:"input_type,omitempty"`
|
||||
OutputType string `json:"output_type,omitempty"`
|
||||
Required bool `json:"required"`
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Standard Interfaces Registry
|
||||
// =============================================================================
|
||||
|
||||
// StandardInterfaces 定义Synapse协议的标准接口
|
||||
var StandardInterfaces = map[string]ImplementedInterface{
|
||||
// === Core Interfaces ===
|
||||
"agent_identity": {
|
||||
Name: "AgentIdentity",
|
||||
Category: CategoryCore,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "basic",
|
||||
Description: "提供Agent身份信息接口",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "GetAgentID", Description: "返回Agent唯一标识", OutputType: "string", Required: true},
|
||||
{Name: "GetSystemID", Description: "返回Agent所属系统ID", OutputType: "string", Required: true},
|
||||
{Name: "GetEndpoint", Description: "返回Agent回调端点", OutputType: "string", Required: true},
|
||||
{Name: "GetName", Description: "返回Agent名称", OutputType: "string", Required: false},
|
||||
{Name: "GetVersion", Description: "返回Agent版本", OutputType: "string", Required: false},
|
||||
},
|
||||
},
|
||||
"message_handler": {
|
||||
Name: "MessageHandler",
|
||||
Category: CategoryCore,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "basic",
|
||||
Description: "处理接收到的Synapse消息",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "HandleMessage", Description: "处理消息并返回响应", InputType: "UnifiedSynapseMessage", OutputType: "UnifiedSynapseMessage", Required: true},
|
||||
{Name: "GetProtocolVersion", Description: "返回支持的协议版本", OutputType: "string", Required: true},
|
||||
},
|
||||
},
|
||||
"capabilities_provider": {
|
||||
Name: "CapabilitiesProvider",
|
||||
Category: CategoryCore,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "basic",
|
||||
Description: "暴露Agent能力信息",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "GetCapabilities", Description: "返回完整能力描述", OutputType: "AgentCapabilities", Required: true},
|
||||
{Name: "GetSupportedInterfaces", Description: "返回实现的接口列表", OutputType: "[]ImplementedInterface", Required: true},
|
||||
},
|
||||
},
|
||||
|
||||
// === P2P Interfaces ===
|
||||
"task_handler": {
|
||||
Name: "P2PTaskHandler",
|
||||
Category: CategoryP2P,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "basic",
|
||||
Description: "处理P2P任务请求",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "ExecuteTask", Description: "执行任务并返回结果", InputType: "taskType, payload", OutputType: "any", Required: true},
|
||||
{Name: "ValidateTask", Description: "验证任务是否可执行", InputType: "taskType, payload", OutputType: "[]MissingField, bool", Required: true},
|
||||
{Name: "GetSupportedTaskTypes", Description: "返回支持的任务类型列表", OutputType: "[]string", Required: true},
|
||||
{Name: "GetEstimatedDuration", Description: "预估任务执行时间", InputType: "taskType, payload", OutputType: "int", Required: false},
|
||||
},
|
||||
},
|
||||
"callback_sender": {
|
||||
Name: "CallbackSender",
|
||||
Category: CategoryP2P,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "complete",
|
||||
Description: "发送回调消息",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "SendCallback", Description: "发送回调消息", InputType: "endpoint, message", OutputType: "error", Required: true},
|
||||
{Name: "SendCallbackWithRetry", Description: "带重试的回调发送", InputType: "endpoint, message, maxRetries", OutputType: "error", Required: false},
|
||||
},
|
||||
},
|
||||
"callback_receiver": {
|
||||
Name: "CallbackReceiver",
|
||||
Category: CategoryP2P,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "basic",
|
||||
Description: "接收回调消息的HTTP端点",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "POST /synapse/callback", Description: "接收回调消息的HTTP端点", InputType: "UnifiedSynapseMessage", OutputType: "HTTP 200", Required: true},
|
||||
},
|
||||
},
|
||||
|
||||
// === Polling Interfaces ===
|
||||
"task_status_provider": {
|
||||
Name: "TaskStatusProvider",
|
||||
Category: CategoryP2P,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "complete",
|
||||
Description: "提供任务状态查询接口",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "GET /synapse/task/{id}", Description: "查询单个任务状态", OutputType: "TaskStatusResponse", Required: true},
|
||||
{Name: "GET /synapse/tasks", Description: "查询任务列表", OutputType: "TaskListResponse", Required: true},
|
||||
{Name: "GET /synapse/task/{id}/events", Description: "查询任务事件流", OutputType: "TaskEventsResponse", Required: false},
|
||||
},
|
||||
},
|
||||
"polling_client": {
|
||||
Name: "PollingClient",
|
||||
Category: CategoryTransport,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "complete",
|
||||
Description: "轮询客户端",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "GetTaskStatus", Description: "获取任务状态", InputType: "taskID", OutputType: "TaskInfo", Required: true},
|
||||
{Name: "StartPolling", Description: "开始持续轮询", InputType: "taskID, callback", OutputType: "error", Required: true},
|
||||
{Name: "StopPolling", Description: "停止轮询", InputType: "taskID", Required: true},
|
||||
},
|
||||
},
|
||||
|
||||
// === Group Interfaces ===
|
||||
"group_handler": {
|
||||
Name: "GroupTaskHandler",
|
||||
Category: CategoryGroup,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "advanced",
|
||||
Description: "处理群组任务协作",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "ExecuteSubtask", Description: "执行子任务", InputType: "subtaskID, payload", OutputType: "any", Required: true},
|
||||
{Name: "MergeResults", Description: "合并子任务结果", InputType: "results, strategy", OutputType: "any", Required: true},
|
||||
{Name: "ValidateTaskSplit", Description: "验证任务分解方案", InputType: "taskType, requirements", OutputType: "[]Subtask, bool", Required: true},
|
||||
},
|
||||
},
|
||||
"group_manager": {
|
||||
Name: "GroupManager",
|
||||
Category: CategoryGroup,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "advanced",
|
||||
Description: "管理群组",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "CreateGroup", Description: "创建群组", InputType: "GroupConfig", OutputType: "Group", Required: true},
|
||||
{Name: "JoinGroup", Description: "加入群组", InputType: "groupID", OutputType: "error", Required: true},
|
||||
{Name: "LeaveGroup", Description: "离开群组", InputType: "groupID", OutputType: "error", Required: true},
|
||||
{Name: "DisbandGroup", Description: "解散群组", InputType: "groupID", OutputType: "error", Required: true},
|
||||
},
|
||||
},
|
||||
"voting_handler": {
|
||||
Name: "VotingHandler",
|
||||
Category: CategoryGroup,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "advanced",
|
||||
Description: "处理投票共识",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "InitiateVote", Description: "发起投票", InputType: "VoteRequest", OutputType: "Vote", Required: true},
|
||||
{Name: "SubmitVote", Description: "提交投票", InputType: "voteID, option", OutputType: "error", Required: true},
|
||||
{Name: "GetVoteStatus", Description: "获取投票状态", InputType: "voteID", OutputType: "VoteStatus", Required: true},
|
||||
},
|
||||
},
|
||||
|
||||
// === HiL Interfaces ===
|
||||
"hil_handler": {
|
||||
Name: "HILHandler",
|
||||
Category: CategoryHiL,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "complete",
|
||||
Description: "处理人工介入请求",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "RequestHumanDecision", Description: "请求人工决策", InputType: "HILRequest", OutputType: "HILResponse", Required: true},
|
||||
{Name: "ProcessHumanDecision", Description: "处理人工决策响应", InputType: "HILResponse", OutputType: "error", Required: true},
|
||||
{Name: "GetHILStatus", Description: "获取HiL请求状态", InputType: "hilID", OutputType: "HILStatus", Required: true},
|
||||
},
|
||||
},
|
||||
"escalation_handler": {
|
||||
Name: "EscalationHandler",
|
||||
Category: CategoryHiL,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "advanced",
|
||||
Description: "处理升级请求",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "EscalateToHuman", Description: "升级到人工", InputType: "taskID, reason, level", OutputType: "HILRequest", Required: true},
|
||||
{Name: "EscalateToGroup", Description: "升级到群组", InputType: "taskID, groupID", OutputType: "error", Required: true},
|
||||
},
|
||||
},
|
||||
|
||||
// === Transport Interfaces ===
|
||||
"http_transport": {
|
||||
Name: "HTTPTransport",
|
||||
Category: CategoryTransport,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "basic",
|
||||
Description: "HTTP传输",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "Send", Description: "发送HTTP消息", InputType: "endpoint, message", OutputType: "error", Required: true},
|
||||
{Name: "Start", Description: "启动服务", Required: true},
|
||||
{Name: "Stop", Description: "停止服务", Required: true},
|
||||
},
|
||||
},
|
||||
"multipart_transport": {
|
||||
Name: "MultipartTransport",
|
||||
Category: CategoryTransport,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "complete",
|
||||
Description: "Multipart文件传输",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "SendTaskWithFiles", Description: "发送带文件的任务", InputType: "endpoint, message, files", OutputType: "error", Required: true},
|
||||
{Name: "ParseMultipartRequest", Description: "解析multipart请求", InputType: "HTTPRequest", OutputType: "Message, Files", Required: true},
|
||||
},
|
||||
},
|
||||
"hybrid_transport": {
|
||||
Name: "HybridTransport",
|
||||
Category: CategoryTransport,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "complete",
|
||||
Description: "混合传输(回调+轮询)",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "SendTaskWithHybridFallback", Description: "发送任务并自动切换", InputType: "endpoint, message, callback", OutputType: "error", Required: true},
|
||||
{Name: "NotifyCallbackReceived", Description: "通知回调已收到", InputType: "taskID", Required: true},
|
||||
},
|
||||
},
|
||||
"streaming_transport": {
|
||||
Name: "StreamingTransport",
|
||||
Category: CategoryTransport,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "advanced",
|
||||
Description: "流式传输",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "WebSocket /synapse/stream", Description: "WebSocket流式端点", Required: true},
|
||||
{Name: "GET /synapse/stream (SSE)", Description: "SSE流式端点", Required: false},
|
||||
},
|
||||
},
|
||||
|
||||
// === Security Interfaces ===
|
||||
"authenticator": {
|
||||
Name: "Authenticator",
|
||||
Category: CategorySecurity,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "basic",
|
||||
Description: "认证和签名",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "Authenticate", Description: "验证消息签名", InputType: "message, signature", OutputType: "bool", Required: true},
|
||||
{Name: "Sign", Description: "签名消息", InputType: "message", OutputType: "string", Required: true},
|
||||
},
|
||||
},
|
||||
"idempotency_handler": {
|
||||
Name: "IdempotencyHandler",
|
||||
Category: CategorySecurity,
|
||||
Version: "1.0.0",
|
||||
ComplianceLevel: "basic",
|
||||
Description: "幂等性处理",
|
||||
Status: "implemented",
|
||||
Methods: []InterfaceMethod{
|
||||
{Name: "CheckIdempotency", Description: "检查消息幂等性", InputType: "messageID", OutputType: "bool", Required: true},
|
||||
{Name: "MarkProcessed", Description: "标记消息已处理", InputType: "messageID", Required: true},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Extended AgentCapabilities
|
||||
// =============================================================================
|
||||
|
||||
// ExtendedAgentCapabilities 扩展的Agent能力描述
|
||||
type ExtendedAgentCapabilities struct {
|
||||
// 基础能力
|
||||
types.AgentCapabilities
|
||||
|
||||
// 实现的接口列表
|
||||
ImplementedInterfaces []ImplementedInterface `json:"implemented_interfaces"`
|
||||
|
||||
// 合规级别 summary
|
||||
ComplianceSummary ComplianceSummary `json:"compliance_summary"`
|
||||
|
||||
// 自定义能力
|
||||
CustomCapabilities map[string]any `json:"custom_capabilities,omitempty"`
|
||||
|
||||
// 依赖的其他Agent
|
||||
Dependencies []AgentDependency `json:"dependencies,omitempty"`
|
||||
|
||||
// 服务健康信息
|
||||
HealthInfo HealthInfo `json:"health_info"`
|
||||
}
|
||||
|
||||
// ComplianceSummary 合规级别摘要
|
||||
type ComplianceSummary struct {
|
||||
BasicImplemented int `json:"basic_implemented"`
|
||||
BasicRequired int `json:"basic_required"`
|
||||
CompleteImplemented int `json:"complete_implemented"`
|
||||
CompleteRequired int `json:"complete_required"`
|
||||
AdvancedImplemented int `json:"advanced_implemented"`
|
||||
|
||||
OverallLevel string `json:"overall_level"` // "basic", "complete", "advanced"
|
||||
}
|
||||
|
||||
// AgentDependency Agent依赖
|
||||
type AgentDependency struct {
|
||||
AgentID string `json:"agent_id"`
|
||||
SystemID string `json:"system_id"`
|
||||
Required bool `json:"required"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// HealthInfo 健康信息
|
||||
type HealthInfo struct {
|
||||
Status string `json:"status"` // "healthy", "degraded", "unhealthy"
|
||||
LastCheckAt string `json:"last_check_at"`
|
||||
Uptime int64 `json:"uptime_seconds"`
|
||||
Version string `json:"version"`
|
||||
ActiveTasks int `json:"active_tasks"`
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// HTTP Handler for Capabilities Endpoint
|
||||
// =============================================================================
|
||||
|
||||
// CapabilitiesHandler 处理 GET /synapse/capabilities 请求
|
||||
type CapabilitiesHandler struct {
|
||||
provider CapabilitiesProvider
|
||||
}
|
||||
|
||||
// NewCapabilitiesHandler 创建能力查询处理器
|
||||
func NewCapabilitiesHandler(provider CapabilitiesProvider) *CapabilitiesHandler {
|
||||
return &CapabilitiesHandler{provider: provider}
|
||||
}
|
||||
|
||||
// ServeHTTP 处理HTTP请求
|
||||
func (h *CapabilitiesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
// 获取能力
|
||||
caps, err := h.provider.GetCapabilities(ctx)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// 获取实现的接口
|
||||
interfaces := h.provider.GetSupportedInterfaces()
|
||||
|
||||
// 构建扩展能力响应
|
||||
extended := &ExtendedAgentCapabilities{
|
||||
AgentCapabilities: *caps,
|
||||
ImplementedInterfaces: interfaces,
|
||||
ComplianceSummary: CalculateComplianceSummary(interfaces),
|
||||
}
|
||||
|
||||
// 返回响应
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Synapse-Version", "1.0.0")
|
||||
|
||||
resp := types.NewCapabilitiesResponse(&extended.AgentCapabilities)
|
||||
respJSON, _ := json.Marshal(resp)
|
||||
w.Write(respJSON)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Helper Functions
|
||||
// =============================================================================
|
||||
|
||||
// CalculateComplianceSummary 计算合规摘要
|
||||
func CalculateComplianceSummary(interfaces []ImplementedInterface) ComplianceSummary {
|
||||
summary := ComplianceSummary{}
|
||||
|
||||
for _, iface := range interfaces {
|
||||
switch iface.ComplianceLevel {
|
||||
case "basic":
|
||||
summary.BasicImplemented++
|
||||
case "complete":
|
||||
summary.CompleteImplemented++
|
||||
case "advanced":
|
||||
summary.AdvancedImplemented++
|
||||
}
|
||||
}
|
||||
|
||||
// 计算要求的数量
|
||||
for _, std := range StandardInterfaces {
|
||||
switch std.ComplianceLevel {
|
||||
case "basic":
|
||||
summary.BasicRequired++
|
||||
case "complete":
|
||||
summary.CompleteRequired++
|
||||
}
|
||||
}
|
||||
|
||||
// 确定整体级别
|
||||
if summary.BasicImplemented >= summary.BasicRequired {
|
||||
if summary.CompleteImplemented >= summary.CompleteRequired {
|
||||
if summary.AdvancedImplemented > 0 {
|
||||
summary.OverallLevel = "advanced"
|
||||
} else {
|
||||
summary.OverallLevel = "complete"
|
||||
}
|
||||
} else {
|
||||
summary.OverallLevel = "basic"
|
||||
}
|
||||
} else {
|
||||
summary.OverallLevel = "none"
|
||||
}
|
||||
|
||||
return summary
|
||||
}
|
||||
|
||||
// GetStandardInterface 获取标准接口定义
|
||||
func GetStandardInterface(name string) *ImplementedInterface {
|
||||
if iface, ok := StandardInterfaces[name]; ok {
|
||||
return &iface
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAllStandardInterfaces 获取所有标准接口
|
||||
func GetAllStandardInterfaces() map[string]ImplementedInterface {
|
||||
return StandardInterfaces
|
||||
}
|
||||
|
||||
// GetInterfacesByCategory 获取指定分类的接口
|
||||
func GetInterfacesByCategory(category InterfaceCategory) []ImplementedInterface {
|
||||
var result []ImplementedInterface
|
||||
for _, iface := range StandardInterfaces {
|
||||
if iface.Category == category {
|
||||
result = append(result, iface)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// GetInterfacesByComplianceLevel 获取指定合规级别的接口
|
||||
func GetInterfacesByComplianceLevel(level string) []ImplementedInterface {
|
||||
var result []ImplementedInterface
|
||||
for _, iface := range StandardInterfaces {
|
||||
if iface.ComplianceLevel == level {
|
||||
result = append(result, iface)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// CheckInterfaceCompliance 检查接口合规性
|
||||
func CheckInterfaceCompliance(implemented []ImplementedInterface) map[string][]string {
|
||||
result := map[string][]string{
|
||||
"missing_basic": []string{},
|
||||
"missing_complete": []string{},
|
||||
"implemented": []string{},
|
||||
}
|
||||
|
||||
implementedSet := make(map[string]bool)
|
||||
for _, iface := range implemented {
|
||||
implementedSet[iface.Name] = true
|
||||
}
|
||||
|
||||
for name, std := range StandardInterfaces {
|
||||
if implementedSet[std.Name] {
|
||||
result["implemented"] = append(result["implemented"], name)
|
||||
} else {
|
||||
switch std.ComplianceLevel {
|
||||
case "basic":
|
||||
result["missing_basic"] = append(result["missing_basic"], name)
|
||||
case "complete":
|
||||
result["missing_complete"] = append(result["missing_complete"], name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
521
internal/components/harbor/harbor.go
Normal file
521
internal/components/harbor/harbor.go
Normal file
@@ -0,0 +1,521 @@
|
||||
// Package harbor 灵泊 - 异步队列与暂存层
|
||||
//
|
||||
// "泊"为船舶停靠。数据包如远行之舟,
|
||||
// 遇风浪(网络抖动)时暂泊于此,
|
||||
// 待风平浪静(目标就绪)再启航。
|
||||
// 不丢包、不超时,给予 Agent 异步协作的从容。
|
||||
package harbor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/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
internal/components/libra/libra.go
Normal file
473
internal/components/libra/libra.go
Normal file
@@ -0,0 +1,473 @@
|
||||
// Package libra 灵衡 - 价值结算与激励层
|
||||
//
|
||||
// 权衡利弊,计量公平。此层负责将 Agent 间的
|
||||
// "智力贡献"与"资源消耗"通证化,动态定价,
|
||||
// 让多智能体经济具备自驱的盈亏平衡,
|
||||
// 而非单一中心补贴。
|
||||
package libra
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/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
internal/components/meridian/meridian.go
Normal file
351
internal/components/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/pkg/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)
|
||||
}
|
||||
540
internal/components/panorama/panorama.go
Normal file
540
internal/components/panorama/panorama.go
Normal file
@@ -0,0 +1,540 @@
|
||||
// Package panorama 灵瞰 - 可观测与度量层
|
||||
//
|
||||
// 居高临下,俯瞰全局。此层不参与业务交互,
|
||||
// 却如"天眼"般记录每一帧交互的耗时、置信度与资源消耗,
|
||||
// 让黑盒群体智能变为白盒可解释的图景。
|
||||
package panorama
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/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
internal/components/pivot/pivot.go
Normal file
503
internal/components/pivot/pivot.go
Normal file
@@ -0,0 +1,503 @@
|
||||
// Package pivot 灵枢 - 紧急制动与治理层
|
||||
//
|
||||
// 取自《灵枢经》(黄帝内经下半部),
|
||||
// 讲的是针灸经络之枢纽。
|
||||
// 这是整个协议的"总闸"与"方向盘",
|
||||
// 不轻易触发,但触发时能以最小代价
|
||||
// 重置整个 Synapse 网络的状态。
|
||||
package pivot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/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)
|
||||
}
|
||||
446
internal/components/sigil/sigil.go
Normal file
446
internal/components/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/pkg/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
internal/components/speculum/speculum.go
Normal file
523
internal/components/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)
|
||||
}
|
||||
683
internal/hil/protocol.go
Normal file
683
internal/hil/protocol.go
Normal file
@@ -0,0 +1,683 @@
|
||||
package hil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// HiL Manager
|
||||
// =============================================================================
|
||||
|
||||
// DecisionMaker is the interface for human decision makers
|
||||
type DecisionMaker interface {
|
||||
// RequestDecision sends a decision request to a human
|
||||
RequestDecision(ctx context.Context, request *HILRequest) (*HILResponse, error)
|
||||
|
||||
// GetUserRole returns the user's role for authorization
|
||||
GetUserRole(userID string) string
|
||||
}
|
||||
|
||||
// HILConfig holds HiL configuration
|
||||
type HILConfig struct {
|
||||
// Level 1: Agent suggests + human confirms (24h default)
|
||||
Level1Timeout time.Duration
|
||||
|
||||
// Level 2: Must human decide (12h default, 2h urgent)
|
||||
Level2Timeout time.Duration
|
||||
Level2UrgentTimeout time.Duration
|
||||
|
||||
// Level 3: Expert/management decision (on-demand)
|
||||
Level3Timeout time.Duration
|
||||
|
||||
// Default timeouts
|
||||
DefaultTimeout time.Duration
|
||||
}
|
||||
|
||||
func DefaultHILConfig() *HILConfig {
|
||||
return &HILConfig{
|
||||
Level1Timeout: 24 * time.Hour,
|
||||
Level2Timeout: 12 * time.Hour,
|
||||
Level2UrgentTimeout: 2 * time.Hour,
|
||||
Level3Timeout: 72 * time.Hour,
|
||||
DefaultTimeout: 24 * time.Hour,
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// HILRequest represents a human-in-the-loop request
|
||||
// =============================================================================
|
||||
|
||||
type HILRequest struct {
|
||||
ID string
|
||||
TaskID string
|
||||
EscalationType string // P2P, GROUP, INTER_GROUP
|
||||
EscalationLevel int // 1, 2, 3
|
||||
Reason HILReason
|
||||
Context HILContext
|
||||
Options []HILOption
|
||||
SuggestedValue any
|
||||
Deadline time.Time
|
||||
Status HILStatus
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
DecidedAt *time.Time
|
||||
Response *HILResponse
|
||||
}
|
||||
|
||||
// HILReason describes why human intervention is needed
|
||||
type HILReason struct {
|
||||
Code string
|
||||
Message string
|
||||
}
|
||||
|
||||
// HILContext provides context for the decision
|
||||
type HILContext struct {
|
||||
TaskSummary string
|
||||
CurrentProgress int
|
||||
BlockedReason string
|
||||
RelevantHistory []HILHistoryItem
|
||||
}
|
||||
|
||||
// HILHistoryItem is a historical item for context
|
||||
type HILHistoryItem struct {
|
||||
Timestamp time.Time
|
||||
Event string
|
||||
Details string
|
||||
}
|
||||
|
||||
// HILOption represents a decision option
|
||||
type HILOption struct {
|
||||
Field string
|
||||
Value any
|
||||
Label string
|
||||
ProsCons string
|
||||
Confidence int // 0-100
|
||||
}
|
||||
|
||||
// HILStatus represents the status of a HiL request
|
||||
type HILStatus string
|
||||
|
||||
const (
|
||||
HILStatusPending HILStatus = "pending"
|
||||
HILStatusWaiting HILStatus = "waiting"
|
||||
HILStatusDeciding HILStatus = "deciding"
|
||||
HILStatusApproved HILStatus = "approved"
|
||||
HILStatusRejected HILStatus = "rejected"
|
||||
HILStatusTimeout HILStatus = "timeout"
|
||||
HILStatusEscalated HILStatus = "escalated"
|
||||
)
|
||||
|
||||
// HILResponse represents a human's decision
|
||||
type HILResponse struct {
|
||||
DecisionID string
|
||||
UserID string
|
||||
UserName string
|
||||
UserRole string
|
||||
Action string // approve, reject, modify, select
|
||||
Decision HILDecision
|
||||
Notes string
|
||||
Timestamp time.Time
|
||||
}
|
||||
|
||||
// HILDecision contains the actual decision
|
||||
type HILDecision struct {
|
||||
ApprovedFields map[string]interface{}
|
||||
ModifiedFields map[string]interface{}
|
||||
SelectedOption any
|
||||
RejectionReason string
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// HILProtocol
|
||||
// =============================================================================
|
||||
|
||||
type HILProtocol struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
// Agent identity
|
||||
agentEndpoint types.AgentEndpoint
|
||||
|
||||
// HIL requests
|
||||
requests map[string]*HILRequest
|
||||
|
||||
// Decision maker
|
||||
decisionMaker DecisionMaker
|
||||
|
||||
// Configuration
|
||||
config *HILConfig
|
||||
|
||||
// Callbacks
|
||||
callbacks map[string]chan *HILResponse
|
||||
}
|
||||
|
||||
// NewHILProtocol creates a new HiL protocol handler
|
||||
func NewHILProtocol(agentEndpoint types.AgentEndpoint, config *HILConfig) *HILProtocol {
|
||||
if config == nil {
|
||||
config = DefaultHILConfig()
|
||||
}
|
||||
return &HILProtocol{
|
||||
agentEndpoint: agentEndpoint,
|
||||
requests: make(map[string]*HILRequest),
|
||||
config: config,
|
||||
callbacks: make(map[string]chan *HILResponse),
|
||||
}
|
||||
}
|
||||
|
||||
// SetDecisionMaker sets the decision maker
|
||||
func (h *HILProtocol) SetDecisionMaker(m DecisionMaker) {
|
||||
h.decisionMaker = m
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// P2P HiL Methods
|
||||
// =============================================================================
|
||||
|
||||
// CreateP2PHILRequest creates a HiL request for P2P task
|
||||
func (h *HILProtocol) CreateP2PHILRequest(
|
||||
taskID string,
|
||||
reasonCode, reasonMessage string,
|
||||
context HILContext,
|
||||
options []HILOption,
|
||||
suggestedValue any,
|
||||
escalationLevel int,
|
||||
) *HILRequest {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
req := &HILRequest{
|
||||
ID: fmt.Sprintf("hil-%d", time.Now().UnixNano()),
|
||||
TaskID: taskID,
|
||||
EscalationType: "p2p",
|
||||
EscalationLevel: escalationLevel,
|
||||
Reason: HILReason{
|
||||
Code: reasonCode,
|
||||
Message: reasonMessage,
|
||||
},
|
||||
Context: context,
|
||||
Options: options,
|
||||
SuggestedValue: suggestedValue,
|
||||
Status: HILStatusPending,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Set deadline based on escalation level
|
||||
req.Deadline = h.getDeadline(escalationLevel)
|
||||
|
||||
h.requests[req.ID] = req
|
||||
|
||||
log.Printf("[HiL] P2P HiL request created: %s (level: %d, task: %s)", req.ID, escalationLevel, taskID)
|
||||
|
||||
return req
|
||||
}
|
||||
|
||||
// CreateP2PHumanDecisionMessage creates a HUMAN_DECISION message payload
|
||||
func (h *HILProtocol) CreateP2PHumanDecisionMessage(req *HILRequest, response *HILResponse) *types.UnifiedSynapseMessage {
|
||||
payload := types.HumanDecisionPayload{}
|
||||
payload.TaskID = req.TaskID
|
||||
payload.DecisionID = response.DecisionID
|
||||
payload.ReplyTo = req.ID
|
||||
payload.DecidedBy.UserID = response.UserID
|
||||
payload.DecidedBy.UserName = response.UserName
|
||||
payload.DecidedBy.Role = response.UserRole
|
||||
payload.Decision.Action = response.Action
|
||||
payload.Notes = response.Notes
|
||||
payload.Timestamp = types.NowTimestamp()
|
||||
|
||||
switch response.Action {
|
||||
case "approve":
|
||||
if response.Decision.ApprovedFields != nil {
|
||||
payload.Decision.ApprovedFields = response.Decision.ApprovedFields
|
||||
}
|
||||
case "reject":
|
||||
payload.Decision.RejectionReason = response.Decision.RejectionReason
|
||||
case "select":
|
||||
payload.Decision.SelectedOption = response.Decision.SelectedOption
|
||||
case "modify":
|
||||
payload.Decision.ModifiedFields = response.Decision.ModifiedFields
|
||||
}
|
||||
|
||||
payloadBytes, _ := json.Marshal(payload)
|
||||
|
||||
return &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.P2PHumanDecision),
|
||||
Sender: h.agentEndpoint,
|
||||
Payload: payloadBytes,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Group HiL Methods
|
||||
// =============================================================================
|
||||
|
||||
// CreateGroupConsensusEscalation creates a consensus escalation request
|
||||
func (h *HILProtocol) CreateGroupConsensusEscalation(
|
||||
groupID string,
|
||||
voteID string,
|
||||
question string,
|
||||
votes []struct {
|
||||
VoterID string
|
||||
VoterRole string
|
||||
Option string
|
||||
Reason string
|
||||
},
|
||||
consensusStatus struct {
|
||||
RequiredThreshold float64
|
||||
ActualThreshold float64
|
||||
LeadingOption string
|
||||
OptionsTied bool
|
||||
},
|
||||
escalateReason struct {
|
||||
Code string
|
||||
Message string
|
||||
},
|
||||
escalationLevel int,
|
||||
context struct {
|
||||
TaskID string
|
||||
OriginalTaskRequirements map[string]interface{}
|
||||
AgentRecommendations []struct {
|
||||
AgentID string
|
||||
SuggestedOption string
|
||||
}
|
||||
},
|
||||
) *types.UnifiedSynapseMessage {
|
||||
decisionOptions := make([]struct {
|
||||
Option string
|
||||
SupportCount int
|
||||
SupportAgents []string
|
||||
}, 0)
|
||||
|
||||
// Count votes per option
|
||||
optionCounts := make(map[string]int)
|
||||
optionAgents := make(map[string][]string)
|
||||
for _, v := range votes {
|
||||
optionCounts[v.Option]++
|
||||
optionAgents[v.Option] = append(optionAgents[v.Option], v.VoterID)
|
||||
}
|
||||
for opt, count := range optionCounts {
|
||||
decisionOptions = append(decisionOptions, struct {
|
||||
Option string
|
||||
SupportCount int
|
||||
SupportAgents []string
|
||||
}{
|
||||
Option: opt,
|
||||
SupportCount: count,
|
||||
SupportAgents: optionAgents[opt],
|
||||
})
|
||||
}
|
||||
|
||||
payload := types.GroupConsensusEscalatePayload{}
|
||||
payload.VoteID = voteID
|
||||
payload.EscalationID = fmt.Sprintf("hil-%d", time.Now().UnixNano())
|
||||
payload.Question = question
|
||||
|
||||
// Copy votes
|
||||
payload.Votes = make([]struct {
|
||||
VoterID string `json:"voter_id"`
|
||||
VoterRole string `json:"voter_role"`
|
||||
Option string `json:"option"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}, len(votes))
|
||||
for i, v := range votes {
|
||||
payload.Votes[i].VoterID = v.VoterID
|
||||
payload.Votes[i].VoterRole = v.VoterRole
|
||||
payload.Votes[i].Option = v.Option
|
||||
payload.Votes[i].Reason = v.Reason
|
||||
}
|
||||
|
||||
payload.ConsensusStatus.RequiredThreshold = consensusStatus.RequiredThreshold
|
||||
payload.ConsensusStatus.ActualThreshold = consensusStatus.ActualThreshold
|
||||
payload.ConsensusStatus.LeadingOption = consensusStatus.LeadingOption
|
||||
payload.ConsensusStatus.OptionsTied = consensusStatus.OptionsTied
|
||||
payload.EscalateReason.Code = escalateReason.Code
|
||||
payload.EscalateReason.Message = escalateReason.Message
|
||||
payload.EscalationLevel = escalationLevel
|
||||
|
||||
// Copy decision options
|
||||
payload.DecisionOptions = make([]struct {
|
||||
Option string `json:"option"`
|
||||
SupportCount int `json:"support_count"`
|
||||
SupportAgents []string `json:"support_agents"`
|
||||
}, len(decisionOptions))
|
||||
for i, d := range decisionOptions {
|
||||
payload.DecisionOptions[i].Option = d.Option
|
||||
payload.DecisionOptions[i].SupportCount = d.SupportCount
|
||||
payload.DecisionOptions[i].SupportAgents = d.SupportAgents
|
||||
}
|
||||
|
||||
payload.Deadline = types.Timestamp(h.getDeadline(escalationLevel).Format(time.RFC3339))
|
||||
payload.Context.TaskID = context.TaskID
|
||||
payload.Context.OriginalTaskRequirements = context.OriginalTaskRequirements
|
||||
|
||||
// Copy agent recommendations
|
||||
payload.Context.AgentRecommendations = make([]struct {
|
||||
AgentID string `json:"agent_id"`
|
||||
SuggestedOption string `json:"suggested_option"`
|
||||
}, len(context.AgentRecommendations))
|
||||
for i, r := range context.AgentRecommendations {
|
||||
payload.Context.AgentRecommendations[i].AgentID = r.AgentID
|
||||
payload.Context.AgentRecommendations[i].SuggestedOption = r.SuggestedOption
|
||||
}
|
||||
|
||||
payloadBytes, _ := json.Marshal(payload)
|
||||
|
||||
return &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.GroupConsensusEscalate),
|
||||
Sender: h.agentEndpoint,
|
||||
GroupID: groupID,
|
||||
Payload: payloadBytes,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}
|
||||
}
|
||||
|
||||
// CreateGroupSubtaskEscalation creates a subtask escalation request
|
||||
func (h *HILProtocol) CreateGroupSubtaskEscalation(
|
||||
groupID string,
|
||||
originalTask struct {
|
||||
ID string
|
||||
Type string
|
||||
Description string
|
||||
},
|
||||
subtask struct {
|
||||
ID string
|
||||
Description string
|
||||
AssignedTo string
|
||||
BlockedAt string
|
||||
BlockedReason struct {
|
||||
Code string
|
||||
Message string
|
||||
}
|
||||
AttemptedSolutions []string
|
||||
},
|
||||
requiredDecision struct {
|
||||
FieldsNeeded []struct {
|
||||
Field string
|
||||
CurrentValue any
|
||||
SuggestedValue any
|
||||
Alternatives []any
|
||||
ValidationRules string
|
||||
}
|
||||
DecisionType string
|
||||
AffectsOtherSubtasks bool
|
||||
RollbackPossible bool
|
||||
},
|
||||
escalationLevel int,
|
||||
) *types.UnifiedSynapseMessage {
|
||||
payload := types.GroupSubtaskEscalatePayload{}
|
||||
payload.OriginalTask.ID = originalTask.ID
|
||||
payload.OriginalTask.Type = originalTask.Type
|
||||
payload.OriginalTask.Description = originalTask.Description
|
||||
payload.Subtask.ID = subtask.ID
|
||||
payload.Subtask.Description = subtask.Description
|
||||
payload.Subtask.AssignedTo = subtask.AssignedTo
|
||||
payload.Subtask.BlockedAt = subtask.BlockedAt
|
||||
payload.Subtask.BlockedReason.Code = subtask.BlockedReason.Code
|
||||
payload.Subtask.BlockedReason.Message = subtask.BlockedReason.Message
|
||||
payload.Subtask.AttemptedSolutions = subtask.AttemptedSolutions
|
||||
|
||||
// Copy fields needed
|
||||
payload.RequiredDecision.FieldsNeeded = make([]struct {
|
||||
Field string `json:"field"`
|
||||
CurrentValue any `json:"current_value,omitempty"`
|
||||
SuggestedValue any `json:"suggested_value,omitempty"`
|
||||
Alternatives []any `json:"alternatives,omitempty"`
|
||||
ValidationRules string `json:"validation_rules,omitempty"`
|
||||
}, len(requiredDecision.FieldsNeeded))
|
||||
for i, f := range requiredDecision.FieldsNeeded {
|
||||
payload.RequiredDecision.FieldsNeeded[i].Field = f.Field
|
||||
payload.RequiredDecision.FieldsNeeded[i].CurrentValue = f.CurrentValue
|
||||
payload.RequiredDecision.FieldsNeeded[i].SuggestedValue = f.SuggestedValue
|
||||
payload.RequiredDecision.FieldsNeeded[i].Alternatives = f.Alternatives
|
||||
payload.RequiredDecision.FieldsNeeded[i].ValidationRules = f.ValidationRules
|
||||
}
|
||||
|
||||
payload.RequiredDecision.DecisionType = requiredDecision.DecisionType
|
||||
payload.RequiredDecision.AffectsOtherSubtasks = requiredDecision.AffectsOtherSubtasks
|
||||
payload.RequiredDecision.RollbackPossible = requiredDecision.RollbackPossible
|
||||
payload.EscalationLevel = escalationLevel
|
||||
|
||||
deadline := types.Timestamp(h.getDeadline(escalationLevel).Format(time.RFC3339))
|
||||
payload.Deadline = &deadline
|
||||
|
||||
payloadBytes, _ := json.Marshal(payload)
|
||||
|
||||
return &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.GroupSubtaskEscalate),
|
||||
Sender: h.agentEndpoint,
|
||||
GroupID: groupID,
|
||||
Payload: payloadBytes,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// HiL Status Management
|
||||
// =============================================================================
|
||||
|
||||
// GetRequest returns a HiL request by ID
|
||||
func (h *HILProtocol) GetRequest(id string) (*HILRequest, bool) {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
req, ok := h.requests[id]
|
||||
return req, ok
|
||||
}
|
||||
|
||||
// ListRequests returns all HiL requests
|
||||
func (h *HILProtocol) ListRequests() []*HILRequest {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
|
||||
result := make([]*HILRequest, 0, len(h.requests))
|
||||
for _, req := range h.requests {
|
||||
result = append(result, req)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ListPendingRequests returns all pending HiL requests
|
||||
func (h *HILProtocol) ListPendingRequests() []*HILRequest {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
|
||||
result := make([]*HILRequest, 0)
|
||||
for _, req := range h.requests {
|
||||
if req.Status == HILStatusPending || req.Status == HILStatusWaiting {
|
||||
result = append(result, req)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// UpdateRequestStatus updates the status of a HiL request
|
||||
func (h *HILProtocol) UpdateRequestStatus(id string, status HILStatus) error {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
req, ok := h.requests[id]
|
||||
if !ok {
|
||||
return fmt.Errorf("HiL request not found: %s", id)
|
||||
}
|
||||
|
||||
req.Status = status
|
||||
req.UpdatedAt = time.Now()
|
||||
|
||||
if status == HILStatusApproved || status == HILStatusRejected {
|
||||
now := time.Now()
|
||||
req.DecidedAt = &now
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecordResponse records a human decision response
|
||||
func (h *HILProtocol) RecordResponse(id string, response *HILResponse) error {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
req, ok := h.requests[id]
|
||||
if !ok {
|
||||
return fmt.Errorf("HiL request not found: %s", id)
|
||||
}
|
||||
|
||||
req.Response = response
|
||||
req.Status = HILStatusApproved // or rejected based on action
|
||||
req.UpdatedAt = time.Now()
|
||||
now := time.Now()
|
||||
req.DecidedAt = &now
|
||||
|
||||
log.Printf("[HiL] Response recorded for %s: %s by %s", id, response.Action, response.UserName)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Timeout Management
|
||||
// =============================================================================
|
||||
|
||||
func (h *HILProtocol) getDeadline(escalationLevel int) time.Time {
|
||||
switch escalationLevel {
|
||||
case 1:
|
||||
return time.Now().Add(h.config.Level1Timeout)
|
||||
case 2:
|
||||
return time.Now().Add(h.config.Level2Timeout)
|
||||
case 3:
|
||||
return time.Now().Add(h.config.Level3Timeout)
|
||||
default:
|
||||
return time.Now().Add(h.config.DefaultTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
// CheckTimeouts checks for and handles timed out requests
|
||||
func (h *HILProtocol) CheckTimeouts() []*HILRequest {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
timedOut := make([]*HILRequest, 0)
|
||||
now := time.Now()
|
||||
|
||||
for _, req := range h.requests {
|
||||
if (req.Status == HILStatusPending || req.Status == HILStatusWaiting) && now.After(req.Deadline) {
|
||||
req.Status = HILStatusTimeout
|
||||
req.UpdatedAt = now
|
||||
timedOut = append(timedOut, req)
|
||||
log.Printf("[HiL] Request timed out: %s (task: %s)", req.ID, req.TaskID)
|
||||
}
|
||||
}
|
||||
|
||||
return timedOut
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Human Decision Panel (for frontend integration)
|
||||
// =============================================================================
|
||||
|
||||
// GetDecisionPanelData returns data needed to render a decision panel
|
||||
func (h *HILProtocol) GetDecisionPanelData(req *HILRequest) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"request_id": req.ID,
|
||||
"task_id": req.TaskID,
|
||||
"escalation_type": req.EscalationType,
|
||||
"escalation_level": req.EscalationLevel,
|
||||
"reason": req.Reason,
|
||||
"context": req.Context,
|
||||
"options": req.Options,
|
||||
"suggested_value": req.SuggestedValue,
|
||||
"deadline": req.Deadline.Format(time.RFC3339),
|
||||
"status": req.Status,
|
||||
"created_at": req.CreatedAt.Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
// CreateHumanDecisionPayload creates a HUMAN_DECISION payload
|
||||
func (h *HILProtocol) CreateHumanDecisionPayload(
|
||||
taskID string,
|
||||
replyTo string,
|
||||
user struct {
|
||||
UserID string
|
||||
UserName string
|
||||
Role string
|
||||
},
|
||||
decision struct {
|
||||
Action string
|
||||
ApprovedFields map[string]interface{}
|
||||
ModifiedFields map[string]interface{}
|
||||
SelectedOption any
|
||||
RejectionReason string
|
||||
},
|
||||
notes string,
|
||||
) *types.HumanDecisionPayload {
|
||||
payload := &types.HumanDecisionPayload{}
|
||||
payload.TaskID = taskID
|
||||
payload.DecisionID = fmt.Sprintf("decision-%d", time.Now().UnixNano())
|
||||
payload.ReplyTo = replyTo
|
||||
payload.DecidedBy.UserID = user.UserID
|
||||
payload.DecidedBy.UserName = user.UserName
|
||||
payload.DecidedBy.Role = user.Role
|
||||
payload.Decision.Action = decision.Action
|
||||
payload.Notes = notes
|
||||
payload.Timestamp = types.NowTimestamp()
|
||||
|
||||
switch decision.Action {
|
||||
case "approve":
|
||||
payload.Decision.ApprovedFields = decision.ApprovedFields
|
||||
case "reject":
|
||||
payload.Decision.RejectionReason = decision.RejectionReason
|
||||
case "select":
|
||||
payload.Decision.SelectedOption = decision.SelectedOption
|
||||
case "modify":
|
||||
payload.Decision.ModifiedFields = decision.ModifiedFields
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Utility Methods
|
||||
// =============================================================================
|
||||
|
||||
// IsHILRequired checks if a task requires human intervention
|
||||
func IsHILRequired(reasonCode string) bool {
|
||||
hilRequiredCodes := map[string]bool{
|
||||
"BRAND_STYLE": true,
|
||||
"CREATIVE_DIRECTION": true,
|
||||
"COMPLIANCE": true,
|
||||
"CAPABILITY_LACKING": true,
|
||||
"USER_REQUESTED": true,
|
||||
"HIGH_COST_RISK": true,
|
||||
}
|
||||
return hilRequiredCodes[reasonCode]
|
||||
}
|
||||
|
||||
// GetEscalationLevel determines escalation level based on reason code
|
||||
func GetEscalationLevel(reasonCode string) int {
|
||||
levelMap := map[string]int{
|
||||
"INFO_MISSING": 1,
|
||||
"CREATIVE_DIRECTION": 1,
|
||||
"BRAND_STYLE": 2,
|
||||
"COMPLIANCE": 2,
|
||||
"CAPABILITY_LACKING": 2,
|
||||
"USER_REQUESTED": 1,
|
||||
"HIGH_COST_RISK": 2,
|
||||
"RESOURCE_DEADLOCK": 2,
|
||||
"STRATEGIC_DECISION": 3,
|
||||
}
|
||||
|
||||
if level, ok := levelMap[reasonCode]; ok {
|
||||
return level
|
||||
}
|
||||
return 1 // Default to level 1
|
||||
}
|
||||
451
internal/routing/router.go
Normal file
451
internal/routing/router.go
Normal file
@@ -0,0 +1,451 @@
|
||||
package routing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"synapse/internal/agent/group"
|
||||
"synapse/internal/agent/p2p"
|
||||
"synapse/internal/hil"
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Message Router
|
||||
// =============================================================================
|
||||
|
||||
// Router handles routing of Synapse messages
|
||||
type Router struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
// Protocols
|
||||
p2pProtocol *p2p.P2PProtocol
|
||||
groupProtocol *group.GroupProtocol
|
||||
hilProtocol *hil.HILProtocol
|
||||
|
||||
// External routing
|
||||
externalRoutes map[string]string // system_id -> gateway endpoint
|
||||
|
||||
// Configuration
|
||||
config *RouterConfig
|
||||
}
|
||||
|
||||
// RouterConfig holds router configuration
|
||||
type RouterConfig struct {
|
||||
MaxHops int
|
||||
EnableCaching bool
|
||||
}
|
||||
|
||||
// DefaultRouterConfig returns default router configuration
|
||||
func DefaultRouterConfig() *RouterConfig {
|
||||
return &RouterConfig{
|
||||
MaxHops: 10,
|
||||
EnableCaching: true,
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// NewRouter creates a new message router
|
||||
// =============================================================================
|
||||
|
||||
func NewRouter(config *RouterConfig) *Router {
|
||||
if config == nil {
|
||||
config = DefaultRouterConfig()
|
||||
}
|
||||
return &Router{
|
||||
externalRoutes: make(map[string]string),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// SetP2PProtocol sets the P2P protocol handler
|
||||
func (r *Router) SetP2PProtocol(p *p2p.P2PProtocol) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.p2pProtocol = p
|
||||
}
|
||||
|
||||
// SetGroupProtocol sets the Group protocol handler
|
||||
func (r *Router) SetGroupProtocol(g *group.GroupProtocol) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.groupProtocol = g
|
||||
}
|
||||
|
||||
// SetHILProtocol sets the HiL protocol handler
|
||||
func (r *Router) SetHILProtocol(h *hil.HILProtocol) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.hilProtocol = h
|
||||
}
|
||||
|
||||
// RegisterExternalRoute registers an external system gateway
|
||||
func (r *Router) RegisterExternalRoute(systemID, endpoint string) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.externalRoutes[systemID] = endpoint
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// RouteMessage routes an incoming message to the appropriate handler
|
||||
// =============================================================================
|
||||
|
||||
func (r *Router) RouteMessage(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
// Validate message
|
||||
if err := r.validateMessage(msg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Route based on message category
|
||||
if isGroupMessage(msg.Type) {
|
||||
if r.groupProtocol == nil {
|
||||
return nil, fmt.Errorf("group protocol not configured")
|
||||
}
|
||||
return r.groupProtocol.HandleMessage(ctx, msg)
|
||||
}
|
||||
|
||||
if isP2PMessage(msg.Type) {
|
||||
if r.p2pProtocol == nil {
|
||||
return nil, fmt.Errorf("p2p protocol not configured")
|
||||
}
|
||||
return r.p2pProtocol.HandleMessage(ctx, msg)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("unknown message type: %s", msg.Type)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// SendMessage sends a message to a destination
|
||||
// =============================================================================
|
||||
|
||||
// MessageSender is the interface for sending messages
|
||||
type MessageSender interface {
|
||||
Send(ctx context.Context, endpoint string, msg *types.UnifiedSynapseMessage) error
|
||||
}
|
||||
|
||||
// TransportSender is used by the router to send messages
|
||||
var _ MessageSender = (*TransportSender)(nil)
|
||||
|
||||
// TransportSender is a placeholder for actual transport implementation
|
||||
type TransportSender struct {
|
||||
httpClient *HTTPClient
|
||||
}
|
||||
|
||||
// HTTPClient is a simple HTTP client for sending messages
|
||||
type HTTPClient struct {
|
||||
baseURL string
|
||||
timeoutMs int
|
||||
}
|
||||
|
||||
// Send sends a message via HTTP
|
||||
func (t *TransportSender) Send(ctx context.Context, endpoint string, msg *types.UnifiedSynapseMessage) error {
|
||||
if endpoint == "" {
|
||||
return fmt.Errorf("endpoint is required")
|
||||
}
|
||||
|
||||
_, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal message: %w", err)
|
||||
}
|
||||
|
||||
// In a real implementation, this would use net/http to send the message
|
||||
log.Printf("[Router] Sending message to %s: type=%s, id=%s", endpoint, msg.Type, msg.ID)
|
||||
|
||||
return nil // Placeholder - actual HTTP call would go here
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// CreateOutboundMessage creates a message for sending to a remote agent
|
||||
// =============================================================================
|
||||
|
||||
func (r *Router) CreateOutboundMessage(
|
||||
msgType string,
|
||||
sender types.AgentEndpoint,
|
||||
receiver *types.AgentEndpoint,
|
||||
payload any,
|
||||
correlationID string,
|
||||
) (*types.UnifiedSynapseMessage, error) {
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal payload: %w", err)
|
||||
}
|
||||
|
||||
msg := &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: msgType,
|
||||
Sender: sender,
|
||||
Receiver: receiver,
|
||||
CorrelationID: correlationID,
|
||||
Payload: payloadBytes,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}
|
||||
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// CreateTaskRequest creates a task request message
|
||||
// =============================================================================
|
||||
|
||||
func (r *Router) CreateTaskRequest(
|
||||
sender types.AgentEndpoint,
|
||||
receiver types.AgentEndpoint,
|
||||
taskID string,
|
||||
taskType string,
|
||||
taskPayload map[string]interface{},
|
||||
priority types.Priority,
|
||||
correlationID string,
|
||||
) (*types.UnifiedSynapseMessage, error) {
|
||||
payload := types.TaskRequestPayload{}
|
||||
payload.Task.ID = taskID
|
||||
payload.Task.Type = taskType
|
||||
payload.Task.Priority = priority
|
||||
payload.Task.Payload = taskPayload
|
||||
|
||||
return r.CreateOutboundMessage(
|
||||
string(types.P2PTaskRequest),
|
||||
sender,
|
||||
&receiver,
|
||||
payload,
|
||||
correlationID,
|
||||
)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// CreateTaskNeedHuman creates a need human message
|
||||
// =============================================================================
|
||||
|
||||
func (r *Router) CreateTaskNeedHuman(
|
||||
sender types.AgentEndpoint,
|
||||
receiver types.AgentEndpoint,
|
||||
taskID string,
|
||||
reasonCode, reasonMessage string,
|
||||
context struct {
|
||||
TaskSummary string
|
||||
CurrentProgress int
|
||||
BlockedReason string
|
||||
RelevantHistory []any
|
||||
},
|
||||
options []struct {
|
||||
Field string
|
||||
Value any
|
||||
ProsCons string
|
||||
Confidence int
|
||||
},
|
||||
suggestedValue any,
|
||||
escalationLevel int,
|
||||
correlationID string,
|
||||
) (*types.UnifiedSynapseMessage, error) {
|
||||
payload := types.TaskNeedHumanPayload{}
|
||||
payload.TaskID = taskID
|
||||
payload.Reason.Code = reasonCode
|
||||
payload.Reason.Message = reasonMessage
|
||||
payload.Context.TaskSummary = context.TaskSummary
|
||||
payload.Context.CurrentProgress = context.CurrentProgress
|
||||
payload.Context.BlockedReason = context.BlockedReason
|
||||
payload.Context.RelevantHistory = context.RelevantHistory
|
||||
|
||||
// Copy options
|
||||
payload.Options = make([]struct {
|
||||
Field string `json:"field"`
|
||||
Value any `json:"value"`
|
||||
ProsCons string `json:"pros_cons,omitempty"`
|
||||
Confidence int `json:"confidence,omitempty"`
|
||||
}, len(options))
|
||||
for i, opt := range options {
|
||||
payload.Options[i].Field = opt.Field
|
||||
payload.Options[i].Value = opt.Value
|
||||
payload.Options[i].ProsCons = opt.ProsCons
|
||||
payload.Options[i].Confidence = opt.Confidence
|
||||
}
|
||||
|
||||
payload.SuggestedValue = suggestedValue
|
||||
payload.EscalationLevel = escalationLevel
|
||||
|
||||
return r.CreateOutboundMessage(
|
||||
string(types.P2PTaskNeedHuman),
|
||||
sender,
|
||||
&receiver,
|
||||
payload,
|
||||
correlationID,
|
||||
)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// CreateGroupTaskSplit creates a group task split message
|
||||
// =============================================================================
|
||||
|
||||
func (r *Router) CreateGroupTaskSplit(
|
||||
sender types.AgentEndpoint,
|
||||
groupID string,
|
||||
originalTask struct {
|
||||
ID string
|
||||
Type string
|
||||
Requirements map[string]interface{}
|
||||
Deadline *types.Timestamp
|
||||
},
|
||||
subtasks []types.Subtask,
|
||||
mergeStrategy types.MergeStrategy,
|
||||
correlationID string,
|
||||
) (*types.UnifiedSynapseMessage, error) {
|
||||
payload := types.GroupTaskSplitPayload{}
|
||||
payload.OriginalTask.ID = originalTask.ID
|
||||
payload.OriginalTask.Type = originalTask.Type
|
||||
payload.OriginalTask.Requirements = originalTask.Requirements
|
||||
payload.OriginalTask.Deadline = originalTask.Deadline
|
||||
payload.Subtasks = subtasks
|
||||
payload.MergeStrategy = mergeStrategy
|
||||
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal payload: %w", err)
|
||||
}
|
||||
|
||||
msg := &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.GroupTaskSplit),
|
||||
Sender: sender,
|
||||
GroupID: groupID,
|
||||
Broadcast: false,
|
||||
CorrelationID: correlationID,
|
||||
Payload: payloadBytes,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}
|
||||
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// CreateGroupBroadcast creates a group broadcast message
|
||||
// =============================================================================
|
||||
|
||||
func (r *Router) CreateGroupBroadcast(
|
||||
sender types.AgentEndpoint,
|
||||
groupID string,
|
||||
msgType string,
|
||||
payload any,
|
||||
correlationID string,
|
||||
) (*types.UnifiedSynapseMessage, error) {
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal payload: %w", err)
|
||||
}
|
||||
|
||||
msg := &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: msgType,
|
||||
Sender: sender,
|
||||
GroupID: groupID,
|
||||
Broadcast: true,
|
||||
CorrelationID: correlationID,
|
||||
Payload: payloadBytes,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}
|
||||
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// CreateGroupVote creates a group vote message
|
||||
// =============================================================================
|
||||
|
||||
func (r *Router) CreateGroupVote(
|
||||
sender types.AgentEndpoint,
|
||||
groupID string,
|
||||
voteID string,
|
||||
question string,
|
||||
options []string,
|
||||
voters []string,
|
||||
threshold float64,
|
||||
deadline types.Timestamp,
|
||||
correlationID string,
|
||||
) (*types.UnifiedSynapseMessage, error) {
|
||||
payload := types.GroupVotePayload{}
|
||||
payload.VoteID = voteID
|
||||
payload.Question = question
|
||||
payload.Options = options
|
||||
payload.Voters = voters
|
||||
payload.Threshold = threshold
|
||||
payload.Deadline = deadline
|
||||
payload.Status = "open"
|
||||
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal payload: %w", err)
|
||||
}
|
||||
|
||||
msg := &types.UnifiedSynapseMessage{
|
||||
ID: types.GenerateMessageID(),
|
||||
Version: "1.0.0",
|
||||
Type: string(types.GroupVote),
|
||||
Sender: sender,
|
||||
GroupID: groupID,
|
||||
Broadcast: true,
|
||||
CorrelationID: correlationID,
|
||||
Payload: payloadBytes,
|
||||
Timestamp: types.NowTimestamp(),
|
||||
}
|
||||
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Validation
|
||||
// =============================================================================
|
||||
|
||||
func (r *Router) validateMessage(msg *types.UnifiedSynapseMessage) error {
|
||||
if msg.ID == "" {
|
||||
return types.ErrMessageFormatInvalidError
|
||||
}
|
||||
if msg.Sender.AgentID == "" {
|
||||
return types.NewSynapseError(types.ErrMessageFormatInvalid, "Missing sender agent_id", nil)
|
||||
}
|
||||
if msg.Sender.Endpoint == "" {
|
||||
return types.NewSynapseError(types.ErrMessageFormatInvalid, "Missing sender endpoint", nil)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Helper Functions
|
||||
// =============================================================================
|
||||
|
||||
func isP2PMessage(msgType string) bool {
|
||||
return strings.HasPrefix(msgType, "p2p:")
|
||||
}
|
||||
|
||||
func isGroupMessage(msgType string) bool {
|
||||
return strings.HasPrefix(msgType, "group:") || strings.HasPrefix(msgType, "inter_group:")
|
||||
}
|
||||
|
||||
// GetRoute determines the route for a message
|
||||
func (r *Router) GetRoute(msg *types.UnifiedSynapseMessage) (routeType string, target string, err error) {
|
||||
// P2P messages
|
||||
if msg.Receiver != nil {
|
||||
if msg.Receiver.SystemID != r.p2pProtocol.AgentEndpoint().SystemID {
|
||||
// External system
|
||||
if endpoint, ok := r.externalRoutes[msg.Receiver.SystemID]; ok {
|
||||
return "external", endpoint, nil
|
||||
}
|
||||
return "unknown", "", fmt.Errorf("no route for system: %s", msg.Receiver.SystemID)
|
||||
}
|
||||
return "local", msg.Receiver.AgentID, nil
|
||||
}
|
||||
|
||||
// Group messages
|
||||
if msg.GroupID != "" {
|
||||
return "group", msg.GroupID, nil
|
||||
}
|
||||
|
||||
return "unknown", "", fmt.Errorf("no route found for message")
|
||||
}
|
||||
611
internal/transport/multipart_polling.go
Normal file
611
internal/transport/multipart_polling.go
Normal file
@@ -0,0 +1,611 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Multipart Transport - 混合文本+文件传输
|
||||
// =============================================================================
|
||||
|
||||
// MultipartTransport handles multipart file transfers
|
||||
type MultipartTransport struct {
|
||||
mu sync.RWMutex
|
||||
client *http.Client
|
||||
timeout time.Duration
|
||||
authSecret string
|
||||
}
|
||||
|
||||
// NewMultipartTransport creates a new multipart transport
|
||||
func NewMultipartTransport(timeout time.Duration, authSecret string) *MultipartTransport {
|
||||
return &MultipartTransport{
|
||||
client: &http.Client{
|
||||
Timeout: timeout,
|
||||
},
|
||||
timeout: timeout,
|
||||
authSecret: authSecret,
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Multipart Message Sending
|
||||
// =============================================================================
|
||||
|
||||
// SendTaskWithFiles sends a task request with file attachments via multipart/form-data
|
||||
func (m *MultipartTransport) SendTaskWithFiles(
|
||||
ctx context.Context,
|
||||
endpoint string,
|
||||
msg *types.UnifiedSynapseMessage,
|
||||
files []types.FileContent,
|
||||
) error {
|
||||
var buf bytes.Buffer
|
||||
writer := multipart.NewWriter(&buf)
|
||||
|
||||
// 1. Write the main request JSON as the "request" part
|
||||
requestPart, err := writer.CreateFormField("request")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create request part: %w", err)
|
||||
}
|
||||
if err := json.NewEncoder(requestPart).Encode(msg); err != nil {
|
||||
return fmt.Errorf("failed to encode request: %w", err)
|
||||
}
|
||||
|
||||
// 2. Write each file as a separate part
|
||||
for _, file := range files {
|
||||
if file.TransferMode != types.TransferInline {
|
||||
continue // Skip URL-based files
|
||||
}
|
||||
|
||||
part, err := writer.CreateFormFile(file.Name, file.Name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file part %s: %w", file.Name, err)
|
||||
}
|
||||
|
||||
// For inline files, data is base64 encoded in file.Data
|
||||
// In real implementation, decode base64 and write binary
|
||||
// For now, just write the data as-is
|
||||
if file.Data != "" {
|
||||
part.Write([]byte(file.Data))
|
||||
}
|
||||
}
|
||||
|
||||
// Close the writer to finalize the boundary
|
||||
if err := writer.Close(); err != nil {
|
||||
return fmt.Errorf("failed to close writer: %w", err)
|
||||
}
|
||||
|
||||
// 3. Create HTTP request
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", endpoint, &buf)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
req.Header.Set("X-Synapse-Version", "1.0.0")
|
||||
req.Header.Set("X-Synapse-Agent", msg.Sender.AgentID)
|
||||
req.Header.Set("X-Synapse-System", msg.Sender.SystemID)
|
||||
|
||||
// 4. Send
|
||||
resp, err := m.client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to send request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 400 {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
log.Printf("[Multipart] Task sent with %d files to %s", len(files), endpoint)
|
||||
return nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Multipart Message Parsing
|
||||
// =============================================================================
|
||||
|
||||
// ParseMultipartRequest parses a multipart request with message + files
|
||||
func (m *MultipartTransport) ParseMultipartRequest(r *http.Request) (
|
||||
*types.UnifiedSynapseMessage,
|
||||
[]types.FileContent,
|
||||
error,
|
||||
) {
|
||||
// Limit max size (100MB default)
|
||||
if err := r.ParseMultipartForm(100 << 20); err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to parse multipart: %w", err)
|
||||
}
|
||||
|
||||
// 1. Parse the message JSON
|
||||
requestValue := r.FormValue("request")
|
||||
if requestValue == "" {
|
||||
return nil, nil, fmt.Errorf("missing 'request' field")
|
||||
}
|
||||
|
||||
var msg types.UnifiedSynapseMessage
|
||||
if err := json.Unmarshal([]byte(requestValue), &msg); err != nil {
|
||||
return nil, nil, fmt.Errorf("invalid request JSON: %w", err)
|
||||
}
|
||||
|
||||
// 2. Parse file attachments
|
||||
var files []types.FileContent
|
||||
for _, fileHeaders := range r.MultipartForm.File {
|
||||
for _, fh := range fileHeaders {
|
||||
file, err := fh.Open()
|
||||
if err != nil {
|
||||
log.Printf("[Multipart] Failed to open file %s: %v", fh.Filename, err)
|
||||
continue
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(file)
|
||||
file.Close()
|
||||
if err != nil {
|
||||
log.Printf("[Multipart] Failed to read file %s: %v", fh.Filename, err)
|
||||
continue
|
||||
}
|
||||
|
||||
mimeType := fh.Header.Get("Content-Type")
|
||||
if mimeType == "" {
|
||||
mimeType = types.InferMimeType(fh.Filename)
|
||||
}
|
||||
|
||||
fc := types.FileContent{
|
||||
ContentBase: types.ContentBase{
|
||||
MIMEType: mimeType,
|
||||
Encoding: types.EncodingBase64,
|
||||
Size: fh.Size,
|
||||
TransferMode: types.TransferInline,
|
||||
},
|
||||
Name: fh.Filename,
|
||||
Data: string(data), // In real impl: base64 encode
|
||||
}
|
||||
files = append(files, fc)
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("[Multipart] Parsed request: %d files received", len(files))
|
||||
return &msg, files, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Polling Client - 轮询客户端
|
||||
// =============================================================================
|
||||
|
||||
// PollingClient handles task status polling
|
||||
type PollingClient struct {
|
||||
mu sync.RWMutex
|
||||
client *http.Client
|
||||
baseURL string
|
||||
authSecret string
|
||||
|
||||
// Polling configuration
|
||||
initialInterval time.Duration
|
||||
maxInterval time.Duration
|
||||
backoffFactor float64
|
||||
maxDuration time.Duration
|
||||
|
||||
// Active polls
|
||||
activePolls map[string]*pollContext
|
||||
}
|
||||
|
||||
type pollContext struct {
|
||||
taskID string
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
interval time.Duration
|
||||
lastStatus string
|
||||
lastProgress int
|
||||
callback func(status *types.TaskInfo) bool // returns true to stop polling
|
||||
}
|
||||
|
||||
// PollingClientConfig holds configuration for the polling client
|
||||
type PollingClientConfig struct {
|
||||
BaseURL string
|
||||
AuthSecret string
|
||||
InitialInterval time.Duration
|
||||
MaxInterval time.Duration
|
||||
BackoffFactor float64
|
||||
MaxDuration time.Duration
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// DefaultPollingClientConfig returns default polling configuration
|
||||
func DefaultPollingClientConfig() *PollingClientConfig {
|
||||
return &PollingClientConfig{
|
||||
InitialInterval: 5 * time.Second,
|
||||
MaxInterval: 60 * time.Second,
|
||||
BackoffFactor: 2.0,
|
||||
MaxDuration: 2 * time.Hour,
|
||||
Timeout: 30 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// NewPollingClient creates a new polling client
|
||||
func NewPollingClient(config *PollingClientConfig) *PollingClient {
|
||||
if config == nil {
|
||||
config = DefaultPollingClientConfig()
|
||||
}
|
||||
return &PollingClient{
|
||||
client: &http.Client{
|
||||
Timeout: config.Timeout,
|
||||
},
|
||||
baseURL: config.BaseURL,
|
||||
authSecret: config.AuthSecret,
|
||||
initialInterval: config.InitialInterval,
|
||||
maxInterval: config.MaxInterval,
|
||||
backoffFactor: config.BackoffFactor,
|
||||
maxDuration: config.MaxDuration,
|
||||
activePolls: make(map[string]*pollContext),
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Single Poll - 单次轮询
|
||||
// =============================================================================
|
||||
|
||||
// GetTaskStatus polls for a task's current status
|
||||
func (p *PollingClient) GetTaskStatus(ctx context.Context, taskID string) (*types.TaskInfo, error) {
|
||||
url := fmt.Sprintf("%s/synapse/task/%s", p.baseURL, taskID)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("X-Synapse-Version", "1.0.0")
|
||||
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == 304 {
|
||||
return nil, nil // Not modified
|
||||
}
|
||||
|
||||
if resp.StatusCode >= 400 {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var result types.TaskStatusResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||||
}
|
||||
|
||||
if !result.Success {
|
||||
return nil, fmt.Errorf("API error: %s", result.Error.Message)
|
||||
}
|
||||
|
||||
return result.Task, nil
|
||||
}
|
||||
|
||||
// ListTasks lists tasks with filtering
|
||||
func (p *PollingClient) ListTasks(ctx context.Context, status string, limit, offset int) (*types.TaskListResponse, error) {
|
||||
url := fmt.Sprintf("%s/synapse/tasks?status=%s&limit=%d&offset=%d",
|
||||
p.baseURL, status, limit, offset)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var result types.TaskListResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||||
}
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
// GetTaskEvents gets incremental task events
|
||||
func (p *PollingClient) GetTaskEvents(ctx context.Context, taskID, since string) (*types.TaskEventsResponse, error) {
|
||||
url := fmt.Sprintf("%s/synapse/task/%s/events", p.baseURL, taskID)
|
||||
if since != "" {
|
||||
url += fmt.Sprintf("?since=%s", since)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var result types.TaskEventsResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||||
}
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Continuous Polling - 持续轮询
|
||||
// =============================================================================
|
||||
|
||||
// StartPolling starts continuous polling for a task
|
||||
func (p *PollingClient) StartPolling(
|
||||
ctx context.Context,
|
||||
taskID string,
|
||||
callback func(status *types.TaskInfo) bool,
|
||||
) error {
|
||||
p.mu.Lock()
|
||||
if _, exists := p.activePolls[taskID]; exists {
|
||||
p.mu.Unlock()
|
||||
return fmt.Errorf("polling already active for task %s", taskID)
|
||||
}
|
||||
|
||||
pollCtx, cancel := context.WithTimeout(ctx, p.maxDuration)
|
||||
pc := &pollContext{
|
||||
taskID: taskID,
|
||||
ctx: pollCtx,
|
||||
cancel: cancel,
|
||||
interval: p.initialInterval,
|
||||
callback: callback,
|
||||
}
|
||||
p.activePolls[taskID] = pc
|
||||
p.mu.Unlock()
|
||||
|
||||
go p.pollLoop(pc)
|
||||
return nil
|
||||
}
|
||||
|
||||
// StopPolling stops polling for a task
|
||||
func (p *PollingClient) StopPolling(taskID string) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if pc, exists := p.activePolls[taskID]; exists {
|
||||
pc.cancel()
|
||||
delete(p.activePolls, taskID)
|
||||
}
|
||||
}
|
||||
|
||||
// pollLoop is the main polling loop
|
||||
func (p *PollingClient) pollLoop(pc *pollContext) {
|
||||
defer func() {
|
||||
p.mu.Lock()
|
||||
delete(p.activePolls, pc.taskID)
|
||||
p.mu.Unlock()
|
||||
}()
|
||||
|
||||
ticker := time.NewTicker(pc.interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
consecutiveNoChange := 0
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-pc.ctx.Done():
|
||||
log.Printf("[Polling] Stopped for task %s: %v", pc.taskID, pc.ctx.Err())
|
||||
return
|
||||
|
||||
case <-ticker.C:
|
||||
status, err := p.GetTaskStatus(pc.ctx, pc.taskID)
|
||||
if err != nil {
|
||||
log.Printf("[Polling] Error for task %s: %v", pc.taskID, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if status == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if status or progress changed
|
||||
changed := status.Status != pc.lastStatus || status.Progress != pc.lastProgress
|
||||
if changed {
|
||||
consecutiveNoChange = 0
|
||||
pc.interval = p.initialInterval
|
||||
ticker.Reset(pc.interval)
|
||||
} else {
|
||||
consecutiveNoChange++
|
||||
// Apply backoff after 3 consecutive no-change polls
|
||||
if consecutiveNoChange >= 3 {
|
||||
newInterval := time.Duration(float64(pc.interval) * p.backoffFactor)
|
||||
if newInterval > p.maxInterval {
|
||||
newInterval = p.maxInterval
|
||||
}
|
||||
if newInterval != pc.interval {
|
||||
pc.interval = newInterval
|
||||
ticker.Reset(pc.interval)
|
||||
log.Printf("[Polling] Backoff to %v for task %s", pc.interval, pc.taskID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pc.lastStatus = status.Status
|
||||
pc.lastProgress = status.Progress
|
||||
|
||||
// Call callback
|
||||
if pc.callback(status) {
|
||||
log.Printf("[Polling] Callback returned stop for task %s", pc.taskID)
|
||||
return
|
||||
}
|
||||
|
||||
// Check terminal states
|
||||
if status.Status == "completed" || status.Status == "failed" ||
|
||||
status.Status == "cancelled" || status.Status == "rejected" {
|
||||
log.Printf("[Polling] Task %s reached terminal state: %s", pc.taskID, status.Status)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Capability Query - 能力查询(同步)
|
||||
// =============================================================================
|
||||
|
||||
// QueryCapabilities queries an agent's capabilities synchronously
|
||||
func (p *PollingClient) QueryCapabilities(ctx context.Context, baseURL string) (*types.AgentCapabilities, error) {
|
||||
url := fmt.Sprintf("%s/synapse/capabilities", baseURL)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 400 {
|
||||
return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var result types.CapabilitiesResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||||
}
|
||||
|
||||
if !result.Success {
|
||||
return nil, fmt.Errorf("API error: %s", result.Error.Message)
|
||||
}
|
||||
|
||||
return result.Data, nil
|
||||
}
|
||||
|
||||
// HealthCheck checks if an agent is reachable
|
||||
func (p *PollingClient) HealthCheck(ctx context.Context, baseURL string) (bool, error) {
|
||||
url := fmt.Sprintf("%s/synapse/health", baseURL)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return false, nil
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
return resp.StatusCode == 200, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Hybrid Mode - 混合模式 (Callback + Polling Fallback)
|
||||
// =============================================================================
|
||||
|
||||
// HybridTransport combines callback-based push with polling-based fallback
|
||||
type HybridTransport struct {
|
||||
callbackTransport *HTTPTransport
|
||||
pollingClient *PollingClient
|
||||
mu sync.RWMutex
|
||||
pendingTasks map[string]*hybridTaskState
|
||||
}
|
||||
|
||||
type hybridTaskState struct {
|
||||
taskID string
|
||||
callbackOK bool
|
||||
pollingActive bool
|
||||
lastStatus string
|
||||
}
|
||||
|
||||
// NewHybridTransport creates a new hybrid transport
|
||||
func NewHybridTransport(callback *HTTPTransport, polling *PollingClient) *HybridTransport {
|
||||
return &HybridTransport{
|
||||
callbackTransport: callback,
|
||||
pollingClient: polling,
|
||||
pendingTasks: make(map[string]*hybridTaskState),
|
||||
}
|
||||
}
|
||||
|
||||
// SendTaskWithHybridFallback sends a task request and sets up both callback and polling
|
||||
func (h *HybridTransport) SendTaskWithHybridFallback(
|
||||
ctx context.Context,
|
||||
endpoint string,
|
||||
msg *types.UnifiedSynapseMessage,
|
||||
callback func(status *types.TaskInfo),
|
||||
) error {
|
||||
// 1. First, try callback-based approach
|
||||
err := h.callbackTransport.Send(ctx, endpoint, msg)
|
||||
if err != nil {
|
||||
log.Printf("[Hybrid] Direct send failed, using polling only: %v", err)
|
||||
}
|
||||
|
||||
// 2. Extract task ID from payload
|
||||
var payload types.TaskRequestPayload
|
||||
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
|
||||
return fmt.Errorf("failed to extract task ID: %w", err)
|
||||
}
|
||||
taskID := payload.Task.ID
|
||||
|
||||
// 3. Set up polling as fallback after 30s
|
||||
h.mu.Lock()
|
||||
h.pendingTasks[taskID] = &hybridTaskState{
|
||||
taskID: taskID,
|
||||
callbackOK: err == nil,
|
||||
pollingActive: false,
|
||||
}
|
||||
h.mu.Unlock()
|
||||
|
||||
// Start polling after a delay if callback hasn't been received
|
||||
go func() {
|
||||
select {
|
||||
case <-time.After(30 * time.Second):
|
||||
h.mu.RLock()
|
||||
state, exists := h.pendingTasks[taskID]
|
||||
h.mu.RUnlock()
|
||||
|
||||
if exists && !state.callbackOK {
|
||||
log.Printf("[Hybrid] Callback not received for %s, starting polling fallback", taskID)
|
||||
h.pollingClient.StartPolling(ctx, taskID, func(status *types.TaskInfo) bool {
|
||||
if callback != nil {
|
||||
callback(status)
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// NotifyCallbackReceived notifies that a callback was received (stops polling fallback)
|
||||
func (h *HybridTransport) NotifyCallbackReceived(taskID string) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
if state, exists := h.pendingTasks[taskID]; exists {
|
||||
state.callbackOK = true
|
||||
if state.pollingActive {
|
||||
h.pollingClient.StopPolling(taskID)
|
||||
state.pollingActive = false
|
||||
}
|
||||
log.Printf("[Hybrid] Callback received for %s, polling disabled", taskID)
|
||||
}
|
||||
}
|
||||
420
internal/transport/transport.go
Normal file
420
internal/transport/transport.go
Normal file
@@ -0,0 +1,420 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// HTTP Transport
|
||||
// =============================================================================
|
||||
|
||||
// HTTPTransport implements HTTP-based transport for Synapse messages
|
||||
type HTTPTransport struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
// Configuration
|
||||
baseURL string
|
||||
timeout time.Duration
|
||||
maxRetries int
|
||||
retryDelay time.Duration
|
||||
|
||||
// HTTP Client
|
||||
client *http.Client
|
||||
|
||||
// Security
|
||||
authSecret string
|
||||
|
||||
// Callbacks
|
||||
callbackEndpoint string
|
||||
callbackHandler MessageCallbackHandler
|
||||
}
|
||||
|
||||
// HTTPTransportConfig holds HTTP transport configuration
|
||||
type HTTPTransportConfig struct {
|
||||
BaseURL string
|
||||
Timeout time.Duration
|
||||
MaxRetries int
|
||||
RetryDelay time.Duration
|
||||
AuthSecret string
|
||||
}
|
||||
|
||||
// DefaultHTTPTransportConfig returns default HTTP transport configuration
|
||||
func DefaultHTTPTransportConfig() *HTTPTransportConfig {
|
||||
return &HTTPTransportConfig{
|
||||
Timeout: 30 * time.Second,
|
||||
MaxRetries: 5,
|
||||
RetryDelay: 2 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// NewHTTPTransport creates a new HTTP transport
|
||||
func NewHTTPTransport(config *HTTPTransportConfig) *HTTPTransport {
|
||||
if config == nil {
|
||||
config = DefaultHTTPTransportConfig()
|
||||
}
|
||||
|
||||
t := &HTTPTransport{
|
||||
baseURL: config.BaseURL,
|
||||
timeout: config.Timeout,
|
||||
maxRetries: config.MaxRetries,
|
||||
retryDelay: config.RetryDelay,
|
||||
authSecret: config.AuthSecret,
|
||||
client: &http.Client{
|
||||
Timeout: config.Timeout,
|
||||
},
|
||||
}
|
||||
|
||||
return t
|
||||
}
|
||||
|
||||
// SetCallbackHandler sets the handler for incoming callbacks
|
||||
func (t *HTTPTransport) SetCallbackHandler(handler MessageCallbackHandler) {
|
||||
t.callbackHandler = handler
|
||||
}
|
||||
|
||||
// SetCallbackEndpoint sets the endpoint for receiving callbacks
|
||||
func (t *HTTPTransport) SetCallbackEndpoint(endpoint string) {
|
||||
t.callbackEndpoint = endpoint
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Message Sending
|
||||
// =============================================================================
|
||||
|
||||
// Send sends a message via HTTP POST
|
||||
func (t *HTTPTransport) Send(ctx context.Context, endpoint string, msg *types.UnifiedSynapseMessage) error {
|
||||
if endpoint == "" {
|
||||
return fmt.Errorf("endpoint is required")
|
||||
}
|
||||
|
||||
// Add signature if secret is configured
|
||||
if t.authSecret != "" {
|
||||
t.signMessage(msg)
|
||||
}
|
||||
|
||||
// Marshal message
|
||||
body, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal message: %w", err)
|
||||
}
|
||||
|
||||
// Create request
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
// Set headers
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Synapse-Version", "1.0.0")
|
||||
req.Header.Set("X-Synapse-Agent", msg.Sender.AgentID)
|
||||
req.Header.Set("X-Synapse-System", msg.Sender.SystemID)
|
||||
|
||||
if msg.Signature != "" {
|
||||
req.Header.Set("X-Synapse-Signature", msg.Signature)
|
||||
}
|
||||
|
||||
// Send with retries
|
||||
var lastErr error
|
||||
for i := 0; i < t.maxRetries; i++ {
|
||||
if i > 0 {
|
||||
delay := t.retryDelay * time.Duration(1<<uint(i-1))
|
||||
log.Printf("[Transport] Retrying request (%d/%d) after %v", i, t.maxRetries, delay)
|
||||
time.Sleep(delay)
|
||||
}
|
||||
|
||||
resp, err := t.client.Do(req)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
log.Printf("[Transport] Request failed: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Read response
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
||||
log.Printf("[Transport] Message sent successfully: %s to %s", msg.ID, endpoint)
|
||||
return nil
|
||||
}
|
||||
|
||||
lastErr = fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(respBody))
|
||||
log.Printf("[Transport] Request failed: %v", lastErr)
|
||||
}
|
||||
|
||||
return fmt.Errorf("failed to send message after %d retries: %w", t.maxRetries, lastErr)
|
||||
}
|
||||
|
||||
// SendWithCallback sends a message and waits for callback response
|
||||
func (t *HTTPTransport) SendWithCallback(
|
||||
ctx context.Context,
|
||||
endpoint string,
|
||||
msg *types.UnifiedSynapseMessage,
|
||||
timeout time.Duration,
|
||||
) (*types.UnifiedSynapseMessage, error) {
|
||||
// Create channel for response
|
||||
respChan := make(chan *types.UnifiedSynapseMessage, 1)
|
||||
errChan := make(chan error, 1)
|
||||
|
||||
// Register callback handler for this message
|
||||
correlationID := msg.CorrelationID
|
||||
if correlationID == "" {
|
||||
correlationID = msg.ID
|
||||
}
|
||||
|
||||
// Start timeout goroutine
|
||||
go func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
errChan <- ctx.Err()
|
||||
case <-time.After(timeout):
|
||||
errChan <- fmt.Errorf("timeout waiting for response")
|
||||
}
|
||||
}()
|
||||
|
||||
// Send message
|
||||
if err := t.Send(ctx, endpoint, msg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Wait for response
|
||||
select {
|
||||
case resp := <-respChan:
|
||||
return resp, nil
|
||||
case err := <-errChan:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Message Reception
|
||||
// =============================================================================
|
||||
|
||||
// MessageCallbackHandler is the interface for handling incoming messages
|
||||
type MessageCallbackHandler interface {
|
||||
HandleMessage(msg *types.UnifiedSynapseMessage) error
|
||||
}
|
||||
|
||||
// HandleCallback handles an incoming callback message (HTTP POST)
|
||||
func (t *HTTPTransport) HandleCallback(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "POST" {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// Read body
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to read body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
r.Body.Close()
|
||||
|
||||
// Parse message
|
||||
var msg types.UnifiedSynapseMessage
|
||||
if err := json.Unmarshal(body, &msg); err != nil {
|
||||
http.Error(w, "invalid JSON", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Verify signature if configured
|
||||
if t.authSecret != "" && msg.Signature != "" {
|
||||
if !t.verifySignature(body, msg.Signature) {
|
||||
http.Error(w, "invalid signature", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Handle message
|
||||
if t.callbackHandler != nil {
|
||||
if err := t.callbackHandler.HandleMessage(&msg); err != nil {
|
||||
log.Printf("[Transport] Failed to handle message: %v", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Send success response
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": true,
|
||||
"message": "received",
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// HTTP Server
|
||||
// =============================================================================
|
||||
|
||||
// Server is an HTTP server for Synapse transport
|
||||
type Server struct {
|
||||
transport *HTTPTransport
|
||||
mux *http.ServeMux
|
||||
server *http.Server
|
||||
}
|
||||
|
||||
// NewServer creates a new HTTP server for Synapse transport
|
||||
func NewServer(addr string, transport *HTTPTransport) *Server {
|
||||
mux := http.NewServeMux()
|
||||
server := &Server{
|
||||
transport: transport,
|
||||
mux: mux,
|
||||
server: &http.Server{
|
||||
Addr: addr,
|
||||
Handler: mux,
|
||||
},
|
||||
}
|
||||
|
||||
// Register callback endpoint
|
||||
mux.HandleFunc("/synapse/callback", transport.HandleCallback)
|
||||
mux.HandleFunc("/synapse/health", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"status":"ok"}`))
|
||||
})
|
||||
|
||||
return server
|
||||
}
|
||||
|
||||
// Start starts the HTTP server
|
||||
func (s *Server) Start() error {
|
||||
log.Printf("[Transport] Starting HTTP server on %s", s.server.Addr)
|
||||
return s.server.ListenAndServe()
|
||||
}
|
||||
|
||||
// Stop stops the HTTP server
|
||||
func (s *Server) Stop(ctx context.Context) error {
|
||||
return s.server.Shutdown(ctx)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Security
|
||||
// =============================================================================
|
||||
|
||||
func (t *HTTPTransport) signMessage(msg *types.UnifiedSynapseMessage) {
|
||||
// Create canonical body (message without signature)
|
||||
msgCopy := *msg
|
||||
msgCopy.Signature = ""
|
||||
|
||||
body, _ := json.Marshal(msgCopy)
|
||||
|
||||
// Compute HMAC-SHA256
|
||||
h := hmac.New(sha256.New, []byte(t.authSecret))
|
||||
h.Write(body)
|
||||
signature := hex.EncodeToString(h.Sum(nil))
|
||||
|
||||
msg.Signature = signature
|
||||
}
|
||||
|
||||
func (t *HTTPTransport) verifySignature(body []byte, signature string) bool {
|
||||
h := hmac.New(sha256.New, []byte(t.authSecret))
|
||||
h.Write(body)
|
||||
expected := hex.EncodeToString(h.Sum(nil))
|
||||
|
||||
return hmac.Equal([]byte(strings.ToLower(signature)), []byte(strings.ToLower(expected)))
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Callback Sender (implements p2p.CallbackSender)
|
||||
// =============================================================================
|
||||
|
||||
// HTTPCallbackSender implements p2p.CallbackSender using HTTP transport
|
||||
type HTTPCallbackSender struct {
|
||||
transport *HTTPTransport
|
||||
}
|
||||
|
||||
// NewHTTPCallbackSender creates a new HTTP callback sender
|
||||
func NewHTTPCallbackSender(t *HTTPTransport) *HTTPCallbackSender {
|
||||
return &HTTPCallbackSender{transport: t}
|
||||
}
|
||||
|
||||
// SendCallback sends a callback message
|
||||
func (s *HTTPCallbackSender) SendCallback(ctx context.Context, endpoint string, msg *types.UnifiedSynapseMessage) error {
|
||||
if endpoint == "" && msg.Receiver != nil {
|
||||
endpoint = msg.Receiver.Endpoint
|
||||
}
|
||||
return s.transport.Send(ctx, endpoint, msg)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// WebSocket Transport (for future extension)
|
||||
// =============================================================================
|
||||
|
||||
// WebSocketConfig holds WebSocket transport configuration
|
||||
type WebSocketConfig struct {
|
||||
URL string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// WebSocketTransport implements WebSocket-based transport
|
||||
type WebSocketTransport struct {
|
||||
mu sync.RWMutex
|
||||
config *WebSocketConfig
|
||||
handler MessageCallbackHandler
|
||||
}
|
||||
|
||||
// NewWebSocketTransport creates a new WebSocket transport
|
||||
func NewWebSocketTransport(config *WebSocketConfig) *WebSocketTransport {
|
||||
return &WebSocketTransport{
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// SetMessageHandler sets the message handler
|
||||
func (t *WebSocketTransport) SetMessageHandler(handler MessageCallbackHandler) {
|
||||
t.handler = handler
|
||||
}
|
||||
|
||||
// Connect establishes a WebSocket connection
|
||||
func (t *WebSocketTransport) Connect(ctx context.Context) error {
|
||||
// Placeholder for WebSocket implementation
|
||||
// In a real implementation, this would use gorilla/websocket
|
||||
log.Printf("[Transport] WebSocket connect to %s (placeholder)", t.config.URL)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Send sends a message via WebSocket
|
||||
func (t *WebSocketTransport) Send(ctx context.Context, msg *types.UnifiedSynapseMessage) error {
|
||||
// Placeholder for WebSocket send implementation
|
||||
log.Printf("[Transport] WebSocket send (placeholder): %s", msg.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Message Utilities
|
||||
// =============================================================================
|
||||
|
||||
// CreateSuccessResponse creates a success response
|
||||
func CreateSuccessResponse(msgID string) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"success": true,
|
||||
"message": "received",
|
||||
"id": msgID,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateErrorResponse creates an error response
|
||||
func CreateErrorResponse(code int, message string) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"success": false,
|
||||
"error": map[string]interface{}{
|
||||
"code": code,
|
||||
"message": message,
|
||||
},
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user