灵隙(synapse) v1.0.0 版本
This commit is contained in:
517
docs/implement/components.md
Normal file
517
docs/implement/components.md
Normal file
@@ -0,0 +1,517 @@
|
||||
# 灵隙协议组件实现规范:七大组件层
|
||||
|
||||
> 版本:1.0.0 | 层级:实现层 | 依赖:v1 各核心协议
|
||||
|
||||
根据 [v0/06-implementation-details.md](file:///e:/code/go/synapse/docs/v0/06-implementation-details.md) 的第1章内容,分别创建以下7个组件的规范(每组包含:定位说明、核心功能表、数据结构定义)。
|
||||
|
||||
---
|
||||
|
||||
## 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)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 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 列表
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 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)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 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" // 未知
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 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 // 停机模式(全部拒绝)
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
> 本文档对应 [v0/06-implementation-details.md](file:///e:/code/go/synapse/docs/v0/06-implementation-details.md) 第1章"七大组件层详细规范",是 v1 协议栈组件实现的参考依据。
|
||||
Reference in New Issue
Block a user