Files
synapse/sdk/a2a/client.go
2026-06-27 22:17:15 +08:00

460 lines
13 KiB
Go

package a2a
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"time"
"synapse/types"
)
// =============================================================================
// Synapse P2P SDK (灵隙协议)
// Agent 间点对点通信客户端 SDK
// 基于 A2A 协议:两个 Agent 之间进行点对点任务协作
// =============================================================================
// MessageCallbackHandler 消息回调处理器接口
type MessageCallbackHandler interface {
HandleTaskRequest(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error)
HandleTaskStatusUpdate(ctx context.Context, msg *types.UnifiedSynapseMessage) error
HandleTaskComplete(ctx context.Context, msg *types.UnifiedSynapseMessage) error
HandleTaskFailed(ctx context.Context, msg *types.UnifiedSynapseMessage) error
HandleNeedHuman(ctx context.Context, msg *types.UnifiedSynapseMessage) error
}
// Client 灵隙 点对点通信客户端
type Client struct {
agentEndpoint types.AgentEndpoint
authSecret string
callbackHandler MessageCallbackHandler
tasks map[string]*P2PTaskState
tasksMu sync.RWMutex
httpClient *http.Client
}
// ClientConfig 灵隙 客户端配置
type ClientConfig struct {
AgentEndpoint types.AgentEndpoint
AuthSecret string
CallbackPort int
Timeout time.Duration
MaxRetries int
}
// P2PTaskState P2P 任务状态
type P2PTaskState struct {
TaskID string
Status types.P2PTaskStatus
Progress int
Message string
Result any
Error *types.SynapseError
}
// NewClient 创建新的 灵隙 客户端
func NewClient(config *ClientConfig) (*Client, error) {
if config.Timeout == 0 {
config.Timeout = 30 * time.Second
}
return &Client{
agentEndpoint: config.AgentEndpoint,
authSecret: config.AuthSecret,
tasks: make(map[string]*P2PTaskState),
httpClient: &http.Client{Timeout: config.Timeout},
}, nil
}
// SetMessageHandler 设置消息回调处理器
func (c *Client) SetMessageHandler(handler MessageCallbackHandler) {
c.callbackHandler = handler
}
// =============================================================================
// 任务状态管理
// =============================================================================
// GetTaskState 获取任务状态
func (c *Client) GetTaskState(taskID string) (*P2PTaskState, bool) {
c.tasksMu.RLock()
defer c.tasksMu.RUnlock()
state, ok := c.tasks[taskID]
return state, ok
}
// ListTasks 列出所有任务
func (c *Client) ListTasks() map[string]*P2PTaskState {
c.tasksMu.RLock()
defer c.tasksMu.RUnlock()
result := make(map[string]*P2PTaskState, len(c.tasks))
for k, v := range c.tasks {
result[k] = v
}
return result
}
func (c *Client) setTaskState(taskID string, status types.P2PTaskStatus, progress int, message string) {
c.tasksMu.Lock()
defer c.tasksMu.Unlock()
if _, ok := c.tasks[taskID]; !ok {
c.tasks[taskID] = &P2PTaskState{TaskID: taskID}
}
c.tasks[taskID].Status = status
c.tasks[taskID].Progress = progress
c.tasks[taskID].Message = message
}
func (c *Client) setTaskResult(taskID string, result any) {
c.tasksMu.Lock()
defer c.tasksMu.Unlock()
if state, ok := c.tasks[taskID]; ok {
state.Result = result
}
}
func (c *Client) setTaskError(taskID string, err *types.SynapseError) {
c.tasksMu.Lock()
defer c.tasksMu.Unlock()
if state, ok := c.tasks[taskID]; ok {
state.Error = err
}
}
// =============================================================================
// 消息发送
// =============================================================================
// SendTaskRequest 发送任务请求
func (c *Client) SendTaskRequest(ctx context.Context, target types.AgentEndpoint, taskType string, payload map[string]any) (string, error) {
taskID := types.GenerateTaskID()
taskReq := types.TaskRequestPayload{}
taskReq.Task.ID = taskID
taskReq.Task.Type = taskType
taskReq.Task.Priority = types.PriorityNormal
taskReq.Task.Payload = payload
payloadBytes, _ := json.Marshal(taskReq)
msg := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PTaskRequest),
Sender: c.agentEndpoint,
Receiver: &target,
Payload: payloadBytes,
Priority: types.PriorityNormal,
Timestamp: types.NowTimestamp(),
}
c.setTaskState(taskID, types.P2PStatusPending, 0, "任务已发送")
err := c.sendMessage(ctx, target.Endpoint, msg)
if err != nil {
return "", fmt.Errorf("failed to send task request: %w", err)
}
return taskID, nil
}
// SendTaskCancel 发送任务取消
func (c *Client) SendTaskCancel(ctx context.Context, target types.AgentEndpoint, taskID, reason string) error {
cancelPayload := types.TaskCancelPayload{
TaskID: taskID,
Reason: reason,
CancelledBy: c.agentEndpoint.AgentID,
}
payloadBytes, _ := json.Marshal(cancelPayload)
msg := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PTaskCancel),
Sender: c.agentEndpoint,
Receiver: &target,
Payload: payloadBytes,
Timestamp: types.NowTimestamp(),
}
c.setTaskState(taskID, types.P2PStatusCancelled, 0, "任务已取消")
return c.sendMessage(ctx, target.Endpoint, msg)
}
// SendHumanDecision 发送人类决策结果
func (c *Client) SendHumanDecision(ctx context.Context, target types.AgentEndpoint, taskID string, decision types.HumanDecisionPayload) error {
payloadBytes, _ := json.Marshal(decision)
msg := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PHumanDecision),
Sender: c.agentEndpoint,
Receiver: &target,
Payload: payloadBytes,
Timestamp: types.NowTimestamp(),
}
return c.sendMessage(ctx, target.Endpoint, msg)
}
// SendCapabilityQuery 查询对方能力
func (c *Client) SendCapabilityQuery(ctx context.Context, target types.AgentEndpoint) ([]string, error) {
msg := &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: "1.0.0",
Type: string(types.P2PCapabilityQuery),
Sender: c.agentEndpoint,
Receiver: &target,
Payload: []byte("{}"),
Timestamp: types.NowTimestamp(),
}
respMsg, err := c.sendRequest(ctx, target.Endpoint, msg)
if err != nil {
return nil, fmt.Errorf("failed to query capabilities: %w", err)
}
var resp struct {
Capabilities []string `json:"capabilities"`
}
if err := json.Unmarshal(respMsg.Payload, &resp); err != nil {
return nil, fmt.Errorf("failed to parse capabilities: %w", err)
}
return resp.Capabilities, nil
}
// =============================================================================
// 消息签名与验证
// =============================================================================
func (c *Client) signMessage(msg *types.UnifiedSynapseMessage) string {
if c.authSecret == "" {
return ""
}
h := hmac.New(sha256.New, []byte(c.authSecret))
h.Write([]byte(msg.ID + "." + string(msg.Payload)))
return hex.EncodeToString(h.Sum(nil))
}
// VerifySignature 验证消息签名
func (c *Client) VerifySignature(msg *types.UnifiedSynapseMessage, secret string) bool {
if secret == "" {
return true
}
if msg.Signature == "" {
return false
}
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(msg.ID + "." + string(msg.Payload)))
expected := hex.EncodeToString(h.Sum(nil))
return hmac.Equal([]byte(msg.Signature), []byte(expected))
}
// =============================================================================
// 消息发送底层
// =============================================================================
func (c *Client) sendMessage(ctx context.Context, endpoint string, msg *types.UnifiedSynapseMessage) error {
msg.Signature = c.signMessage(msg)
body, err := json.Marshal(msg)
if err != nil {
return fmt.Errorf("failed to marshal message: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("X-Synapse-Signature", msg.Signature)
resp, err := c.httpClient.Do(httpReq)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("remote error: %s", string(respBody))
}
return nil
}
func (c *Client) sendRequest(ctx context.Context, endpoint string, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
msg.Signature = c.signMessage(msg)
body, err := json.Marshal(msg)
if err != nil {
return nil, fmt.Errorf("failed to marshal message: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("X-Synapse-Signature", msg.Signature)
resp, err := c.httpClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("remote error: %s", string(respBody))
}
var respMsg types.UnifiedSynapseMessage
if err := json.Unmarshal(respBody, &respMsg); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
return &respMsg, nil
}
// =============================================================================
// 等待任务完成
// =============================================================================
// WaitForTask 等待任务完成(轮询方式,通过回调更新状态)
func (c *Client) WaitForTask(ctx context.Context, taskID string, timeout time.Duration) (*P2PTaskState, error) {
deadline := time.Now().Add(timeout)
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-ticker.C:
if time.Now().After(deadline) {
return nil, fmt.Errorf("task timeout")
}
state, ok := c.GetTaskState(taskID)
if !ok {
continue
}
switch state.Status {
case types.P2PStatusCompleted, types.P2PStatusFailed, types.P2PStatusCancelled, types.P2PStatusRejected:
return state, nil
}
}
}
}
// =============================================================================
// 回调处理
// =============================================================================
// HandleMessage 处理收到的消息(供 HTTP 服务调用)
func (c *Client) HandleMessage(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
if c.authSecret != "" && !c.VerifySignature(msg, c.authSecret) {
return nil, fmt.Errorf("invalid signature")
}
switch types.P2PMessageType(msg.Type) {
case types.P2PTaskRequest:
if c.callbackHandler != nil {
return c.callbackHandler.HandleTaskRequest(ctx, msg)
}
return c.ackMessage(msg), nil
case types.P2PTaskConfirm:
var payload types.TaskConfirmPayload
_ = json.Unmarshal(msg.Payload, &payload)
c.setTaskState(payload.TaskID, types.P2PStatusConfirmed, 0, "任务已确认")
return c.ackMessage(msg), nil
case types.P2PTaskReject:
var payload types.TaskRejectPayload
_ = json.Unmarshal(msg.Payload, &payload)
c.setTaskState(payload.TaskID, types.P2PStatusRejected, 0, payload.Reason.Message)
return c.ackMessage(msg), nil
case types.P2PTaskStatusUpdate:
var payload types.TaskStatusUpdatePayload
_ = json.Unmarshal(msg.Payload, &payload)
c.setTaskState(payload.TaskID, types.P2PTaskStatus(payload.Status), payload.Progress, payload.Message)
if c.callbackHandler != nil {
_ = c.callbackHandler.HandleTaskStatusUpdate(ctx, msg)
}
return c.ackMessage(msg), nil
case types.P2PTaskComplete:
var payload types.TaskCompletePayload
_ = json.Unmarshal(msg.Payload, &payload)
c.setTaskState(payload.TaskID, types.P2PStatusCompleted, 100, payload.Summary)
c.setTaskResult(payload.TaskID, payload.Result.Output)
if c.callbackHandler != nil {
_ = c.callbackHandler.HandleTaskComplete(ctx, msg)
}
return c.ackMessage(msg), nil
case types.P2PTaskFailed:
var payload types.TaskFailedPayload
_ = json.Unmarshal(msg.Payload, &payload)
c.setTaskState(payload.TaskID, types.P2PStatusFailed, 0, payload.Error.Message)
c.setTaskError(payload.TaskID, types.NewSynapseError(
types.SynapseErrorCode(0),
payload.Error.Message,
nil,
))
if c.callbackHandler != nil {
_ = c.callbackHandler.HandleTaskFailed(ctx, msg)
}
return c.ackMessage(msg), nil
case types.P2PTaskNeedHuman:
var payload types.TaskNeedHumanPayload
_ = json.Unmarshal(msg.Payload, &payload)
c.setTaskState(payload.TaskID, types.P2PStatusNeedHuman, 0, payload.Reason.Message)
if c.callbackHandler != nil {
_ = c.callbackHandler.HandleNeedHuman(ctx, msg)
}
return c.ackMessage(msg), nil
case types.P2PCapabilityQuery:
return nil, nil
default:
return c.ackMessage(msg), nil
}
}
func (c *Client) ackMessage(msg *types.UnifiedSynapseMessage) *types.UnifiedSynapseMessage {
return &types.UnifiedSynapseMessage{
ID: types.GenerateMessageID(),
Version: msg.Version,
Type: string(types.P2PAck),
Sender: c.agentEndpoint,
Receiver: &msg.Sender,
ReplyTo: msg.ID,
Payload: []byte("{}"),
Timestamp: types.NowTimestamp(),
}
}