548 lines
16 KiB
Go
548 lines
16 KiB
Go
package caller
|
||
|
||
import (
|
||
"bytes"
|
||
"context"
|
||
"encoding/json"
|
||
"fmt"
|
||
"io"
|
||
"mime/multipart"
|
||
"net/http"
|
||
"time"
|
||
)
|
||
|
||
// =============================================================================
|
||
// Synapse Caller SDK (P2A Protocol)
|
||
// 非Agent调用方使用的客户端SDK
|
||
// 基于 P2A 协议:非 Agent 调用方通过 REST API 调用 Agent 能力
|
||
// =============================================================================
|
||
|
||
// Client 是 Synapse P2A 服务的外部调用客户端
|
||
type Client struct {
|
||
baseURL string
|
||
apiKey string
|
||
httpClient *http.Client
|
||
}
|
||
|
||
// ClientConfig 客户端配置
|
||
type ClientConfig struct {
|
||
BaseURL string
|
||
APIKey string
|
||
Timeout time.Duration
|
||
MaxRetries int
|
||
}
|
||
|
||
// NewClient 创建新的 Synapse Caller 客户端
|
||
func NewClient(config ClientConfig) *Client {
|
||
if config.Timeout == 0 {
|
||
config.Timeout = 30 * time.Second
|
||
}
|
||
return &Client{
|
||
baseURL: config.BaseURL,
|
||
apiKey: config.APIKey,
|
||
httpClient: &http.Client{Timeout: config.Timeout},
|
||
}
|
||
}
|
||
|
||
// =============================================================================
|
||
// 通用响应结构
|
||
// =============================================================================
|
||
|
||
// APIResponse 通用 API 响应
|
||
type APIResponse struct {
|
||
Success bool `json:"success"`
|
||
Message string `json:"message,omitempty"`
|
||
Error string `json:"error,omitempty"`
|
||
}
|
||
|
||
// TaskResponse 任务提交响应
|
||
type TaskResponse struct {
|
||
APIResponse
|
||
TaskID string `json:"task_id"`
|
||
Status string `json:"status"`
|
||
Message string `json:"message,omitempty"`
|
||
}
|
||
|
||
// TaskStatusResponse 任务状态响应(简化版)
|
||
type TaskStatusResponse struct {
|
||
APIResponse
|
||
TaskID string `json:"task_id"`
|
||
Status string `json:"status"`
|
||
Progress int `json:"progress"`
|
||
}
|
||
|
||
// TaskDetailResponse 任务详情响应
|
||
type TaskDetailResponse struct {
|
||
APIResponse
|
||
Task TaskInfo `json:"task"`
|
||
}
|
||
|
||
// TaskListResponse 任务列表响应
|
||
type TaskListResponse struct {
|
||
APIResponse
|
||
Tasks []TaskInfo `json:"tasks"`
|
||
Total int `json:"total"`
|
||
Limit int `json:"limit"`
|
||
Offset int `json:"offset"`
|
||
HasMore bool `json:"has_more"`
|
||
}
|
||
|
||
// TaskInfo 任务详情信息
|
||
type TaskInfo struct {
|
||
ID string `json:"id"`
|
||
Type string `json:"type"`
|
||
Status string `json:"status"`
|
||
Progress int `json:"progress"`
|
||
Message string `json:"message,omitempty"`
|
||
CreatedAt string `json:"created_at"`
|
||
UpdatedAt string `json:"updated_at"`
|
||
CompletedAt string `json:"completed_at,omitempty"`
|
||
ETA string `json:"eta,omitempty"`
|
||
Result map[string]any `json:"result,omitempty"`
|
||
Error *TaskError `json:"error,omitempty"`
|
||
ExternalTaskID string `json:"external_task_id,omitempty"`
|
||
}
|
||
|
||
// TaskError 任务错误
|
||
type TaskError struct {
|
||
Code string `json:"code"`
|
||
Message string `json:"message"`
|
||
}
|
||
|
||
// TaskRequest 任务请求
|
||
type TaskRequest struct {
|
||
TaskType string `json:"task_type"`
|
||
Payload map[string]any `json:"payload"`
|
||
ExternalTaskID string `json:"external_task_id,omitempty"`
|
||
Priority string `json:"priority,omitempty"`
|
||
CallbackURL string `json:"callback_url,omitempty"`
|
||
CallbackToken string `json:"callback_token,omitempty"`
|
||
}
|
||
|
||
// FileParam 上传文件参数
|
||
type FileParam struct {
|
||
FieldName string
|
||
Filename string
|
||
Data []byte
|
||
MimeType string
|
||
}
|
||
|
||
// =============================================================================
|
||
// 能力查询
|
||
// =============================================================================
|
||
|
||
// CapabilitiesResponse 能力查询响应
|
||
type CapabilitiesResponse struct {
|
||
APIResponse
|
||
Capabilities CapabilitiesInfo `json:"capabilities"`
|
||
}
|
||
|
||
// CapabilitiesInfo Agent 能力信息
|
||
type CapabilitiesInfo struct {
|
||
AgentID string `json:"agent_id"`
|
||
AgentName string `json:"agent_name"`
|
||
SystemID string `json:"system_id"`
|
||
ProtocolVersion string `json:"protocol_version"`
|
||
SupportedTaskTypes []SupportedTaskType `json:"supported_task_types"`
|
||
SupportedTransportModes []string `json:"supported_transport_modes"`
|
||
MaxFileSize int64 `json:"max_file_size"`
|
||
MaxConcurrentTasks int `json:"max_concurrent_tasks"`
|
||
SupportProgressUpdates bool `json:"support_progress_updates"`
|
||
SupportStreaming bool `json:"support_streaming"`
|
||
SupportHiL bool `json:"support_hil"`
|
||
SupportGroups bool `json:"support_groups"`
|
||
}
|
||
|
||
// SupportedTaskType 支持的任务类型
|
||
type SupportedTaskType struct {
|
||
Type string `json:"type"`
|
||
Name string `json:"name"`
|
||
Description string `json:"description"`
|
||
EstimatedTime string `json:"estimated_time"`
|
||
InputSchema string `json:"input_schema,omitempty"`
|
||
OutputSchema string `json:"output_schema,omitempty"`
|
||
}
|
||
|
||
// GetCapabilities 获取 Agent 能力清单
|
||
func (c *Client) GetCapabilities(ctx context.Context) (*CapabilitiesResponse, error) {
|
||
url := fmt.Sprintf("%s/api/v1/synapse/capabilities", c.baseURL)
|
||
|
||
httpReq, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||
}
|
||
|
||
c.setAuthHeaders(httpReq)
|
||
|
||
resp, err := c.httpClient.Do(httpReq)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("request failed: %w", err)
|
||
}
|
||
defer resp.Body.Close()
|
||
|
||
respBody, _ := io.ReadAll(resp.Body)
|
||
|
||
var result CapabilitiesResponse
|
||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||
}
|
||
|
||
if resp.StatusCode >= 400 {
|
||
return &result, fmt.Errorf("API error: %s", result.Error)
|
||
}
|
||
|
||
return &result, nil
|
||
}
|
||
|
||
// =============================================================================
|
||
// 任务提交
|
||
// =============================================================================
|
||
|
||
// SubmitTask 提交任务(JSON 方式)
|
||
func (c *Client) SubmitTask(ctx context.Context, req *TaskRequest) (*TaskResponse, error) {
|
||
url := fmt.Sprintf("%s/api/v1/synapse/task", c.baseURL)
|
||
|
||
body, err := json.Marshal(req)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("failed to marshal request: %w", err)
|
||
}
|
||
|
||
httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
|
||
if err != nil {
|
||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||
}
|
||
|
||
httpReq.Header.Set("Content-Type", "application/json")
|
||
c.setAuthHeaders(httpReq)
|
||
|
||
resp, err := c.httpClient.Do(httpReq)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("request failed: %w", err)
|
||
}
|
||
defer resp.Body.Close()
|
||
|
||
respBody, _ := io.ReadAll(resp.Body)
|
||
|
||
var result TaskResponse
|
||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||
}
|
||
|
||
if resp.StatusCode >= 400 {
|
||
return &result, fmt.Errorf("API error: %s", result.Error)
|
||
}
|
||
|
||
return &result, nil
|
||
}
|
||
|
||
// SubmitTaskWithFiles 提交带文件的任务(multipart/form-data 方式)
|
||
func (c *Client) SubmitTaskWithFiles(ctx context.Context, req *TaskRequest, files []FileParam) (*TaskResponse, error) {
|
||
url := fmt.Sprintf("%s/api/v1/synapse/task/multipart", c.baseURL)
|
||
|
||
var buf bytes.Buffer
|
||
writer := multipart.NewWriter(&buf)
|
||
|
||
_ = writer.WriteField("task_type", req.TaskType)
|
||
|
||
payloadJSON, _ := json.Marshal(req.Payload)
|
||
_ = writer.WriteField("payload", string(payloadJSON))
|
||
|
||
if req.ExternalTaskID != "" {
|
||
_ = writer.WriteField("external_task_id", req.ExternalTaskID)
|
||
}
|
||
if req.Priority != "" {
|
||
_ = writer.WriteField("priority", req.Priority)
|
||
}
|
||
if req.CallbackURL != "" {
|
||
_ = writer.WriteField("callback_url", req.CallbackURL)
|
||
}
|
||
if req.CallbackToken != "" {
|
||
_ = writer.WriteField("callback_token", req.CallbackToken)
|
||
}
|
||
|
||
for _, f := range files {
|
||
var part io.Writer
|
||
var err error
|
||
if f.MimeType != "" {
|
||
part, err = writer.CreatePart(map[string][]string{
|
||
"Content-Disposition": {fmt.Sprintf(`form-data; name="%s"; filename="%s"`, f.FieldName, f.Filename)},
|
||
"Content-Type": {f.MimeType},
|
||
})
|
||
} else {
|
||
part, err = writer.CreateFormFile(f.FieldName, f.Filename)
|
||
}
|
||
if err != nil {
|
||
return nil, fmt.Errorf("failed to create form file: %w", err)
|
||
}
|
||
_, _ = part.Write(f.Data)
|
||
}
|
||
|
||
_ = writer.Close()
|
||
|
||
httpReq, err := http.NewRequestWithContext(ctx, "POST", url, &buf)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||
}
|
||
|
||
httpReq.Header.Set("Content-Type", writer.FormDataContentType())
|
||
c.setAuthHeaders(httpReq)
|
||
|
||
resp, err := c.httpClient.Do(httpReq)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("request failed: %w", err)
|
||
}
|
||
defer resp.Body.Close()
|
||
|
||
respBody, _ := io.ReadAll(resp.Body)
|
||
|
||
var result TaskResponse
|
||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||
}
|
||
|
||
if resp.StatusCode >= 400 {
|
||
return &result, fmt.Errorf("API error: %s", result.Error)
|
||
}
|
||
|
||
return &result, nil
|
||
}
|
||
|
||
// =============================================================================
|
||
// 任务查询
|
||
// =============================================================================
|
||
|
||
// GetTask 获取任务详情
|
||
func (c *Client) GetTask(ctx context.Context, taskID string) (*TaskDetailResponse, error) {
|
||
url := fmt.Sprintf("%s/api/v1/synapse/task/%s", c.baseURL, taskID)
|
||
|
||
httpReq, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||
}
|
||
|
||
c.setAuthHeaders(httpReq)
|
||
|
||
resp, err := c.httpClient.Do(httpReq)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("request failed: %w", err)
|
||
}
|
||
defer resp.Body.Close()
|
||
|
||
respBody, _ := io.ReadAll(resp.Body)
|
||
|
||
var result TaskDetailResponse
|
||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||
}
|
||
|
||
if resp.StatusCode >= 400 {
|
||
return &result, fmt.Errorf("API error: %s", result.Error)
|
||
}
|
||
|
||
return &result, nil
|
||
}
|
||
|
||
// GetTaskStatus 获取任务状态(简化版)
|
||
func (c *Client) GetTaskStatus(ctx context.Context, taskID string) (*TaskStatusResponse, error) {
|
||
url := fmt.Sprintf("%s/api/v1/synapse/task/%s/status", c.baseURL, taskID)
|
||
|
||
httpReq, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||
}
|
||
|
||
c.setAuthHeaders(httpReq)
|
||
|
||
resp, err := c.httpClient.Do(httpReq)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("request failed: %w", err)
|
||
}
|
||
defer resp.Body.Close()
|
||
|
||
respBody, _ := io.ReadAll(resp.Body)
|
||
|
||
var result TaskStatusResponse
|
||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||
}
|
||
|
||
if resp.StatusCode >= 400 {
|
||
return &result, fmt.Errorf("API error: %s", result.Error)
|
||
}
|
||
|
||
return &result, nil
|
||
}
|
||
|
||
// ListTasks 获取任务列表
|
||
func (c *Client) ListTasks(ctx context.Context, status string, limit, offset int) (*TaskListResponse, error) {
|
||
if limit <= 0 {
|
||
limit = 20
|
||
}
|
||
url := fmt.Sprintf("%s/api/v1/synapse/tasks?status=%s&limit=%d&offset=%d",
|
||
c.baseURL, status, limit, offset)
|
||
|
||
httpReq, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||
}
|
||
|
||
c.setAuthHeaders(httpReq)
|
||
|
||
resp, err := c.httpClient.Do(httpReq)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("request failed: %w", err)
|
||
}
|
||
defer resp.Body.Close()
|
||
|
||
respBody, _ := io.ReadAll(resp.Body)
|
||
|
||
var result TaskListResponse
|
||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||
}
|
||
|
||
if resp.StatusCode >= 400 {
|
||
return &result, fmt.Errorf("API error: %s", result.Error)
|
||
}
|
||
|
||
return &result, nil
|
||
}
|
||
|
||
// =============================================================================
|
||
// 任务取消
|
||
// =============================================================================
|
||
|
||
// CancelTask 取消任务
|
||
func (c *Client) CancelTask(ctx context.Context, taskID string) (*TaskResponse, error) {
|
||
url := fmt.Sprintf("%s/api/v1/synapse/task/%s/cancel", c.baseURL, taskID)
|
||
|
||
httpReq, err := http.NewRequestWithContext(ctx, "POST", url, nil)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||
}
|
||
|
||
c.setAuthHeaders(httpReq)
|
||
|
||
resp, err := c.httpClient.Do(httpReq)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("request failed: %w", err)
|
||
}
|
||
defer resp.Body.Close()
|
||
|
||
respBody, _ := io.ReadAll(resp.Body)
|
||
|
||
var result TaskResponse
|
||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||
return nil, fmt.Errorf("failed to decode response: %w", err)
|
||
}
|
||
|
||
if resp.StatusCode >= 400 {
|
||
return &result, fmt.Errorf("API error: %s", result.Error)
|
||
}
|
||
|
||
return &result, nil
|
||
}
|
||
|
||
// =============================================================================
|
||
// 等待任务完成
|
||
// =============================================================================
|
||
|
||
// WaitForTask 等待任务完成(轮询方式)
|
||
func (c *Client) WaitForTask(ctx context.Context, taskID string, interval time.Duration) (*TaskInfo, error) {
|
||
if interval == 0 {
|
||
interval = 5 * time.Second
|
||
}
|
||
|
||
ticker := time.NewTicker(interval)
|
||
defer ticker.Stop()
|
||
|
||
for {
|
||
select {
|
||
case <-ctx.Done():
|
||
return nil, ctx.Err()
|
||
case <-ticker.C:
|
||
resp, err := c.GetTask(ctx, taskID)
|
||
if err != nil {
|
||
continue
|
||
}
|
||
|
||
switch resp.Task.Status {
|
||
case "completed", "failed", "cancelled", "rejected":
|
||
return &resp.Task, nil
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// =============================================================================
|
||
// 回调验证
|
||
// =============================================================================
|
||
|
||
// CallbackRequest 回调请求结构
|
||
type CallbackRequest struct {
|
||
TaskID string `json:"task_id"`
|
||
Status string `json:"status"`
|
||
Progress int `json:"progress"`
|
||
Message string `json:"message,omitempty"`
|
||
Result map[string]any `json:"result,omitempty"`
|
||
Error *TaskError `json:"error,omitempty"`
|
||
Timestamp string `json:"timestamp"`
|
||
}
|
||
|
||
// VerifyCallback 验证回调请求签名
|
||
func (c *Client) VerifyCallback(r *http.Request, callbackToken string) bool {
|
||
if callbackToken == "" {
|
||
return true
|
||
}
|
||
token := r.Header.Get("X-Callback-Token")
|
||
return token == callbackToken
|
||
}
|
||
|
||
// =============================================================================
|
||
// 高阶 API: 快速创建任务并等待
|
||
// =============================================================================
|
||
|
||
// CreateAndWait 创建任务并等待完成
|
||
func (c *Client) CreateAndWait(ctx context.Context, taskType string, payload map[string]any, interval time.Duration) (*TaskInfo, error) {
|
||
req := &TaskRequest{
|
||
TaskType: taskType,
|
||
Payload: payload,
|
||
Priority: "normal",
|
||
}
|
||
|
||
resp, err := c.SubmitTask(ctx, req)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
if !resp.Success {
|
||
return nil, fmt.Errorf("task submission failed: %s", resp.Message)
|
||
}
|
||
|
||
return c.WaitForTask(ctx, resp.TaskID, interval)
|
||
}
|
||
|
||
// CreateWithCallback 创建任务并指定回调
|
||
func (c *Client) CreateWithCallback(ctx context.Context, taskType string, payload map[string]any, callbackURL, callbackToken string) (*TaskResponse, error) {
|
||
req := &TaskRequest{
|
||
TaskType: taskType,
|
||
Payload: payload,
|
||
Priority: "normal",
|
||
CallbackURL: callbackURL,
|
||
CallbackToken: callbackToken,
|
||
}
|
||
|
||
return c.SubmitTask(ctx, req)
|
||
}
|
||
|
||
// =============================================================================
|
||
// 辅助方法
|
||
// =============================================================================
|
||
|
||
func (c *Client) setAuthHeaders(req *http.Request) {
|
||
if c.apiKey != "" {
|
||
req.Header.Set("X-API-Key", c.apiKey)
|
||
}
|
||
req.Header.Set("Accept", "application/json")
|
||
}
|