# 灵隙 Synapse 协议实现细节文档 > 本文档描述 Synapse 协议栈的具体实现规范,作为核心协议文档的补充。 > > 版本:1.0.0 | 更新日期:2026-06-27 --- ## 目录 1. [七大组件层详细规范](#1-七大组件层详细规范) 2. [内容类型系统](#2-内容类型系统) 3. [能力声明系统](#3-能力声明系统) 4. [gRPC 传输协议](#4-grpc-传输协议) 5. [人工介入(HiL)三级升级机制](#5-人工介入hil三级升级机制) 6. [数字分段错误码系统](#6-数字分段错误码系统) 7. [消息扩展字段](#7-消息扩展字段) 8. [传输模式定义](#8-传输模式定义) --- ## 1. 七大组件层详细规范 灵隙协议栈的七大组件层构成了协议的核心基础设施。每层都有独立的职责和接口。 ### 1.1 灵脉 Meridian - 寻址与路由层 **定位**:Agent 之间虽有空隙(灵隙),但暗中有能量流动的轨迹(脉)。此层负责维护全局路由表。 **核心功能**: | 功能 | 方法 | 说明 | |-----|------|------| | Agent 注册 | `Register(endpoint)` | Agent "通脉"入网 | | Agent 注销 | `Unregister(agentID)` | Agent "断脉"离场 | | Agent 查询 | `GetAgent(agentID)` | 获取 Agent 端点信息 | | Agent 列表 | `ListAgents()` | 列出所有活跃 Agent | | 心跳保活 | `Heartbeat(agentID)` | 刷新 Agent TTL | | 按能力查找 | `FindByCapability(capability)` | 查找具备特定能力的 Agent | **数据结构**: ```go // AgentEndpoint - Agent 端点信息 type AgentEndpoint struct { AgentID string // Agent 唯一标识 AgentName string // Agent 名称 SystemID string // 所属系统 ID Endpoint string // 回调端点 URL Version string // Agent 版本 Capabilities []string // 能力标签列表 Metadata map[string]interface{} // 扩展元数据 } // RegistryConfig - 注册表配置 type RegistryConfig struct { DefaultTTL time.Duration // 默认存活时间(5分钟) } ``` **拓扑管理**: ```go // 拓扑类型 type TopologyType string const ( TopologyStar = "star" // 星型拓扑(中心协调) TopologyMesh = "mesh" // 网状拓扑(全互联) TopologyRing = "ring" // 环形拓扑(环形传递) TopologyTree = "tree" // 树形拓扑(层级管理) TopologyHybrid = "hybrid" // 混合拓扑 ) // 拓扑管理接口 type TopologyManager interface { CreateTopology(id, name string, topologyType TopologyType) *NetworkTopology AddNode(topologyID, nodeID string) error AddEdge(topologyID, from, to string) error GetNeighbors(topologyID, nodeID string) ([]string, error) } ``` --- ### 1.2 灵玺 Sigil - 身份与凭证层 **定位**:皇帝的玉玺是最高凭证。每个 Agent 的初始身份都需经过"铸玺"过程,每一次交互都要"验玺"。 **核心功能**: | 功能 | 方法 | 说明 | |-----|------|------| | 创建身份 | `CreateIdentity(agentID, ...)` | "铸玺" - 创建身份凭证 | | 获取身份 | `GetIdentity(agentID)` | 获取 Agent 身份信息 | | 撤销身份 | `RevokeIdentity(agentID)` | "废玺" - 撤销身份 | | 检查撤销 | `IsRevoked(agentID)` | 检查身份是否已撤销 | | 签名消息 | `SignMessage(msg)` | 对消息签名 | | 验证签名 | `VerifySignature(msg)` | 验证消息签名 | | 颁发令牌 | `IssueToken(agentID, ...)` | 颁发认证令牌 | | 验证令牌 | `ValidateToken(signedToken)` | 验证令牌有效性 | **身份结构**: ```go // AgentIdentity - Agent 身份凭证 type AgentIdentity struct { AgentID string // Agent 唯一标识 AgentName string // Agent 名称 SystemID string // 所属系统 ID PublicKey string // 公钥(可选) PrivateKey string // 私钥(本地保存) AuthSecret string // HMAC 密钥 Roles []string // 角色列表 Permissions []string // 权限列表 CreatedAt time.Time // 创建时间 ExpiresAt *time.Time // 过期时间 RevokedAt *time.Time // 撤销时间 } // AuthToken - 认证令牌 type AuthToken struct { TokenID string // 令牌 ID AgentID string // 所属 Agent SystemID string // 所属系统 Roles []string // 角色列表 IssuedAt time.Time // 颁发时间 ExpiresAt time.Time // 过期时间 } ``` **签名算法**: ```go // 支持的签名算法 type SignatureAlgorithm string const ( AlgHMACSHA256 SignatureAlgorithm = "HMAC-SHA256" // 默认 AlgHMACSHA512 SignatureAlgorithm = "HMAC-SHA512" // 可选 ) // 签名内容格式 // signature_content = sender_id | receiver_id | timestamp | payload_json ``` --- ### 1.3 灵鉴 Speculum - 共识与裁决层 **定位**:古有"以史为鉴",今有"以智为鉴"。此层通过对比推理链的严密性来达成共识,如青天明镜。 **核心功能**: | 功能 | 方法 | 说明 | |-----|------|------| | 发起投票 | `InitiateVote(...)` | 创建投票议题 | | 提交投票 | `SubmitVote(voteID, voterID, optionID, reasoning)` | 提交投票 | | 关闭投票 | `CloseVote(voteID)` | 关闭并统计结果 | | 获取投票 | `GetVote(voteID)` | 获取投票信息 | | 仲裁争议 | `Arbitrate(ctx, dispute)` | 仲裁争议 | | 提交推理链 | `SubmitReasoning(chain)` | 提交推理链到镜面 | | 比较推理链 | `CompareReasonings(chainIDs)` | 比较推理链严密性 | **共识类型**: ```go type ConsensusType string const ( ConsensusMajority = "majority" // 多数投票(>50%) ConsensusSupermajority = "supermajority" // 绝对多数(>67%) ConsensusUnanimity = "unanimity" // 一致同意(100%) ConsensusWeighted = "weighted" // 加权投票 ConsensusRanked = "ranked" // 排序投票 ) ``` **投票结构**: ```go // Vote - 投票 type Vote struct { VoteID string // 投票 ID 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 -> 推理理由 } // VoteResult - 投票结果 type VoteResult struct { Winner string // 获胜选项 WinOption VoteOption // 获胜选项详情 VoteCounts map[string]int // 选项 -> 票数 Passed bool // 是否通过 Margin float64 // 得票率 } ``` **推理镜面**: ```go // ReasoningChain - 推理链 type ReasoningChain struct { ChainID string // 推理链 ID AgentID string // Agent ID Topic string // 推理主题 Steps []ReasoningStep // 推理步骤 Score float64 // 推理得分 SubmittedAt time.Time // 提交时间 } // ReasoningStep - 推理步骤 type ReasoningStep struct { StepID string // 步骤 ID Description string // 步骤描述 Evidence []string // 证据列表 Confidence float64 // 置信度(0-1) Next []string // 下一步 ID 列表 } ``` --- ### 1.4 灵泊 Harbor - 异步队列与暂存层 **定位**:"泊"为船舶停靠。数据包遇风浪(网络抖动)时暂泊于此,待风平浪静再启航。 **核心功能**: | 功能 | 方法 | 说明 | |-----|------|------| | 消息入队 | `Enqueue(msg, target, priority)` | 消息入队(支持优先级) | | 消息出队 | `Dequeue()` | 消息出队 | | 标记送达 | `MarkDelivered(msgID)` | 标记消息已送达 | | 标记失败 | `MarkFailed(msgID, err)` | 标记消息失败(触发重试) | | 缓冲消息 | `BufferMessage(agentID, msg)` | 为离线 Agent 缓冲消息 | | 清空缓冲 | `FlushBuffer(agentID)` | Agent 上线后清空缓冲 | | 添加重试 | `AddRetry(msg, target)` | 添加重试条目 | **队列配置**: ```go // QueueConfig - 队列配置 type QueueConfig struct { MaxSize int // 最大队列大小(10000) DefaultMaxRetries int // 默认最大重试次数(5) DefaultRetryDelay time.Duration // 默认重试延迟(30s) } // 队列消息状态 type QueuedStatus string const ( QueuedPending = "pending" // 待处理 QueuedProcessing = "processing" // 处理中 QueuedDelivered = "delivered" // 已送达 QueuedFailed = "failed" // 失败 QueuedDead = "dead" // 死信 ) ``` **重试机制**: ```go // RetryConfig - 重试配置 type RetryConfig struct { MaxRetries int // 最大重试次数(5) BaseDelay time.Duration // 基础延迟(1s) MaxDelay time.Duration // 最大延迟(5min) JitterFactor float64 // 抖动因子(0.1) } // 重试延迟算法:指数退避 + 抖动 // delay = min(BaseDelay * 2^(retryCount-1), MaxDelay) * (1 ± JitterFactor) ``` **缓冲配置**: ```go // BufferConfig - 缓冲配置 type BufferConfig struct { MaxPerAgent int // 每个 Agent 最大缓冲数(1000) MaxAge time.Duration // 消息最大存活时间(24h) CleanupInterval time.Duration // 清理间隔(1h) } ``` --- ### 1.5 灵瞰 Panorama - 可观测与度量层 **定位**:居高临下,俯瞰全局。如"天眼"般记录每一帧交互的耗时、置信度与资源消耗。 **核心功能**: | 功能 | 方法 | 说明 | |-----|------|------| | 开始追踪 | `StartTrace(traceID, name, agentID)` | 创建追踪链路 | | 开始跨度 | `StartSpan(traceID, parentSpanID, name, agentID)` | 创建子跨度 | | 结束跨度 | `EndSpan(traceID, spanID, status, err)` | 结束跨度 | | 添加日志 | `AddSpanLog(traceID, spanID, message, fields)` | 添加跨度日志 | | 记录指标 | `RecordMetric(name, type, value, labels)` | 记录指标 | | 递增计数 | `IncrementCounter(name, labels, delta)` | 递增计数器 | | 设置计量 | `SetGauge(name, labels, value)` | 设置计量值 | | 健康检查 | `CheckAll(ctx)` | 检查所有组件健康状态 | **追踪结构**: ```go // Trace - 追踪链路 type Trace struct { TraceID string // 追踪 ID RootSpan *Span // 根跨度 Spans map[string]*Span // 跨度集合 StartTime time.Time // 开始时间 EndTime *time.Time // 结束时间 Metadata map[string]interface{} // 元数据 } // Span - 追踪跨度 type Span struct { SpanID string // 跨度 ID TraceID string // 所属追踪 ID ParentID string // 父跨度 ID Name string // 跨度名称 Service string // 服务名 AgentID string // Agent ID StartTime time.Time // 开始时间 EndTime *time.Time // 结束时间 Duration time.Duration // 持续时间 Status SpanStatus // 跨度状态 Tags map[string]string // 标签 Logs []SpanLog // 日志 Attributes map[string]interface{} // 属性 } // SpanStatus - 跨度状态 type SpanStatus string const ( SpanStatusPending = "pending" // 待定 SpanStatusRunning = "running" // 运行中 SpanStatusSuccess = "success" // 成功 SpanStatusFailed = "failed" // 失败 SpanStatusCancelled = "cancelled" // 已取消 ) ``` **指标类型**: ```go type MetricType string const ( MetricCounter = "counter" // 计数器(累加) MetricGauge = "gauge" // 计量器(瞬时值) MetricHistogram = "histogram" // 直方图(分布) ) ``` **健康状态**: ```go type HealthStatus string const ( HealthStatusHealthy = "healthy" // 健康 HealthStatusDegraded = "degraded" // 降级 HealthStatusUnhealthy = "unhealthy" // 不健康 HealthStatusUnknown = "unknown" // 未知 ) ``` --- ### 1.6 灵衡 Libra - 价值结算与激励层 **定位**:权衡利弊,计量公平。将 Agent 间的"智力贡献"与"资源消耗"通证化,动态定价。 **核心功能**: | 功能 | 方法 | 说明 | |-----|------|------| | 创建账户 | `CreateAccount(agentID)` | 为 Agent 创建账户 | | 获取余额 | `GetBalance(agentID)` | 查询账户余额 | | 转账 | `Transfer(from, to, amount, ...)` | 执行转账 | | 设置价格 | `SetPrice(taskType, capability, price)` | 设置任务价格 | | 获取价格 | `GetPrice(taskType)` | 获取任务价格 | | 计算成本 | `CalculateCost(taskType, complexity, duration)` | 计算任务成本 | | 结算任务 | `SettleTask(taskID, ...)` | 结算单个任务 | | 结算群组任务 | `SettleGroupTask(taskID, ...)` | 结算群组任务(分摊费用) | | 奖励 | `Reward(agentID, amount, reason)` | 发放奖励 | **账户与交易**: ```go // Account - 账户 type Account struct { AgentID string // Agent ID Balance map[string]float64 // 余额(currency -> amount) CreatedAt time.Time // 创建时间 Metadata map[string]interface{} // 元数据 } // Transaction - 交易记录 type Transaction struct { TxID string // 交易 ID Type TransactionType // 交易类型 FromAgentID string // 发送方 ToAgentID string // 接收方 Amount float64 // 金额 Currency string // 货币("SYN") Description string // 描述 TaskID string // 关联任务 ID Timestamp time.Time // 时间戳 Status TransactionStatus // 交易状态 } // TransactionType - 交易类型 type TransactionType string const ( TxTaskExecution = "task_execution" // 任务执行 TxDataSharing = "data_sharing" // 数据共享 TxAPIInvocation = "api_invocation" // API 调用 TxGroupContribution = "group_contribution" // 群组贡献 TxDeposit = "deposit" // 充值 TxWithdraw = "withdraw" // 提现 TxReward = "reward" // 奖励 TxPenalty = "penalty" // 惩罚 ) ``` **定价规则**: ```go // 基础价格(默认) var 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, } // 成本计算公式 // cost = basePrice * complexityFactor + durationFactor // complexityFactor = complexity * 0.5 // durationFactor = duration_seconds * 0.01 ``` --- ### 1.7 灵枢 Pivot - 紧急制动与治理层 **定位**:取自《灵枢经》。这是整个协议的"总闸"与"方向盘",不轻易触发,但触发时能以最小代价重置网络状态。 **核心功能**: | 功能 | 方法 | 说明 | |-----|------|------| | 允许请求 | `Allow()` | 检查熔断器是否允许请求 | | 记录成功 | `RecordSuccess()` | 记录成功(用于恢复) | | 记录失败 | `RecordFailure()` | 记录失败(触发熔断) | | 获取状态 | `State()` | 获取熔断器状态 | | 重置 | `Reset()` | 重置熔断器 | | 设置治理级别 | `SetLevel(level)` | 设置治理级别 | | 封禁 Agent | `BanAgent(agentID, reason)` | 封禁 Agent | | 解封 Agent | `UnbanAgent(agentID)` | 解封 Agent | | 紧急停止 | `EmergencyStop(reason)` | 一键熔断所有 | | 恢复正常 | `Resume()` | 恢复正常模式 | | 应用升级 | `ApplyUpgrade(version)` | 应用协议升级 | | 回滚升级 | `RollbackUpgrade(version)` | 回滚协议升级 | **熔断器**: ```go // CircuitBreaker - 熔断器 type CircuitBreaker struct { name string // 熔断器名称 state CircuitState // 状态 failureCount int // 失败计数 successCount int // 成功计数(半开状态) threshold int // 失败阈值(5) timeout time.Duration // 熔断超时(30s) } // CircuitState - 熔断器状态 type CircuitState string const ( CircuitClosed = "closed" // 关闭:正常流通 CircuitOpen = "open" // 打开:熔断,拒绝请求 CircuitHalfOpen = "half_open" // 半开:尝试恢复 ) // 状态转换规则: // Closed -> Open:失败次数 >= threshold // Open -> HalfOpen:超过 timeout 时间 // HalfOpen -> Closed:连续成功 3 次 // HalfOpen -> Open:再次失败 ``` **治理级别**: ```go type GovernanceLevel int const ( GovLevelNormal = iota // 正常运行 GovLevelWatch // 观察模式(记录但不限制) GovLevelRestricted // 受限模式(限流) GovLevelEmergency // 紧急模式(仅白名单) GovLevelShutdown // 停机模式(全部拒绝) ) ``` --- ## 2. 内容类型系统 Synapse 协议支持多种内容类型的传输,适用于不同场景的数据交互。 ### 2.1 传输模式 ```go type TransferMode string const ( TransferInline = "inline" // 内嵌传输(base64 编码) TransferURL = "url" // URL 引用传输 TransferStreaming = "streaming" // 流式传输 TransferMultipart = "multipart" // Multipart 表单传输 ) // 文件大小阈值判断 // size <= 1MB → inline // size > 1MB → url 或 streaming ``` ### 2.2 内容编码 ```go type ContentEncoding string const ( EncodingNone = "none" // 无编码 EncodingBase64 = "base64" // Base64 编码 EncodingGzip = "gzip" // Gzip 压缩 EncodingDeflate = "deflate" // Deflate 压缩 ) ``` ### 2.3 内容类型定义 **文本内容**: ```go type TextContent struct { ContentBase Charset string `json:"charset"` // 字符集("utf-8") Language string `json:"language,omitempty"` // 语言 Data string `json:"data"` // 文本数据 } ``` **JSON 内容**: ```go type JSONContent struct { ContentBase Schema string `json:"schema,omitempty"` // Schema 标识 SchemaURL string `json:"schema_url,omitempty"` // Schema URL Data any `json:"data"` // JSON 数据 } ``` **代码内容**: ```go type CodeContent struct { ContentBase Language string `json:"language"` // 编程语言 Version string `json:"version,omitempty"` // 语言版本 Dependencies []string `json:"dependencies,omitempty"` // 依赖列表 Data string `json:"data"` // 代码内容 } ``` **文件内容**: ```go type FileContent struct { ContentBase Name string `json:"name"` // 文件名 Role string `json:"role,omitempty"` // 角色("reference", "result", "attachment") Description string `json:"description,omitempty"` // 描述 // Inline 传输 Data string `json:"data,omitempty"` // base64 编码 // URL 传输 URL string `json:"url,omitempty"` // URL URLExpiresAt *Timestamp `json:"url_expires_at,omitempty"` // 过期时间 DownloadMethod string `json:"download_method,omitempty"` // GET/POST/signed_url RangeSupported bool `json:"range_supported,omitempty"` // 是否支持范围请求 // 元数据 Width int `json:"width,omitempty"` // 宽度(图片/视频) Height int `json:"height,omitempty"` // 高度 Duration float64 `json:"duration,omitempty"` // 时长(音视频) Resolution string `json:"resolution,omitempty"` // 分辨率 ThumbnailURL string `json:"thumbnail_url,omitempty"` // 缩略图 URL } ``` **内容包(多文件)**: ```go type ContentBundle struct { ID string `json:"id"` // 包 ID Name string `json:"name,omitempty"` // 包名 Description string `json:"description,omitempty"` // 描述 Items []ContentBundleItem `json:"items"` // 内容项列表 TotalSize int64 `json:"total_size,omitempty"` // 总大小 CreatedAt Timestamp `json:"created_at"` // 创建时间 } type ContentBundleItem struct { ID string `json:"id"` // 项 ID Role string `json:"role"` // 角色(main, reference, attachment, thumbnail) Content any `json:"content"` // 内容对象 } ``` ### 2.4 MIME 类型常量 ```go const ( MIMEJSON = "application/json" MIMETextPlain = "text/plain" MIMETextMarkdown = "text/markdown" MIMETextHTML = "text/html" MIMETextCSV = "text/csv" MIMEImageJPEG = "image/jpeg" MIMEImagePNG = "image/png" MIMEImageWebP = "image/webp" MIMEImageGIF = "image/gif" MIMEImageSVG = "image/svg+xml" MIMEVideoMP4 = "video/mp4" MIMEVideoWebM = "video/webm" MIMEAudioMP3 = "audio/mpeg" MIMEAudioWAV = "audio/wav" MIMEAudioAAC = "audio/aac" MIMEPDF = "application/pdf" MIMEOctetStream = "application/octet-stream" MIMEMultipartForm = "multipart/form-data" ) ``` --- ## 3. 能力声明系统 每个 Agent 必须实现 `CapabilitiesProvider` 接口,以便其他 Agent 查询其能力。 ### 3.1 核心接口 ```go type CapabilitiesProvider interface { GetCapabilities(ctx context.Context) (*AgentCapabilities, error) GetSupportedInterfaces() []ImplementedInterface GetTaskTypeCapabilities(taskType string) (*SupportedTaskType, error) } ``` ### 3.2 能力描述结构 ```go type AgentCapabilities 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 []TransportMode `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"` } type SupportedTaskType struct { Type string `json:"type"` Name string `json:"name"` Description string `json:"description"` EstimatedTime string `json:"estimated_time"` // 如 "30s-2min" InputSchema string `json:"input_schema,omitempty"` OutputSchema string `json:"output_schema,omitempty"` Capabilities []string `json:"capabilities,omitempty"` } ``` ### 3.3 接口分类与合规级别 **接口分类**: ```go type InterfaceCategory string const ( CategoryCore = "core" // 核心接口(身份、消息处理) CategoryP2P = "p2p" // P2P 接口(任务处理、回调) CategoryGroup = "group" // 群组接口(子任务、投票) CategoryHiL = "hil" // HiL 接口(人工决策、升级) CategoryTransport = "transport" // 传输接口(HTTP、流式) CategorySecurity = "security" // 安全接口(认证、幂等) CategoryManagement = "management" // 管理接口(配置、监控) ) ``` **合规级别**: ```go // basic:必须实现 // complete:推荐实现 // advanced:可选实现 const ( ComplianceBasic = "basic" ComplianceComplete = "complete" ComplianceAdvanced = "advanced" ) ``` ### 3.4 标准接口注册表 系统预定义的标准接口列表(详见 `capabilities/provider.go`): | 接口名 | 分类 | 合规级别 | 说明 | |------|------|---------|------| | AgentIdentity | core | basic | Agent 身份信息 | | MessageHandler | core | basic | 消息处理 | | CapabilitiesProvider | core | basic | 能力声明 | | P2PTaskHandler | p2p | basic | P2P 任务处理 | | CallbackSender | p2p | complete | 回调发送 | | CallbackReceiver | p2p | basic | 回调接收端点 | | TaskStatusProvider | p2p | complete | 任务状态查询 | | GroupTaskHandler | group | advanced | 群组任务处理 | | GroupManager | group | advanced | 群组管理 | | VotingHandler | group | advanced | 投票处理 | | HILHandler | hil | complete | HiL 决策处理 | | EscalationHandler | hil | advanced | 升级处理 | | HTTPTransport | transport | basic | HTTP 传输 | | MultipartTransport | transport | complete | Multipart 文件传输 | | HybridTransport | transport | complete | 混合传输(回调+轮询) | | StreamingTransport | transport | advanced | 流式传输 | | Authenticator | security | basic | 认证签名 | | IdempotencyHandler | security | basic | 幂等性处理 | --- ## 4. gRPC 传输协议 Synapse 协议支持 HTTP REST 和 gRPC 双传输模式,通过 gRPC Gateway 实现 HTTP/gRPC 双端点。 ### 4.1 Proto 定义位置 ``` proto/synapse.proto ``` ### 4.2 服务定义 **任务服务 TaskService**: ```protobuf service TaskService { rpc SubmitTask(SubmitTaskRequest) returns (SubmitTaskResponse); rpc SubmitTaskWithFiles(SubmitTaskWithFilesRequest) returns (SubmitTaskResponse); rpc GetTask(GetTaskRequest) returns (TaskStatusResponse); rpc GetTaskStatus(GetTaskRequest) returns (TaskStatusResponse); rpc ListTasks(ListTasksRequest) returns (ListTasksResponse); rpc CancelTask(CancelTaskRequest) returns (CancelTaskResponse); rpc StreamTaskStatus(stream TaskStatusStreamRequest) returns (stream TaskStatusUpdate); } ``` **消息服务 SynapseMessageService**: ```protobuf service SynapseMessageService { rpc SendMessage(SendMessageRequest) returns (SendMessageResponse); rpc StreamMessages(stream SynapseMessage) returns (stream SynapseMessage); rpc ReceiveCallback(google.protobuf.Empty) returns (stream SynapseMessage); } ``` **能力服务 CapabilitiesService**: ```protobuf service CapabilitiesService { rpc GetCapabilities(google.protobuf.Empty) returns (CapabilitiesResponse); rpc QueryAgent(QueryAgentRequest) returns (CapabilitiesResponse); rpc ListAgents(google.protobuf.Empty) returns (ListAgentsResponse); } ``` **群组服务 GroupService**: ```protobuf service GroupService { rpc CreateGroup(CreateGroupRequest) returns (CreateGroupResponse); rpc JoinGroup(JoinGroupRequest) returns (JoinGroupResponse); rpc LeaveGroup(LeaveGroupRequest) returns (LeaveGroupResponse); rpc DisbandGroup(DisbandGroupRequest) returns (DisbandGroupResponse); rpc ListGroupMembers(ListGroupMembersRequest) returns (ListGroupMembersResponse); rpc StreamGroupMessages(stream SynapseMessage) returns (stream SynapseMessage); } ``` **健康服务 HealthService**: ```protobuf service HealthService { rpc HealthCheck(google.protobuf.Empty) returns (HealthCheckResponse); } ``` ### 4.3 HTTP 路由映射 通过 `google.api.http` 注解实现 REST API: | gRPC 方法 | HTTP 路由 | |----------|----------| | SubmitTask | POST `/api/v1/synapse/task` | | SubmitTaskWithFiles | POST `/api/v1/synapse/task/multipart` | | GetTask | GET `/api/v1/synapse/task/{task_id}` | | GetTaskStatus | GET `/api/v1/synapse/task/{task_id}/status` | | ListTasks | GET `/api/v1/synapse/tasks` | | CancelTask | POST `/api/v1/synapse/task/{task_id}/cancel` | | GetCapabilities | GET `/api/v1/synapse/capabilities` | | QueryAgent | GET `/api/v1/synapse/agents/{agent_id}` | | ListAgents | GET `/api/v1/synapse/agents` | | CreateGroup | POST `/api/v1/synapse/group` | | JoinGroup | POST `/api/v1/synapse/group/{group_id}/join` | | LeaveGroup | POST `/api/v1/synapse/group/{group_id}/leave` | | DisbandGroup | POST `/api/v1/synapse/group/{group_id}/disband` | | ListGroupMembers | GET `/api/v1/synapse/group/{group_id}/members` | | HealthCheck | GET `/api/v1/synapse/health` | --- ## 5. 人工介入(HiL)三级升级机制 Synapse 协议支持三级人工介入升级机制,根据决策的重要性和紧急程度分级处理。 ### 5.1 升级级别定义 | 级别 | 名称 | 默认超时 | 适用场景 | |-----|------|---------|---------| | Level 1 | Agent 建议 + 人确认 | 24 小时 | 信息缺失、创意方向、用户主动请求 | | Level 2 | 必须人工决策 | 12 小时(紧急 2 小时) | 品牌风格、合规、能力不足、高风险 | | Level 3 | 专家/管理层决策 | 72 小时 | 战略决策、重大争议、跨系统冲突 | ### 5.2 HiL 状态流转 ```go type HILStatus string const ( HILStatusPending = "pending" // 待处理 HILStatusWaiting = "waiting" // 等待人工响应 HILStatusDeciding = "deciding" // 人工正在决策 HILStatusApproved = "approved" // 已批准 HILStatusRejected = "rejected" // 已拒绝 HILStatusTimeout = "timeout" // 超时 HILStatusEscalated = "escalated" // 已升级 ) ``` ### 5.3 HiL 请求结构 ```go type HILRequest struct { ID string // 请求 ID TaskID string // 关联任务 ID EscalationType string // P2P, GROUP, INTER_GROUP EscalationLevel int // 1, 2, 3 Reason HILReason // 介入原因 Context HILContext // 决策上下文 Options []HILOption // 可选方案 SuggestedValue any // Agent 建议值 Deadline time.Time // 截止时间 Status HILStatus // 当前状态 Response *HILResponse // 人工响应 } type HILReason struct { Code string // 原因代码 Message string // 原因描述 } type HILOption struct { Field string // 字段名 Value any // 候选值 Label string // 显示标签 ProsCons string // 优缺点分析 Confidence int // Agent 置信度(0-100) } ``` ### 5.4 升级判定规则 ```go // 需要人工介入的原因代码 var hilRequiredCodes = map[string]bool{ "BRAND_STYLE": true, // 品牌风格 "CREATIVE_DIRECTION": true, // 创意方向 "COMPLIANCE": true, // 合规要求 "CAPABILITY_LACKING": true, // 能力不足 "USER_REQUESTED": true, // 用户请求 "HIGH_COST_RISK": true, // 高成本风险 } // 升级级别判定 var levelMap = map[string]int{ "INFO_MISSING": 1, // Level 1 "CREATIVE_DIRECTION": 1, "BRAND_STYLE": 2, // Level 2 "COMPLIANCE": 2, "CAPABILITY_LACKING": 2, "HIGH_COST_RISK": 2, "RESOURCE_DEADLOCK": 2, "STRATEGIC_DECISION": 3, // Level 3 } ``` ### 5.5 人工响应结构 ```go type HILResponse struct { DecisionID string // 决策 ID UserID string // 决策用户 ID UserName string // 用户名 UserRole string // 用户角色 Action string // approve/reject/modify/select Decision HILDecision // 决策内容 Notes string // 备注 Timestamp time.Time // 时间戳 } type HILDecision struct { ApprovedFields map[string]interface{} // 批准的字段 ModifiedFields map[string]interface{} // 修改的字段 SelectedOption any // 选择的选项 RejectionReason string // 拒绝原因 } ``` --- ## 6. 数字分段错误码系统 Synapse 协议使用数字分段错误码,便于程序化处理和国际化。 ### 6.1 错误码分段 | 分段范围 | 类别 | 说明 | |---------|------|------| | 1000-1999 | SYSTEM_ERROR | 系统错误 | | 2000-2999 | TASK_ERROR | 任务错误 | | 3000-3999 | INFO_ERROR | 信息错误 | | 4000-4999 | CAPABILITY_ERROR | 能力错误 | | 5000-5999 | SECURITY_ERROR | 安全错误 | | 6000-6999 | COMMUNICATION_ERROR | 通信错误 | | 7000-7999 | GROUP_ERROR | 群组错误 | | 8000-8999 | HIL_ERROR | HiL 错误 | | 9000-9999 | VALIDATION_ERROR | 验证错误 | ### 6.2 具体错误码定义 **系统错误(1000-1999)**: | 错误码 | 名称 | 说明 | |-----|------|------| | 1000 | ErrSystemError | 系统错误 | | 1001 | ErrInternalError | 内部错误 | | 1002 | ErrMaintenance | 系统维护中 | **任务错误(2000-2999)**: | 错误码 | 名称 | 说明 | |-----|------|------| | 2001 | ErrTaskNotFound | 任务不存在 | | 2002 | ErrTaskAlreadyCompleted | 任务已完成 | | 2003 | ErrTaskCancelled | 任务已取消 | | 2004 | ErrTaskTimeout | 任务超时 | | 2005 | ErrTaskInvalidParams | 任务参数无效 | **信息错误(3000-3999)**: | 错误码 | 名称 | 说明 | |-----|------|------| | 3001 | ErrRequiredFieldMissing | 必填字段缺失 | | 3002 | ErrInvalidFieldFormat | 字段格式无效 | | 3003 | ErrInfoNotProvided | 信息未提供 | **能力错误(4000-4999)**: | 错误码 | 名称 | 说明 | |-----|------|------| | 4001 | ErrUnsupportedTaskType | 不支持的任务类型 | | 4002 | ErrCapabilityLacking | 能力不足 | | 4003 | ErrResourceBusy | 资源繁忙 | | 4004 | ErrQuotaExceeded | 配额超限 | **安全错误(5000-5999)**: | 错误码 | 名称 | 说明 | |-----|------|------| | 5001 | ErrAuthFailed | 认证失败 | | 5002 | ErrSignatureInvalid | 签名无效 | | 5003 | ErrPermissionDenied | 权限不足 | | 5004 | ErrPolicyViolation | 策略违规 | **通信错误(6000-6999)**: | 错误码 | 名称 | 说明 | |-----|------|------| | 6001 | ErrEndpointUnreachable | 端点不可达 | | 6002 | ErrCallbackFailed | 回调失败 | | 6003 | ErrMessageFormatInvalid | 消息格式无效 | | 6004 | ErrTTLExpired | TTL 过期 | **群组错误(7000-7999)**: | 错误码 | 名称 | 说明 | |-----|------|------| | 7001 | ErrGroupNotFound | 群组不存在 | | 7002 | ErrGroupNotActive | 群组未激活 | | 7003 | ErrMemberNotFound | 成员不存在 | | 7004 | ErrNotGroupMember | 不是群组成员 | | 7005 | ErrConsensusNotReached | 未达成共识 | | 7006 | ErrRoleNotFound | 角色不存在 | | 7007 | ErrAlreadyMember | 已是成员 | | 7008 | ErrGroupFull | 群组已满 | **HiL 错误(8000-8999)**: | 错误码 | 名称 | 说明 | |-----|------|------| | 8001 | ErrHumanTimeout | 人工决策超时 | | 8002 | ErrHumanDeclined | 人工拒绝 | | 8003 | ErrEscalationLevel | 升级级别错误 | **验证错误(9000-9999)**: | 错误码 | 名称 | 说明 | |-----|------|------| | 9001 | ErrInvalidParams | 参数无效 | ### 6.3 错误响应结构 ```go type SynapseError struct { Code SynapseErrorCode `json:"code"` // 数字错误码 Category string `json:"category"` // 错误类别 Message string `json:"message"` // 错误描述 Details any `json:"details,omitempty"` // 详情 RetryAfter *int `json:"retry_after,omitempty"` // 重试等待(秒) Timestamp Timestamp `json:"timestamp"` // 时间戳 } type ErrorResponse struct { Success bool `json:"success"` Error *SynapseError `json:"error"` } ``` --- ## 7. 消息扩展字段 统一消息信封 `UnifiedSynapseMessage` 包含扩展字段,用于支持高级功能。 ### 7.1 扩展字段定义 ```go type UnifiedSynapseMessage struct { // 基础字段(协议定义) ID string `json:"id"` Version string `json:"version"` Type string `json:"type"` Sender AgentEndpoint `json:"sender"` Receiver *AgentEndpoint `json:"receiver,omitempty"` CorrelationID string `json:"correlation_id,omitempty"` ReplyTo string `json:"reply_to,omitempty"` GroupID string `json:"group_id,omitempty"` Payload json.RawMessage `json:"payload"` Timestamp Timestamp `json:"timestamp"` Signature string `json:"signature,omitempty"` // 扩展字段(实现补充) ConversationID string `json:"conversation_id,omitempty"` // 会话 ID TTL int `json:"ttl,omitempty"` // 消息存活时间(秒) Broadcast bool `json:"broadcast,omitempty"` // 是否广播 Encrypt bool `json:"encrypt,omitempty"` // 是否加密 TargetType GroupTargetType `json:"target_type,omitempty"` // 群组目标类型 TargetIDs []string `json:"target_ids,omitempty"` // 目标 ID 列表 SignatureAlgorithm string `json:"signature_algorithm,omitempty"` // 签名算法 } ``` ### 7.2 群组目标类型 ```go type GroupTargetType string const ( TargetTypeAll GroupTargetType = "all" // 所有成员 TargetTypeRole GroupTargetType = "role" // 按角色 TargetTypeSpecific GroupTargetType = "specific" // 指定成员 ) ``` ### 7.3 字段用途说明 | 字段 | 用途 | |-----|------| | `conversation_id` | 关联同一会话的多条消息,用于多轮对话场景 | | `ttl` | 消息存活时间,过期后由灵泊(Harbor)清理 | | `broadcast` | 广播标识,用于群组消息广播 | | `encrypt` | 加密标识,指示 payload 已加密 | | `target_type` + `target_ids` | 精确控制群组消息的目标范围 | | `signature_algorithm` | 明确签名算法,默认 HMAC-SHA256 | --- ## 8. 传输模式定义 Synapse 协议支持多种传输模式,适配不同的网络环境和业务场景。 ### 8.1 传输模式枚举 ```go type TransportMode string const ( TransportModeCallback TransportMode = "callback" // 异步回调(Webhook) TransportModePolling TransportMode = "polling" // 异步轮询 TransportModeSync TransportMode = "sync" // 同步等待 TransportModeHybrid TransportMode = "hybrid" // 回调 + 轮询兜底 ) ``` ### 8.2 传输偏好配置 ```go type TransportPreferences struct { Preferred TransportMode `json:"preferred"` // 首选模式 Fallback TransportMode `json:"fallback,omitempty"` // 兜底模式 CallbackEndpoint string `json:"callback_endpoint,omitempty"` // 回调地址 PollingInterval int `json:"polling_interval,omitempty"` // 轮询间隔(秒) ProgressUpdates bool `json:"progress_updates"` // 是否接收进度更新 ProgressInterval int `json:"progress_interval,omitempty"` // 进度更新间隔(秒) } // 默认传输偏好 func DefaultTransportPreferences() *TransportPreferences { return &TransportPreferences{ Preferred: TransportModeCallback, Fallback: TransportModePolling, PollingInterval: 5, ProgressUpdates: true, ProgressInterval: 10, } } ``` ### 8.3 轮询 API 类型 ```go // 任务状态响应 type TaskStatusResponse struct { Success bool `json:"success"` Task *TaskInfo `json:"task,omitempty"` Error *SynapseError `json:"error,omitempty"` } // 任务信息 type TaskInfo struct { ID string `json:"id"` Type string `json:"type"` Status string `json:"status"` Progress int `json:"progress"` // 0-100 Message string `json:"message,omitempty"` CreatedAt Timestamp `json:"created_at"` UpdatedAt Timestamp `json:"updated_at"` ETA *Timestamp `json:"eta,omitempty"` Result any `json:"result,omitempty"` Error *SynapseError `json:"error,omitempty"` ETag string `json:"etag,omitempty"` // 用于增量查询 } // 任务列表响应 type TaskListResponse struct { Success bool `json:"success"` Tasks []TaskInfo `json:"tasks"` Total int `json:"total"` Limit int `json:"limit"` Offset int `json:"offset"` HasMore bool `json:"has_more"` } // 任务事件 type TaskEvent struct { ID string `json:"id"` Type string `json:"type"` // status_update, progress, log, error, complete Timestamp Timestamp `json:"timestamp"` Data any `json:"data"` } // 任务事件流响应 type TaskEventsResponse struct { Success bool `json:"success"` Since string `json:"since"` Events []TaskEvent `json:"events"` HasMore bool `json:"has_more"` Next string `json:"next_cursor,omitempty"` } ``` ### 8.4 流式传输类型 ```go // 流数据块 type StreamChunk struct { TaskID string `json:"task_id"` Sequence int64 `json:"sequence"` ChunkType string `json:"chunk_type"` // text, binary, audio, video Data string `json:"data"` // base64(二进制) Final bool `json:"final"` Timestamp Timestamp `json:"timestamp"` } // 流完成通知 type StreamComplete struct { TaskID string `json:"task_id"` TotalChunks int64 `json:"total_chunks"` FullContentChecksum string `json:"full_content_checksum"` Result any `json:"result,omitempty"` } ``` --- ## 附录:SDK 结构 SDK 统一为一个包,包含三个子包对应三种协议: ``` sdk/ ├── doc.go # SDK 包文档 ├── p2a/ # P2A 协议客户端(外部调用) │ └── client.go ├── a2a/ # A2A 协议客户端(点对点) │ └── client.go └── a2n/ # A2N 协议客户端(群组) │ └── client.go ``` **SDK 使用示例**: ```go // P2A:外部调用方 import "synapse/sdk/p2a" client := p2a.NewClient("http://agent-endpoint") resp, err := client.SubmitTask(ctx, &p2a.TaskRequest{ TaskType: "text_generation", Payload: payload, }) // A2A:Agent 点对点通信 import "synapse/sdk/a2a" client := a2a.NewClient(myEndpoint, config) err := client.SendTaskRequest(ctx, targetEndpoint, taskPayload) // A2N:Agent 群组协作 import "synapse/sdk/a2n" client := a2n.NewClient(myEndpoint, config) err := client.JoinGroup(ctx, groupID) err := client.SubmitVote(ctx, voteID, optionID) ``` --- **文档结束** > 本实现细节文档与核心协议文档共同构成 Synapse 协议的完整规范。 > 核心协议文档:[01-synapse-raw-protocol.md](01-synapse-raw-protocol.md)、[02-p2p-protocol.md](02-p2p-protocol.md)、[03-group-protocol.md](03-group-protocol.md)、[04-caller-protocol.md](04-caller-protocol.md)