灵隙(synapse) v1.0.0 版本

This commit is contained in:
lychang
2026-06-28 03:24:26 +08:00
parent 88b606b9ca
commit 812f68d5aa
48 changed files with 5566 additions and 1499 deletions

View 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
}

View 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
}

View 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")
}
}