灵隙(synapse) v1.0.0 版本
This commit is contained in:
521
internal/components/harbor/harbor.go
Normal file
521
internal/components/harbor/harbor.go
Normal file
@@ -0,0 +1,521 @@
|
||||
// Package harbor 灵泊 - 异步队列与暂存层
|
||||
//
|
||||
// "泊"为船舶停靠。数据包如远行之舟,
|
||||
// 遇风浪(网络抖动)时暂泊于此,
|
||||
// 待风平浪静(目标就绪)再启航。
|
||||
// 不丢包、不超时,给予 Agent 异步协作的从容。
|
||||
package harbor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Message Queue - 消息队列
|
||||
// =============================================================================
|
||||
|
||||
// QueueType 队列类型
|
||||
type QueueType string
|
||||
|
||||
const (
|
||||
QueueFIFO QueueType = "fifo" // 先进先出
|
||||
QueuePriority QueueType = "priority" // 优先级队列
|
||||
QueueLIFO QueueType = "lifo" // 后进先出
|
||||
)
|
||||
|
||||
// QueuedMessage 队列中的消息
|
||||
type QueuedMessage struct {
|
||||
ID string
|
||||
Message *types.UnifiedSynapseMessage
|
||||
Priority int
|
||||
EnqueueTime time.Time
|
||||
RetryCount int
|
||||
MaxRetries int
|
||||
NextRetry time.Time
|
||||
Status QueuedStatus
|
||||
Target string // 目标 endpoint
|
||||
}
|
||||
|
||||
// QueuedStatus 队列消息状态
|
||||
type QueuedStatus string
|
||||
|
||||
const (
|
||||
QueuedPending QueuedStatus = "pending"
|
||||
QueuedProcessing QueuedStatus = "processing"
|
||||
QueuedDelivered QueuedStatus = "delivered"
|
||||
QueuedFailed QueuedStatus = "failed"
|
||||
QueuedDead QueuedStatus = "dead"
|
||||
)
|
||||
|
||||
// MessageQueue 消息队列
|
||||
type MessageQueue struct {
|
||||
mu sync.RWMutex
|
||||
messages []*QueuedMessage
|
||||
config *QueueConfig
|
||||
}
|
||||
|
||||
// QueueConfig 队列配置
|
||||
type QueueConfig struct {
|
||||
MaxSize int // 最大队列大小
|
||||
DefaultMaxRetries int // 默认最大重试次数
|
||||
DefaultRetryDelay time.Duration // 默认重试延迟
|
||||
}
|
||||
|
||||
// DefaultQueueConfig 返回默认队列配置
|
||||
func DefaultQueueConfig() *QueueConfig {
|
||||
return &QueueConfig{
|
||||
MaxSize: 10000,
|
||||
DefaultMaxRetries: 5,
|
||||
DefaultRetryDelay: 30 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// NewMessageQueue 创建消息队列
|
||||
func NewMessageQueue(config *QueueConfig) *MessageQueue {
|
||||
if config == nil {
|
||||
config = DefaultQueueConfig()
|
||||
}
|
||||
return &MessageQueue{
|
||||
messages: make([]*QueuedMessage, 0),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// Enqueue 入队
|
||||
func (mq *MessageQueue) Enqueue(msg *types.UnifiedSynapseMessage, target string, priority int) (*QueuedMessage, error) {
|
||||
mq.mu.Lock()
|
||||
defer mq.mu.Unlock()
|
||||
|
||||
if len(mq.messages) >= mq.config.MaxSize {
|
||||
return nil, fmt.Errorf("queue is full")
|
||||
}
|
||||
|
||||
qm := &QueuedMessage{
|
||||
ID: fmt.Sprintf("q-%d", time.Now().UnixNano()),
|
||||
Message: msg,
|
||||
Priority: priority,
|
||||
EnqueueTime: time.Now(),
|
||||
RetryCount: 0,
|
||||
MaxRetries: mq.config.DefaultMaxRetries,
|
||||
NextRetry: time.Now(),
|
||||
Status: QueuedPending,
|
||||
Target: target,
|
||||
}
|
||||
|
||||
// 按优先级插入
|
||||
inserted := false
|
||||
for i, m := range mq.messages {
|
||||
if priority > m.Priority {
|
||||
mq.messages = append(mq.messages[:i], append([]*QueuedMessage{qm}, mq.messages[i:]...)...)
|
||||
inserted = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !inserted {
|
||||
mq.messages = append(mq.messages, qm)
|
||||
}
|
||||
|
||||
log.Printf("[灵泊] 消息入队: %s (目标: %s, 优先级: %d)", qm.ID, target, priority)
|
||||
return qm, nil
|
||||
}
|
||||
|
||||
// Dequeue 出队
|
||||
func (mq *MessageQueue) Dequeue() (*QueuedMessage, error) {
|
||||
mq.mu.Lock()
|
||||
defer mq.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
for i, qm := range mq.messages {
|
||||
if qm.Status == QueuedPending && now.After(qm.NextRetry) {
|
||||
qm.Status = QueuedProcessing
|
||||
// 移到待处理
|
||||
mq.messages = append(mq.messages[:i], mq.messages[i+1:]...)
|
||||
return qm, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("no messages available")
|
||||
}
|
||||
|
||||
// MarkDelivered 标记为已送达
|
||||
func (mq *MessageQueue) MarkDelivered(msgID string) error {
|
||||
mq.mu.Lock()
|
||||
defer mq.mu.Unlock()
|
||||
|
||||
for _, qm := range mq.messages {
|
||||
if qm.ID == msgID {
|
||||
qm.Status = QueuedDelivered
|
||||
log.Printf("[灵泊] 消息送达: %s", msgID)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("message %s not found", msgID)
|
||||
}
|
||||
|
||||
// MarkFailed 标记为失败(会重试)
|
||||
func (mq *MessageQueue) MarkFailed(msgID string, err error) error {
|
||||
mq.mu.Lock()
|
||||
defer mq.mu.Unlock()
|
||||
|
||||
for _, qm := range mq.messages {
|
||||
if qm.ID == msgID {
|
||||
qm.RetryCount++
|
||||
if qm.RetryCount >= qm.MaxRetries {
|
||||
qm.Status = QueuedDead
|
||||
log.Printf("[灵泊] 消息失败(已死): %s (重试: %d次)", msgID, qm.RetryCount)
|
||||
} else {
|
||||
qm.Status = QueuedPending
|
||||
// 指数退避
|
||||
delay := mq.config.DefaultRetryDelay * time.Duration(1<<uint(qm.RetryCount-1))
|
||||
qm.NextRetry = time.Now().Add(delay)
|
||||
log.Printf("[灵泊] 消息失败(将重试): %s (重试: %d/%d, 下次: %v)",
|
||||
msgID, qm.RetryCount, qm.MaxRetries, delay)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("message %s not found", msgID)
|
||||
}
|
||||
|
||||
// Size 队列大小
|
||||
func (mq *MessageQueue) Size() int {
|
||||
mq.mu.RLock()
|
||||
defer mq.mu.RUnlock()
|
||||
return len(mq.messages)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Message Buffer - 消息缓冲
|
||||
// =============================================================================
|
||||
|
||||
// MessageBuffer 消息缓冲(暂存离线消息)
|
||||
type MessageBuffer struct {
|
||||
mu sync.RWMutex
|
||||
buffers map[string][]*types.UnifiedSynapseMessage // agent_id -> messages
|
||||
config *BufferConfig
|
||||
}
|
||||
|
||||
// BufferConfig 缓冲配置
|
||||
type BufferConfig struct {
|
||||
MaxPerAgent int // 每个 Agent 最大缓冲数
|
||||
MaxAge time.Duration // 消息最大存活时间
|
||||
CleanupInterval time.Duration // 清理间隔
|
||||
}
|
||||
|
||||
// DefaultBufferConfig 返回默认缓冲配置
|
||||
func DefaultBufferConfig() *BufferConfig {
|
||||
return &BufferConfig{
|
||||
MaxPerAgent: 1000,
|
||||
MaxAge: 24 * time.Hour,
|
||||
CleanupInterval: 1 * time.Hour,
|
||||
}
|
||||
}
|
||||
|
||||
// NewMessageBuffer 创建消息缓冲
|
||||
func NewMessageBuffer(config *BufferConfig) *MessageBuffer {
|
||||
if config == nil {
|
||||
config = DefaultBufferConfig()
|
||||
}
|
||||
mb := &MessageBuffer{
|
||||
buffers: make(map[string][]*types.UnifiedSynapseMessage),
|
||||
config: config,
|
||||
}
|
||||
|
||||
// 启动清理协程
|
||||
go mb.cleanupLoop()
|
||||
|
||||
return mb
|
||||
}
|
||||
|
||||
// BufferMessage 缓冲消息
|
||||
func (mb *MessageBuffer) BufferMessage(agentID string, msg *types.UnifiedSynapseMessage) error {
|
||||
mb.mu.Lock()
|
||||
defer mb.mu.Unlock()
|
||||
|
||||
buf, ok := mb.buffers[agentID]
|
||||
if !ok {
|
||||
buf = make([]*types.UnifiedSynapseMessage, 0)
|
||||
}
|
||||
|
||||
if len(buf) >= mb.config.MaxPerAgent {
|
||||
// 丢弃最旧的
|
||||
buf = buf[1:]
|
||||
}
|
||||
|
||||
mb.buffers[agentID] = append(buf, msg)
|
||||
|
||||
log.Printf("[灵泊] 缓冲消息: %s -> %s (缓冲区大小: %d)",
|
||||
msg.Sender.AgentID, agentID, len(mb.buffers[agentID]))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// FlushBuffer 清空缓冲并返回所有消息
|
||||
func (mb *MessageBuffer) FlushBuffer(agentID string) []*types.UnifiedSynapseMessage {
|
||||
mb.mu.Lock()
|
||||
defer mb.mu.Unlock()
|
||||
|
||||
buf, ok := mb.buffers[agentID]
|
||||
if !ok {
|
||||
return []*types.UnifiedSynapseMessage{}
|
||||
}
|
||||
|
||||
delete(mb.buffers, agentID)
|
||||
|
||||
log.Printf("[灵泊] 清空缓冲: %s (消息数: %d)", agentID, len(buf))
|
||||
return buf
|
||||
}
|
||||
|
||||
// GetBufferSize 获取缓冲大小
|
||||
func (mb *MessageBuffer) GetBufferSize(agentID string) int {
|
||||
mb.mu.RLock()
|
||||
defer mb.mu.RUnlock()
|
||||
return len(mb.buffers[agentID])
|
||||
}
|
||||
|
||||
// cleanupLoop 清理过期消息
|
||||
func (mb *MessageBuffer) cleanupLoop() {
|
||||
ticker := time.NewTicker(mb.config.CleanupInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for range ticker.C {
|
||||
mb.cleanup()
|
||||
}
|
||||
}
|
||||
|
||||
func (mb *MessageBuffer) cleanup() {
|
||||
mb.mu.Lock()
|
||||
defer mb.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
cleaned := 0
|
||||
|
||||
for agentID, buf := range mb.buffers {
|
||||
var newBuf []*types.UnifiedSynapseMessage
|
||||
for _, msg := range buf {
|
||||
msgTime, _ := time.Parse(time.RFC3339, string(msg.Timestamp))
|
||||
if now.Sub(msgTime) < mb.config.MaxAge {
|
||||
newBuf = append(newBuf, msg)
|
||||
} else {
|
||||
cleaned++
|
||||
}
|
||||
}
|
||||
mb.buffers[agentID] = newBuf
|
||||
}
|
||||
|
||||
if cleaned > 0 {
|
||||
log.Printf("[灵泊] 清理过期消息: %d 条", cleaned)
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Retry Manager - 重试管理器
|
||||
// =============================================================================
|
||||
|
||||
// RetryManager 重试管理器
|
||||
type RetryManager struct {
|
||||
mu sync.RWMutex
|
||||
retries map[string]*RetryEntry
|
||||
config *RetryConfig
|
||||
}
|
||||
|
||||
// RetryEntry 重试条目
|
||||
type RetryEntry struct {
|
||||
ID string
|
||||
Message *types.UnifiedSynapseMessage
|
||||
Target string
|
||||
RetryCount int
|
||||
MaxRetries int
|
||||
NextRetry time.Time
|
||||
LastError string
|
||||
BackoffBase time.Duration
|
||||
}
|
||||
|
||||
// RetryConfig 重试配置
|
||||
type RetryConfig struct {
|
||||
MaxRetries int
|
||||
BaseDelay time.Duration
|
||||
MaxDelay time.Duration
|
||||
JitterFactor float64
|
||||
}
|
||||
|
||||
// DefaultRetryConfig 返回默认重试配置
|
||||
func DefaultRetryConfig() *RetryConfig {
|
||||
return &RetryConfig{
|
||||
MaxRetries: 5,
|
||||
BaseDelay: 1 * time.Second,
|
||||
MaxDelay: 5 * time.Minute,
|
||||
JitterFactor: 0.1,
|
||||
}
|
||||
}
|
||||
|
||||
// NewRetryManager 创建重试管理器
|
||||
func NewRetryManager(config *RetryConfig) *RetryManager {
|
||||
if config == nil {
|
||||
config = DefaultRetryConfig()
|
||||
}
|
||||
return &RetryManager{
|
||||
retries: make(map[string]*RetryEntry),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// AddRetry 添加重试条目
|
||||
func (rm *RetryManager) AddRetry(msg *types.UnifiedSynapseMessage, target string) {
|
||||
rm.mu.Lock()
|
||||
defer rm.mu.Unlock()
|
||||
|
||||
id := fmt.Sprintf("retry-%d", time.Now().UnixNano())
|
||||
entry := &RetryEntry{
|
||||
ID: id,
|
||||
Message: msg,
|
||||
Target: target,
|
||||
RetryCount: 0,
|
||||
MaxRetries: rm.config.MaxRetries,
|
||||
NextRetry: time.Now().Add(rm.config.BaseDelay),
|
||||
BackoffBase: rm.config.BaseDelay,
|
||||
}
|
||||
|
||||
rm.retries[id] = entry
|
||||
|
||||
log.Printf("[灵泊] 添加重试: %s -> %s (最多 %d 次)", id, target, rm.config.MaxRetries)
|
||||
}
|
||||
|
||||
// GetPendingRetries 获取待重试的条目
|
||||
func (rm *RetryManager) GetPendingRetries() []*RetryEntry {
|
||||
rm.mu.RLock()
|
||||
defer rm.mu.RUnlock()
|
||||
|
||||
now := time.Now()
|
||||
var pending []*RetryEntry
|
||||
for _, entry := range rm.retries {
|
||||
if now.After(entry.NextRetry) && entry.RetryCount < entry.MaxRetries {
|
||||
pending = append(pending, entry)
|
||||
}
|
||||
}
|
||||
return pending
|
||||
}
|
||||
|
||||
// MarkSuccess 标记成功
|
||||
func (rm *RetryManager) MarkSuccess(retryID string) {
|
||||
rm.mu.Lock()
|
||||
defer rm.mu.Unlock()
|
||||
delete(rm.retries, retryID)
|
||||
log.Printf("[灵泊] 重试成功: %s", retryID)
|
||||
}
|
||||
|
||||
// MarkFailure 标记失败
|
||||
func (rm *RetryManager) MarkFailure(retryID string, err error) bool {
|
||||
rm.mu.Lock()
|
||||
defer rm.mu.Unlock()
|
||||
|
||||
entry, ok := rm.retries[retryID]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
entry.RetryCount++
|
||||
entry.LastError = err.Error()
|
||||
|
||||
if entry.RetryCount >= entry.MaxRetries {
|
||||
delete(rm.retries, retryID)
|
||||
log.Printf("[灵泊] 重试失败(已达上限): %s (重试 %d 次)", retryID, entry.RetryCount)
|
||||
return false
|
||||
}
|
||||
|
||||
// 指数退避 + 抖动
|
||||
delay := entry.BackoffBase * time.Duration(1<<uint(entry.RetryCount-1))
|
||||
if delay > rm.config.MaxDelay {
|
||||
delay = rm.config.MaxDelay
|
||||
}
|
||||
entry.NextRetry = time.Now().Add(delay)
|
||||
|
||||
log.Printf("[灵泊] 重试失败: %s (%d/%d, 下次: %v)",
|
||||
retryID, entry.RetryCount, entry.MaxRetries, delay)
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Stats 获取统计信息
|
||||
func (rm *RetryManager) Stats() (pending, failed int) {
|
||||
rm.mu.RLock()
|
||||
defer rm.mu.RUnlock()
|
||||
for _, entry := range rm.retries {
|
||||
if entry.RetryCount == 0 {
|
||||
pending++
|
||||
}
|
||||
}
|
||||
return pending, 0
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Harbor - 灵泊整体入口
|
||||
// =============================================================================
|
||||
|
||||
// Harbor 灵泊 - 异步队列与暂存
|
||||
type Harbor struct {
|
||||
Queue *MessageQueue
|
||||
Buffer *MessageBuffer
|
||||
Retry *RetryManager
|
||||
}
|
||||
|
||||
// NewHarbor 创建灵泊
|
||||
func NewHarbor() *Harbor {
|
||||
return &Harbor{
|
||||
Queue: NewMessageQueue(nil),
|
||||
Buffer: NewMessageBuffer(nil),
|
||||
Retry: NewRetryManager(nil),
|
||||
}
|
||||
}
|
||||
|
||||
// SendWithRetry 发送消息并重试
|
||||
func (h *Harbor) SendWithRetry(ctx context.Context, msg *types.UnifiedSynapseMessage, target string, sendFunc func(ctx context.Context, msg *types.UnifiedSynapseMessage, target string) error) error {
|
||||
// 先入队
|
||||
qm, err := h.Queue.Enqueue(msg, target, 5)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 尝试发送
|
||||
err = sendFunc(ctx, msg, target)
|
||||
if err == nil {
|
||||
h.Queue.MarkDelivered(qm.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 失败,加入重试
|
||||
h.Retry.AddRetry(msg, target)
|
||||
h.Queue.MarkFailed(qm.ID, err)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// BufferForOffline 为离线 Agent 缓冲消息
|
||||
func (h *Harbor) BufferForOffline(agentID string, msg *types.UnifiedSynapseMessage) {
|
||||
h.Buffer.BufferMessage(agentID, msg)
|
||||
}
|
||||
|
||||
// FlushAndSend 清空缓冲并发送
|
||||
func (h *Harbor) FlushAndSend(agentID string, sendFunc func(msg *types.UnifiedSynapseMessage) error) int {
|
||||
msgs := h.Buffer.FlushBuffer(agentID)
|
||||
sent := 0
|
||||
for _, msg := range msgs {
|
||||
if err := sendFunc(msg); err == nil {
|
||||
sent++
|
||||
}
|
||||
}
|
||||
return sent
|
||||
}
|
||||
|
||||
// ToJSON 导出为 JSON
|
||||
func (qm *QueuedMessage) ToJSON() string {
|
||||
data, _ := json.MarshalIndent(qm, "", " ")
|
||||
return string(data)
|
||||
}
|
||||
473
internal/components/libra/libra.go
Normal file
473
internal/components/libra/libra.go
Normal file
@@ -0,0 +1,473 @@
|
||||
// Package libra 灵衡 - 价值结算与激励层
|
||||
//
|
||||
// 权衡利弊,计量公平。此层负责将 Agent 间的
|
||||
// "智力贡献"与"资源消耗"通证化,动态定价,
|
||||
// 让多智能体经济具备自驱的盈亏平衡,
|
||||
// 而非单一中心补贴。
|
||||
package libra
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Accounting - 记账
|
||||
// =============================================================================
|
||||
|
||||
// TransactionType 交易类型
|
||||
type TransactionType string
|
||||
|
||||
const (
|
||||
TxTaskExecution TransactionType = "task_execution" // 任务执行
|
||||
TxDataSharing TransactionType = "data_sharing" // 数据共享
|
||||
TxAPIInvocation TransactionType = "api_invocation" // API 调用
|
||||
TxGroupContribution TransactionType = "group_contribution" // 群组贡献
|
||||
TxDeposit TransactionType = "deposit" // 充值
|
||||
TxWithdraw TransactionType = "withdraw" // 提现
|
||||
TxReward TransactionType = "reward" // 奖励
|
||||
TxPenalty TransactionType = "penalty" // 惩罚
|
||||
)
|
||||
|
||||
// Transaction 交易记录
|
||||
type Transaction struct {
|
||||
TxID string `json:"tx_id"`
|
||||
Type TransactionType `json:"type"`
|
||||
FromAgentID string `json:"from_agent_id"`
|
||||
ToAgentID string `json:"to_agent_id"`
|
||||
Amount float64 `json:"amount"`
|
||||
Currency string `json:"currency"`
|
||||
Description string `json:"description"`
|
||||
TaskID string `json:"task_id,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Status TransactionStatus `json:"status"`
|
||||
}
|
||||
|
||||
// TransactionStatus 交易状态
|
||||
type TransactionStatus string
|
||||
|
||||
const (
|
||||
TxStatusPending TransactionStatus = "pending"
|
||||
TxStatusCompleted TransactionStatus = "completed"
|
||||
TxStatusFailed TransactionStatus = "failed"
|
||||
TxStatusReverted TransactionStatus = "reverted"
|
||||
)
|
||||
|
||||
// Account 账户
|
||||
type Account struct {
|
||||
AgentID string `json:"agent_id"`
|
||||
Balance map[string]float64 `json:"balance"` // currency -> amount
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// Ledger 账本
|
||||
type Ledger struct {
|
||||
mu sync.RWMutex
|
||||
accounts map[string]*Account // agent_id -> account
|
||||
transactions []Transaction
|
||||
config *LedgerConfig
|
||||
}
|
||||
|
||||
// LedgerConfig 账本配置
|
||||
type LedgerConfig struct {
|
||||
DefaultCurrency string
|
||||
InitialBalance map[string]float64
|
||||
}
|
||||
|
||||
// DefaultLedgerConfig 返回默认账本配置
|
||||
func DefaultLedgerConfig() *LedgerConfig {
|
||||
return &LedgerConfig{
|
||||
DefaultCurrency: "SYN",
|
||||
InitialBalance: map[string]float64{
|
||||
"SYN": 1000.0,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// NewLedger 创建账本
|
||||
func NewLedger(config *LedgerConfig) *Ledger {
|
||||
if config == nil {
|
||||
config = DefaultLedgerConfig()
|
||||
}
|
||||
return &Ledger{
|
||||
accounts: make(map[string]*Account),
|
||||
transactions: make([]Transaction, 0),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateAccount 创建账户
|
||||
func (l *Ledger) CreateAccount(agentID string) (*Account, error) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
if _, exists := l.accounts[agentID]; exists {
|
||||
return nil, fmt.Errorf("account for agent %s already exists", agentID)
|
||||
}
|
||||
|
||||
account := &Account{
|
||||
AgentID: agentID,
|
||||
Balance: make(map[string]float64),
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
Metadata: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
// 初始余额
|
||||
for currency, amount := range l.config.InitialBalance {
|
||||
account.Balance[currency] = amount
|
||||
}
|
||||
|
||||
l.accounts[agentID] = account
|
||||
|
||||
log.Printf("[灵衡] 创建账户: %s (初始余额: %v)", agentID, account.Balance)
|
||||
return account, nil
|
||||
}
|
||||
|
||||
// GetBalance 获取余额
|
||||
func (l *Ledger) GetBalance(agentID string) (map[string]float64, error) {
|
||||
l.mu.RLock()
|
||||
defer l.mu.RUnlock()
|
||||
|
||||
account, ok := l.accounts[agentID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("account for agent %s not found", agentID)
|
||||
}
|
||||
|
||||
balance := make(map[string]float64)
|
||||
for k, v := range account.Balance {
|
||||
balance[k] = v
|
||||
}
|
||||
return balance, nil
|
||||
}
|
||||
|
||||
// Transfer 转账
|
||||
func (l *Ledger) Transfer(fromAgentID, toAgentID string, amount float64, currency string, txType TransactionType, description string, taskID string, metadata map[string]interface{}) (*Transaction, error) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
// 检查账户
|
||||
fromAccount, ok := l.accounts[fromAgentID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("sender account not found")
|
||||
}
|
||||
|
||||
toAccount, ok := l.accounts[toAgentID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("receiver account not found")
|
||||
}
|
||||
|
||||
// 检查余额
|
||||
if fromAccount.Balance[currency] < amount {
|
||||
return nil, fmt.Errorf("insufficient balance")
|
||||
}
|
||||
|
||||
// 创建交易
|
||||
tx := Transaction{
|
||||
TxID: fmt.Sprintf("tx-%d", time.Now().UnixNano()),
|
||||
Type: txType,
|
||||
FromAgentID: fromAgentID,
|
||||
ToAgentID: toAgentID,
|
||||
Amount: amount,
|
||||
Currency: currency,
|
||||
Description: description,
|
||||
TaskID: taskID,
|
||||
Metadata: metadata,
|
||||
Timestamp: time.Now(),
|
||||
Status: TxStatusCompleted,
|
||||
}
|
||||
|
||||
// 执行转账
|
||||
fromAccount.Balance[currency] -= amount
|
||||
toAccount.Balance[currency] += amount
|
||||
fromAccount.UpdatedAt = time.Now()
|
||||
toAccount.UpdatedAt = time.Now()
|
||||
|
||||
l.transactions = append(l.transactions, tx)
|
||||
|
||||
log.Printf("[灵衡] 转账: %s -> %s: %.2f %s (%s)",
|
||||
fromAgentID, toAgentID, amount, currency, description)
|
||||
|
||||
return &tx, nil
|
||||
}
|
||||
|
||||
// GetAccount 获取账户
|
||||
func (l *Ledger) GetAccount(agentID string) (*Account, error) {
|
||||
l.mu.RLock()
|
||||
defer l.mu.RUnlock()
|
||||
|
||||
account, ok := l.accounts[agentID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("account for agent %s not found", agentID)
|
||||
}
|
||||
return account, nil
|
||||
}
|
||||
|
||||
// GetTransactionHistory 获取交易历史
|
||||
func (l *Ledger) GetTransactionHistory(agentID string, limit int) []Transaction {
|
||||
l.mu.RLock()
|
||||
defer l.mu.RUnlock()
|
||||
|
||||
var history []Transaction
|
||||
for i := len(l.transactions) - 1; i >= 0 && len(history) < limit; i-- {
|
||||
tx := l.transactions[i]
|
||||
if tx.FromAgentID == agentID || tx.ToAgentID == agentID {
|
||||
history = append(history, tx)
|
||||
}
|
||||
}
|
||||
return history
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Pricing - 定价
|
||||
// =============================================================================
|
||||
|
||||
// PricingEngine 定价引擎
|
||||
type PricingEngine struct {
|
||||
mu sync.RWMutex
|
||||
prices map[string]map[string]float64 // task_type -> capability -> price
|
||||
config *PricingConfig
|
||||
}
|
||||
|
||||
// PricingConfig 定价配置
|
||||
type PricingConfig struct {
|
||||
BasePrice map[string]float64
|
||||
}
|
||||
|
||||
// DefaultPricingConfig 返回默认定价配置
|
||||
func DefaultPricingConfig() *PricingConfig {
|
||||
return &PricingConfig{
|
||||
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,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// NewPricingEngine 创建定价引擎
|
||||
func NewPricingEngine(config *PricingConfig) *PricingEngine {
|
||||
if config == nil {
|
||||
config = DefaultPricingConfig()
|
||||
}
|
||||
return &PricingEngine{
|
||||
prices: make(map[string]map[string]float64),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// SetPrice 设置价格
|
||||
func (pe *PricingEngine) SetPrice(taskType, capability string, price float64) {
|
||||
pe.mu.Lock()
|
||||
defer pe.mu.Unlock()
|
||||
|
||||
if _, ok := pe.prices[taskType]; !ok {
|
||||
pe.prices[taskType] = make(map[string]float64)
|
||||
}
|
||||
pe.prices[taskType][capability] = price
|
||||
}
|
||||
|
||||
// GetPrice 获取价格
|
||||
func (pe *PricingEngine) GetPrice(taskType string) float64 {
|
||||
pe.mu.RLock()
|
||||
defer pe.mu.RUnlock()
|
||||
|
||||
// 先查自定义价格
|
||||
if caps, ok := pe.prices[taskType]; ok {
|
||||
if price, ok := caps["default"]; ok {
|
||||
return price
|
||||
}
|
||||
}
|
||||
|
||||
// 再查基础价格
|
||||
if price, ok := pe.config.BasePrice[taskType]; ok {
|
||||
return price
|
||||
}
|
||||
|
||||
// 默认价格
|
||||
return 1.0
|
||||
}
|
||||
|
||||
// CalculateCost 计算任务成本
|
||||
func (pe *PricingEngine) CalculateCost(taskType string, complexity int, duration time.Duration) float64 {
|
||||
basePrice := pe.GetPrice(taskType)
|
||||
|
||||
// 复杂度系数
|
||||
complexityFactor := 1.0
|
||||
if complexity > 0 {
|
||||
complexityFactor = float64(complexity) * 0.5
|
||||
}
|
||||
|
||||
// 时长系数(每秒0.01)
|
||||
durationFactor := duration.Seconds() * 0.01
|
||||
|
||||
return basePrice*complexityFactor + durationFactor
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Settlement - 结算
|
||||
// =============================================================================
|
||||
|
||||
// SettlementEngine 结算引擎
|
||||
type SettlementEngine struct {
|
||||
ledger *Ledger
|
||||
pricing *PricingEngine
|
||||
config *SettlementConfig
|
||||
}
|
||||
|
||||
// SettlementConfig 结算配置
|
||||
type SettlementConfig struct {
|
||||
AutoSettlement bool
|
||||
SettlementInterval time.Duration
|
||||
}
|
||||
|
||||
// DefaultSettlementConfig 返回默认结算配置
|
||||
func DefaultSettlementConfig() *SettlementConfig {
|
||||
return &SettlementConfig{
|
||||
AutoSettlement: true,
|
||||
SettlementInterval: 1 * time.Hour,
|
||||
}
|
||||
}
|
||||
|
||||
// NewSettlementEngine 创建结算引擎
|
||||
func NewSettlementEngine(ledger *Ledger, pricing *PricingEngine, config *SettlementConfig) *SettlementEngine {
|
||||
if config == nil {
|
||||
config = DefaultSettlementConfig()
|
||||
}
|
||||
return &SettlementEngine{
|
||||
ledger: ledger,
|
||||
pricing: pricing,
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// SettleTask 结算任务
|
||||
func (se *SettlementEngine) SettleTask(taskID string, fromAgentID, toAgentID string, taskType string, complexity int, duration time.Duration, resultQuality float64) (*Transaction, error) {
|
||||
// 计算成本
|
||||
cost := se.pricing.CalculateCost(taskType, complexity, duration)
|
||||
|
||||
// 质量调整
|
||||
adjustedCost := cost * resultQuality
|
||||
|
||||
log.Printf("[灵衡] 任务结算: %s (成本: %.2f, 质量系数: %.2f, 最终: %.2f)",
|
||||
taskID, cost, resultQuality, adjustedCost)
|
||||
|
||||
// 执行转账
|
||||
return se.ledger.Transfer(
|
||||
fromAgentID,
|
||||
toAgentID,
|
||||
adjustedCost,
|
||||
"SYN",
|
||||
TxTaskExecution,
|
||||
fmt.Sprintf("任务执行: %s", taskType),
|
||||
taskID,
|
||||
map[string]interface{}{
|
||||
"task_type": taskType,
|
||||
"complexity": complexity,
|
||||
"duration_s": duration.Seconds(),
|
||||
"quality": resultQuality,
|
||||
"base_cost": cost,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// SettleGroupTask 结算群组任务(分摊费用)
|
||||
func (se *SettlementEngine) SettleGroupTask(taskID string, coordinatorID string, workerIDs []string, taskType string, totalCost float64, shares map[string]float64) error {
|
||||
// 协调者支付总费用,工作者按比例分配
|
||||
for workerID, share := range shares {
|
||||
amount := totalCost * share
|
||||
_, err := se.ledger.Transfer(
|
||||
coordinatorID,
|
||||
workerID,
|
||||
amount,
|
||||
"SYN",
|
||||
TxGroupContribution,
|
||||
fmt.Sprintf("群组任务分成: %s", taskType),
|
||||
taskID,
|
||||
map[string]interface{}{
|
||||
"share": share,
|
||||
"amount": amount,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("settle worker %s failed: %w", workerID, err)
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("[灵衡] 群组任务结算: %s (总费用: %.2f, 工作者: %d)",
|
||||
taskID, totalCost, len(workerIDs))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Reward 奖励
|
||||
func (se *SettlementEngine) Reward(agentID string, amount float64, reason string) (*Transaction, error) {
|
||||
// 创建系统账户(简化处理)
|
||||
if _, err := se.ledger.GetAccount("system"); err != nil {
|
||||
se.ledger.CreateAccount("system")
|
||||
}
|
||||
|
||||
return se.ledger.Transfer(
|
||||
"system",
|
||||
agentID,
|
||||
amount,
|
||||
"SYN",
|
||||
TxReward,
|
||||
reason,
|
||||
"",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Libra - 灵衡整体入口
|
||||
// =============================================================================
|
||||
|
||||
// Libra 灵衡 - 价值结算与激励
|
||||
type Libra struct {
|
||||
Ledger *Ledger
|
||||
Pricing *PricingEngine
|
||||
Settlement *SettlementEngine
|
||||
}
|
||||
|
||||
// NewLibra 创建灵衡
|
||||
func NewLibra() *Libra {
|
||||
ledger := NewLedger(nil)
|
||||
pricing := NewPricingEngine(nil)
|
||||
settlement := NewSettlementEngine(ledger, pricing, nil)
|
||||
|
||||
return &Libra{
|
||||
Ledger: ledger,
|
||||
Pricing: pricing,
|
||||
Settlement: settlement,
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterAgent 注册 Agent(创建账户)
|
||||
func (l *Libra) RegisterAgent(agentID string) error {
|
||||
_, err := l.Ledger.CreateAccount(agentID)
|
||||
return err
|
||||
}
|
||||
|
||||
// PayForTask 为任务付费
|
||||
func (l *Libra) PayForTask(ctx context.Context, fromAgentID, toAgentID string, msg *types.UnifiedSynapseMessage, duration time.Duration, quality float64) error {
|
||||
return nil // 简化实现
|
||||
}
|
||||
|
||||
// ToJSON 导出为 JSON
|
||||
func (tx *Transaction) ToJSON() string {
|
||||
data, _ := json.MarshalIndent(tx, "", " ")
|
||||
return string(data)
|
||||
}
|
||||
351
internal/components/meridian/meridian.go
Normal file
351
internal/components/meridian/meridian.go
Normal file
@@ -0,0 +1,351 @@
|
||||
// Package meridian 灵脉 - 寻址与路由层
|
||||
//
|
||||
// 取中医"经脉"之意。Agent 之间虽有空隙(灵隙),
|
||||
// 但暗中有能量流动的轨迹(脉)。
|
||||
//
|
||||
// 此层负责维护全局路由表,让新 Agent "通脉"入网,
|
||||
// 旧 Agent "断脉"离场,不死不休。
|
||||
package meridian
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Agent Registry - Agent 注册发现
|
||||
// =============================================================================
|
||||
|
||||
// AgentRegistry Agent 注册表
|
||||
type AgentRegistry struct {
|
||||
mu sync.RWMutex
|
||||
agents map[string]*types.AgentEndpoint // agent_id -> endpoint
|
||||
ttl map[string]time.Time // agent_id -> 过期时间
|
||||
config *RegistryConfig
|
||||
}
|
||||
|
||||
// RegistryConfig 注册表配置
|
||||
type RegistryConfig struct {
|
||||
DefaultTTL time.Duration // 默认存活时间
|
||||
}
|
||||
|
||||
// DefaultRegistryConfig 返回默认注册表配置
|
||||
func DefaultRegistryConfig() *RegistryConfig {
|
||||
return &RegistryConfig{
|
||||
DefaultTTL: 5 * time.Minute,
|
||||
}
|
||||
}
|
||||
|
||||
// NewAgentRegistry 创建 Agent 注册表
|
||||
func NewAgentRegistry(config *RegistryConfig) *AgentRegistry {
|
||||
if config == nil {
|
||||
config = DefaultRegistryConfig()
|
||||
}
|
||||
return &AgentRegistry{
|
||||
agents: make(map[string]*types.AgentEndpoint),
|
||||
ttl: make(map[string]time.Time),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// Register 注册 Agent(通脉)
|
||||
func (r *AgentRegistry) Register(endpoint types.AgentEndpoint) error {
|
||||
if endpoint.AgentID == "" {
|
||||
return fmt.Errorf("agent_id is required")
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
r.agents[endpoint.AgentID] = &endpoint
|
||||
r.ttl[endpoint.AgentID] = time.Now().Add(r.config.DefaultTTL)
|
||||
|
||||
log.Printf("[灵脉] Agent 通脉入网: %s (%s)", endpoint.AgentID, endpoint.AgentName)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Unregister 注销 Agent(断脉)
|
||||
func (r *AgentRegistry) Unregister(agentID string) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
if _, ok := r.agents[agentID]; !ok {
|
||||
return fmt.Errorf("agent %s not found", agentID)
|
||||
}
|
||||
|
||||
delete(r.agents, agentID)
|
||||
delete(r.ttl, agentID)
|
||||
|
||||
log.Printf("[灵脉] Agent 断脉离场: %s", agentID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAgent 获取 Agent 端点
|
||||
func (r *AgentRegistry) GetAgent(agentID string) (*types.AgentEndpoint, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
agent, ok := r.agents[agentID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("agent %s not found", agentID)
|
||||
}
|
||||
|
||||
// 检查是否过期
|
||||
if time.Now().After(r.ttl[agentID]) {
|
||||
return nil, fmt.Errorf("agent %s has expired", agentID)
|
||||
}
|
||||
|
||||
return agent, nil
|
||||
}
|
||||
|
||||
// ListAgents 列出所有活跃 Agent
|
||||
func (r *AgentRegistry) ListAgents() []types.AgentEndpoint {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
agents := make([]types.AgentEndpoint, 0, len(r.agents))
|
||||
now := time.Now()
|
||||
for id, agent := range r.agents {
|
||||
if now.Before(r.ttl[id]) {
|
||||
agents = append(agents, *agent)
|
||||
}
|
||||
}
|
||||
return agents
|
||||
}
|
||||
|
||||
// Heartbeat 心跳保活
|
||||
func (r *AgentRegistry) Heartbeat(agentID string) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
if _, ok := r.agents[agentID]; !ok {
|
||||
return fmt.Errorf("agent %s not registered", agentID)
|
||||
}
|
||||
|
||||
r.ttl[agentID] = time.Now().Add(r.config.DefaultTTL)
|
||||
return nil
|
||||
}
|
||||
|
||||
// FindByCapability 按能力查找 Agent
|
||||
func (r *AgentRegistry) FindByCapability(capability string) []types.AgentEndpoint {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
var result []types.AgentEndpoint
|
||||
now := time.Now()
|
||||
for id, agent := range r.agents {
|
||||
if now.Before(r.ttl[id]) {
|
||||
// 简化处理,实际需要查询能力
|
||||
result = append(result, *agent)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Message Router - 消息路由
|
||||
// =============================================================================
|
||||
|
||||
// Router 消息路由器
|
||||
type Router struct {
|
||||
registry *AgentRegistry
|
||||
|
||||
// 协议处理器
|
||||
handlers map[string]MessageHandler
|
||||
|
||||
mu sync.RWMutex
|
||||
config *RouterConfig
|
||||
}
|
||||
|
||||
// MessageHandler 消息处理器接口
|
||||
type MessageHandler interface {
|
||||
HandleMessage(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error)
|
||||
}
|
||||
|
||||
// RouterConfig 路由器配置
|
||||
type RouterConfig struct {
|
||||
MaxHops int // 最大跳数
|
||||
EnableCaching bool // 启用路由缓存
|
||||
}
|
||||
|
||||
// DefaultRouterConfig 返回默认路由器配置
|
||||
func DefaultRouterConfig() *RouterConfig {
|
||||
return &RouterConfig{
|
||||
MaxHops: 10,
|
||||
EnableCaching: true,
|
||||
}
|
||||
}
|
||||
|
||||
// NewRouter 创建消息路由器
|
||||
func NewRouter(registry *AgentRegistry, config *RouterConfig) *Router {
|
||||
if config == nil {
|
||||
config = DefaultRouterConfig()
|
||||
}
|
||||
if registry == nil {
|
||||
registry = NewAgentRegistry(nil)
|
||||
}
|
||||
return &Router{
|
||||
registry: registry,
|
||||
handlers: make(map[string]MessageHandler),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterHandler 注册消息类型处理器
|
||||
func (r *Router) RegisterHandler(msgType string, handler MessageHandler) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.handlers[msgType] = handler
|
||||
}
|
||||
|
||||
// Route 路由消息
|
||||
func (r *Router) Route(ctx context.Context, msg *types.UnifiedSynapseMessage) (*types.UnifiedSynapseMessage, error) {
|
||||
if msg.Receiver == nil {
|
||||
return nil, fmt.Errorf("receiver is required")
|
||||
}
|
||||
|
||||
// 查找接收方
|
||||
_, err := r.registry.GetAgent(msg.Receiver.AgentID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("route failed: agent not found: %w", err)
|
||||
}
|
||||
|
||||
// 查找处理器
|
||||
r.mu.RLock()
|
||||
handler, ok := r.handlers[msg.Type]
|
||||
r.mu.RUnlock()
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("no handler for message type: %s", msg.Type)
|
||||
}
|
||||
|
||||
log.Printf("[灵脉] 路由消息: %s -> %s (类型: %s)",
|
||||
msg.Sender.AgentID, msg.Receiver.AgentID, msg.Type)
|
||||
|
||||
return handler.HandleMessage(ctx, msg)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Topology Manager - 拓扑管理
|
||||
// =============================================================================
|
||||
|
||||
// TopologyType 拓扑类型
|
||||
type TopologyType string
|
||||
|
||||
const (
|
||||
TopologyStar TopologyType = "star" // 星型拓扑
|
||||
TopologyMesh TopologyType = "mesh" // 网状拓扑
|
||||
TopologyRing TopologyType = "ring" // 环形拓扑
|
||||
TopologyTree TopologyType = "tree" // 树形拓扑
|
||||
TopologyHybrid TopologyType = "hybrid" // 混合拓扑
|
||||
)
|
||||
|
||||
// TopologyManager 拓扑管理器
|
||||
type TopologyManager struct {
|
||||
mu sync.RWMutex
|
||||
topologies map[string]*NetworkTopology
|
||||
}
|
||||
|
||||
// NetworkTopology 网络拓扑
|
||||
type NetworkTopology struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type TopologyType `json:"type"`
|
||||
Nodes map[string]bool `json:"nodes"`
|
||||
Edges map[string][]string `json:"edges"` // node_id -> connected_nodes
|
||||
Config map[string]interface{} `json:"config"`
|
||||
}
|
||||
|
||||
// NewTopologyManager 创建拓扑管理器
|
||||
func NewTopologyManager() *TopologyManager {
|
||||
return &TopologyManager{
|
||||
topologies: make(map[string]*NetworkTopology),
|
||||
}
|
||||
}
|
||||
|
||||
// CreateTopology 创建拓扑
|
||||
func (tm *TopologyManager) CreateTopology(id, name string, topologyType TopologyType) *NetworkTopology {
|
||||
tm.mu.Lock()
|
||||
defer tm.mu.Unlock()
|
||||
|
||||
topo := &NetworkTopology{
|
||||
ID: id,
|
||||
Name: name,
|
||||
Type: topologyType,
|
||||
Nodes: make(map[string]bool),
|
||||
Edges: make(map[string][]string),
|
||||
Config: make(map[string]interface{}),
|
||||
}
|
||||
tm.topologies[id] = topo
|
||||
|
||||
log.Printf("[灵脉] 创建拓扑: %s (%s, %s)", id, name, topologyType)
|
||||
return topo
|
||||
}
|
||||
|
||||
// AddNode 添加节点
|
||||
func (tm *TopologyManager) AddNode(topologyID, nodeID string) error {
|
||||
tm.mu.Lock()
|
||||
defer tm.mu.Unlock()
|
||||
|
||||
topo, ok := tm.topologies[topologyID]
|
||||
if !ok {
|
||||
return fmt.Errorf("topology %s not found", topologyID)
|
||||
}
|
||||
|
||||
topo.Nodes[nodeID] = true
|
||||
if _, ok := topo.Edges[nodeID]; !ok {
|
||||
topo.Edges[nodeID] = []string{}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddEdge 添加边
|
||||
func (tm *TopologyManager) AddEdge(topologyID, from, to string) error {
|
||||
tm.mu.Lock()
|
||||
defer tm.mu.Unlock()
|
||||
|
||||
topo, ok := tm.topologies[topologyID]
|
||||
if !ok {
|
||||
return fmt.Errorf("topology %s not found", topologyID)
|
||||
}
|
||||
|
||||
if !topo.Nodes[from] || !topo.Nodes[to] {
|
||||
return fmt.Errorf("node not found in topology")
|
||||
}
|
||||
|
||||
topo.Edges[from] = append(topo.Edges[from], to)
|
||||
topo.Edges[to] = append(topo.Edges[to], from)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetNeighbors 获取邻居节点
|
||||
func (tm *TopologyManager) GetNeighbors(topologyID, nodeID string) ([]string, error) {
|
||||
tm.mu.RLock()
|
||||
defer tm.mu.RUnlock()
|
||||
|
||||
topo, ok := tm.topologies[topologyID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("topology %s not found", topologyID)
|
||||
}
|
||||
|
||||
neighbors, ok := topo.Edges[nodeID]
|
||||
if !ok {
|
||||
return []string{}, nil
|
||||
}
|
||||
|
||||
return neighbors, nil
|
||||
}
|
||||
|
||||
// ToJSON 导出为 JSON
|
||||
func (t *NetworkTopology) ToJSON() string {
|
||||
data, _ := json.MarshalIndent(t, "", " ")
|
||||
return string(data)
|
||||
}
|
||||
540
internal/components/panorama/panorama.go
Normal file
540
internal/components/panorama/panorama.go
Normal file
@@ -0,0 +1,540 @@
|
||||
// Package panorama 灵瞰 - 可观测与度量层
|
||||
//
|
||||
// 居高临下,俯瞰全局。此层不参与业务交互,
|
||||
// 却如"天眼"般记录每一帧交互的耗时、置信度与资源消耗,
|
||||
// 让黑盒群体智能变为白盒可解释的图景。
|
||||
package panorama
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Tracing - 链路追踪
|
||||
// =============================================================================
|
||||
|
||||
// Trace 追踪链路
|
||||
type Trace struct {
|
||||
TraceID string `json:"trace_id"`
|
||||
RootSpan *Span `json:"root_span"`
|
||||
Spans map[string]*Span `json:"spans"`
|
||||
StartTime time.Time `json:"start_time"`
|
||||
EndTime *time.Time `json:"end_time,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// Span 追踪跨度
|
||||
type Span struct {
|
||||
SpanID string `json:"span_id"`
|
||||
TraceID string `json:"trace_id"`
|
||||
ParentID string `json:"parent_id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Service string `json:"service"`
|
||||
AgentID string `json:"agent_id"`
|
||||
StartTime time.Time `json:"start_time"`
|
||||
EndTime *time.Time `json:"end_time,omitempty"`
|
||||
Duration time.Duration `json:"duration_ms"`
|
||||
Status SpanStatus `json:"status"`
|
||||
Tags map[string]string `json:"tags,omitempty"`
|
||||
Logs []SpanLog `json:"logs,omitempty"`
|
||||
Attributes map[string]interface{} `json:"attributes,omitempty"`
|
||||
}
|
||||
|
||||
// SpanStatus 跨度状态
|
||||
type SpanStatus string
|
||||
|
||||
const (
|
||||
SpanStatusPending SpanStatus = "pending"
|
||||
SpanStatusRunning SpanStatus = "running"
|
||||
SpanStatusSuccess SpanStatus = "success"
|
||||
SpanStatusFailed SpanStatus = "failed"
|
||||
SpanStatusCancelled SpanStatus = "cancelled"
|
||||
)
|
||||
|
||||
// SpanLog 跨度日志
|
||||
type SpanLog struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Message string `json:"message"`
|
||||
Fields map[string]interface{} `json:"fields,omitempty"`
|
||||
}
|
||||
|
||||
// Tracer 追踪器
|
||||
type Tracer struct {
|
||||
mu sync.RWMutex
|
||||
traces map[string]*Trace
|
||||
config *TracerConfig
|
||||
}
|
||||
|
||||
// TracerConfig 追踪器配置
|
||||
type TracerConfig struct {
|
||||
MaxTraces int
|
||||
MaxSpansPerTrace int
|
||||
}
|
||||
|
||||
// DefaultTracerConfig 返回默认追踪器配置
|
||||
func DefaultTracerConfig() *TracerConfig {
|
||||
return &TracerConfig{
|
||||
MaxTraces: 1000,
|
||||
MaxSpansPerTrace: 100,
|
||||
}
|
||||
}
|
||||
|
||||
// NewTracer 创建追踪器
|
||||
func NewTracer(config *TracerConfig) *Tracer {
|
||||
if config == nil {
|
||||
config = DefaultTracerConfig()
|
||||
}
|
||||
return &Tracer{
|
||||
traces: make(map[string]*Trace),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// StartTrace 开始追踪
|
||||
func (t *Tracer) StartTrace(traceID, name string, agentID string) *Trace {
|
||||
if traceID == "" {
|
||||
traceID = fmt.Sprintf("trace-%d", time.Now().UnixNano())
|
||||
}
|
||||
|
||||
rootSpan := &Span{
|
||||
SpanID: fmt.Sprintf("span-%d", time.Now().UnixNano()),
|
||||
TraceID: traceID,
|
||||
Name: name,
|
||||
Service: "synapse",
|
||||
AgentID: agentID,
|
||||
StartTime: time.Now(),
|
||||
Status: SpanStatusRunning,
|
||||
Tags: make(map[string]string),
|
||||
Logs: make([]SpanLog, 0),
|
||||
Attributes: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
trace := &Trace{
|
||||
TraceID: traceID,
|
||||
RootSpan: rootSpan,
|
||||
Spans: map[string]*Span{rootSpan.SpanID: rootSpan},
|
||||
StartTime: time.Now(),
|
||||
Metadata: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
t.traces[traceID] = trace
|
||||
t.mu.Unlock()
|
||||
|
||||
log.Printf("[灵瞰] 开始追踪: %s (%s)", traceID, name)
|
||||
return trace
|
||||
}
|
||||
|
||||
// StartSpan 开始跨度
|
||||
func (t *Tracer) StartSpan(traceID, parentSpanID, name, agentID string) (*Span, error) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
trace, ok := t.traces[traceID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("trace %s not found", traceID)
|
||||
}
|
||||
|
||||
span := &Span{
|
||||
SpanID: fmt.Sprintf("span-%d", time.Now().UnixNano()),
|
||||
TraceID: traceID,
|
||||
ParentID: parentSpanID,
|
||||
Name: name,
|
||||
Service: "synapse",
|
||||
AgentID: agentID,
|
||||
StartTime: time.Now(),
|
||||
Status: SpanStatusRunning,
|
||||
Tags: make(map[string]string),
|
||||
Logs: make([]SpanLog, 0),
|
||||
Attributes: make(map[string]interface{}),
|
||||
}
|
||||
|
||||
trace.Spans[span.SpanID] = span
|
||||
return span, nil
|
||||
}
|
||||
|
||||
// EndSpan 结束跨度
|
||||
func (t *Tracer) EndSpan(traceID, spanID string, status SpanStatus, err error) error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
trace, ok := t.traces[traceID]
|
||||
if !ok {
|
||||
return fmt.Errorf("trace %s not found", traceID)
|
||||
}
|
||||
|
||||
span, ok := trace.Spans[spanID]
|
||||
if !ok {
|
||||
return fmt.Errorf("span %s not found", spanID)
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
span.EndTime = &now
|
||||
span.Duration = now.Sub(span.StartTime)
|
||||
span.Status = status
|
||||
|
||||
if err != nil {
|
||||
span.Logs = append(span.Logs, SpanLog{
|
||||
Timestamp: now,
|
||||
Message: err.Error(),
|
||||
Fields: map[string]interface{}{"error": err.Error()},
|
||||
})
|
||||
}
|
||||
|
||||
// 如果是根跨度,结束整个追踪
|
||||
if span == trace.RootSpan {
|
||||
trace.EndTime = &now
|
||||
}
|
||||
|
||||
log.Printf("[灵瞰] 结束跨度: %s (%s) - %v", spanID, span.Name, span.Duration)
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddSpanLog 添加日志
|
||||
func (t *Tracer) AddSpanLog(traceID, spanID, message string, fields map[string]interface{}) error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
trace, ok := t.traces[traceID]
|
||||
if !ok {
|
||||
return fmt.Errorf("trace %s not found", traceID)
|
||||
}
|
||||
|
||||
span, ok := trace.Spans[spanID]
|
||||
if !ok {
|
||||
return fmt.Errorf("span %s not found", spanID)
|
||||
}
|
||||
|
||||
span.Logs = append(span.Logs, SpanLog{
|
||||
Timestamp: time.Now(),
|
||||
Message: message,
|
||||
Fields: fields,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetTrace 获取追踪
|
||||
func (t *Tracer) GetTrace(traceID string) (*Trace, error) {
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
|
||||
trace, ok := t.traces[traceID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("trace %s not found", traceID)
|
||||
}
|
||||
return trace, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Metrics - 指标收集
|
||||
// =============================================================================
|
||||
|
||||
// MetricType 指标类型
|
||||
type MetricType string
|
||||
|
||||
const (
|
||||
MetricCounter MetricType = "counter"
|
||||
MetricGauge MetricType = "gauge"
|
||||
MetricHistogram MetricType = "histogram"
|
||||
)
|
||||
|
||||
// Metric 指标
|
||||
type Metric struct {
|
||||
Name string `json:"name"`
|
||||
Type MetricType `json:"type"`
|
||||
Value float64 `json:"value"`
|
||||
Labels map[string]string `json:"labels"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
}
|
||||
|
||||
// MetricsCollector 指标收集器
|
||||
type MetricsCollector struct {
|
||||
mu sync.RWMutex
|
||||
metrics map[string]*Metric
|
||||
histories map[string][]Metric
|
||||
config *MetricsConfig
|
||||
}
|
||||
|
||||
// MetricsConfig 指标配置
|
||||
type MetricsConfig struct {
|
||||
MaxHistory int
|
||||
}
|
||||
|
||||
// DefaultMetricsConfig 返回默认指标配置
|
||||
func DefaultMetricsConfig() *MetricsConfig {
|
||||
return &MetricsConfig{
|
||||
MaxHistory: 1000,
|
||||
}
|
||||
}
|
||||
|
||||
// NewMetricsCollector 创建指标收集器
|
||||
func NewMetricsCollector(config *MetricsConfig) *MetricsCollector {
|
||||
if config == nil {
|
||||
config = DefaultMetricsConfig()
|
||||
}
|
||||
return &MetricsCollector{
|
||||
metrics: make(map[string]*Metric),
|
||||
histories: make(map[string][]Metric),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// RecordMetric 记录指标
|
||||
func (mc *MetricsCollector) RecordMetric(name string, metricType MetricType, value float64, labels map[string]string) {
|
||||
mc.mu.Lock()
|
||||
defer mc.mu.Unlock()
|
||||
|
||||
key := name + labelKey(labels)
|
||||
metric := &Metric{
|
||||
Name: name,
|
||||
Type: metricType,
|
||||
Value: value,
|
||||
Labels: labels,
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
mc.metrics[key] = metric
|
||||
|
||||
// 记录历史
|
||||
if history, ok := mc.histories[key]; ok {
|
||||
if len(history) >= mc.config.MaxHistory {
|
||||
history = history[1:]
|
||||
}
|
||||
mc.histories[key] = append(history, *metric)
|
||||
} else {
|
||||
mc.histories[key] = []Metric{*metric}
|
||||
}
|
||||
}
|
||||
|
||||
// IncrementCounter 计数器递增
|
||||
func (mc *MetricsCollector) IncrementCounter(name string, labels map[string]string, delta float64) {
|
||||
mc.mu.Lock()
|
||||
defer mc.mu.Unlock()
|
||||
|
||||
key := name + labelKey(labels)
|
||||
metric, ok := mc.metrics[key]
|
||||
if !ok {
|
||||
metric = &Metric{
|
||||
Name: name,
|
||||
Type: MetricCounter,
|
||||
Value: 0,
|
||||
Labels: labels,
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
mc.metrics[key] = metric
|
||||
}
|
||||
metric.Value += delta
|
||||
metric.Timestamp = time.Now()
|
||||
}
|
||||
|
||||
// SetGauge 设置计量值
|
||||
func (mc *MetricsCollector) SetGauge(name string, labels map[string]string, value float64) {
|
||||
mc.RecordMetric(name, MetricGauge, value, labels)
|
||||
}
|
||||
|
||||
// GetMetric 获取指标
|
||||
func (mc *MetricsCollector) GetMetric(name string, labels map[string]string) (*Metric, error) {
|
||||
mc.mu.RLock()
|
||||
defer mc.mu.RUnlock()
|
||||
|
||||
key := name + labelKey(labels)
|
||||
metric, ok := mc.metrics[key]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("metric %s not found", name)
|
||||
}
|
||||
return metric, nil
|
||||
}
|
||||
|
||||
// GetAllMetrics 获取所有指标
|
||||
func (mc *MetricsCollector) GetAllMetrics() []Metric {
|
||||
mc.mu.RLock()
|
||||
defer mc.mu.RUnlock()
|
||||
|
||||
metrics := make([]Metric, 0, len(mc.metrics))
|
||||
for _, m := range mc.metrics {
|
||||
metrics = append(metrics, *m)
|
||||
}
|
||||
return metrics
|
||||
}
|
||||
|
||||
// GetMetricHistory 获取指标历史
|
||||
func (mc *MetricsCollector) GetMetricHistory(name string, labels map[string]string) ([]Metric, error) {
|
||||
mc.mu.RLock()
|
||||
defer mc.mu.RUnlock()
|
||||
|
||||
key := name + labelKey(labels)
|
||||
history, ok := mc.histories[key]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("metric %s not found", name)
|
||||
}
|
||||
|
||||
result := make([]Metric, len(history))
|
||||
copy(result, history)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func labelKey(labels map[string]string) string {
|
||||
if len(labels) == 0 {
|
||||
return ""
|
||||
}
|
||||
data, _ := json.Marshal(labels)
|
||||
return string(data)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Health Check - 健康检查
|
||||
// =============================================================================
|
||||
|
||||
// HealthStatus 健康状态
|
||||
type HealthStatus string
|
||||
|
||||
const (
|
||||
HealthStatusHealthy HealthStatus = "healthy"
|
||||
HealthStatusDegraded HealthStatus = "degraded"
|
||||
HealthStatusUnhealthy HealthStatus = "unhealthy"
|
||||
HealthStatusUnknown HealthStatus = "unknown"
|
||||
)
|
||||
|
||||
// HealthCheck 健康检查结果
|
||||
type HealthCheck struct {
|
||||
Name string `json:"name"`
|
||||
Status HealthStatus `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Details map[string]interface{} `json:"details,omitempty"`
|
||||
CheckedAt time.Time `json:"checked_at"`
|
||||
}
|
||||
|
||||
// HealthChecker 健康检查器
|
||||
type HealthChecker struct {
|
||||
mu sync.RWMutex
|
||||
checks map[string]HealthCheckable
|
||||
config *HealthConfig
|
||||
}
|
||||
|
||||
// HealthCheckable 可健康检查的接口
|
||||
type HealthCheckable interface {
|
||||
HealthCheck(ctx context.Context) *HealthCheck
|
||||
}
|
||||
|
||||
// HealthConfig 健康检查配置
|
||||
type HealthConfig struct {
|
||||
CheckInterval time.Duration
|
||||
}
|
||||
|
||||
// DefaultHealthConfig 返回默认健康检查配置
|
||||
func DefaultHealthConfig() *HealthConfig {
|
||||
return &HealthConfig{
|
||||
CheckInterval: 30 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// NewHealthChecker 创建健康检查器
|
||||
func NewHealthChecker(config *HealthConfig) *HealthChecker {
|
||||
if config == nil {
|
||||
config = DefaultHealthConfig()
|
||||
}
|
||||
return &HealthChecker{
|
||||
checks: make(map[string]HealthCheckable),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterCheck 注册健康检查
|
||||
func (hc *HealthChecker) RegisterCheck(name string, checkable HealthCheckable) {
|
||||
hc.mu.Lock()
|
||||
defer hc.mu.Unlock()
|
||||
hc.checks[name] = checkable
|
||||
}
|
||||
|
||||
// CheckAll 检查所有组件
|
||||
func (hc *HealthChecker) CheckAll(ctx context.Context) map[string]*HealthCheck {
|
||||
hc.mu.RLock()
|
||||
defer hc.mu.RUnlock()
|
||||
|
||||
results := make(map[string]*HealthCheck)
|
||||
for name, checkable := range hc.checks {
|
||||
results[name] = checkable.HealthCheck(ctx)
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
// OverallStatus 总体健康状态
|
||||
func (hc *HealthChecker) OverallStatus(ctx context.Context) HealthStatus {
|
||||
results := hc.CheckAll(ctx)
|
||||
|
||||
allHealthy := true
|
||||
anyUnhealthy := false
|
||||
|
||||
for _, result := range results {
|
||||
switch result.Status {
|
||||
case HealthStatusUnhealthy:
|
||||
anyUnhealthy = true
|
||||
case HealthStatusDegraded:
|
||||
allHealthy = false
|
||||
case HealthStatusUnknown:
|
||||
allHealthy = false
|
||||
}
|
||||
}
|
||||
|
||||
if anyUnhealthy {
|
||||
return HealthStatusUnhealthy
|
||||
}
|
||||
if !allHealthy {
|
||||
return HealthStatusDegraded
|
||||
}
|
||||
return HealthStatusHealthy
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Panorama - 灵瞰整体入口
|
||||
// =============================================================================
|
||||
|
||||
// Panorama 灵瞰 - 可观测与度量
|
||||
type Panorama struct {
|
||||
Tracer *Tracer
|
||||
Metrics *MetricsCollector
|
||||
Health *HealthChecker
|
||||
}
|
||||
|
||||
// NewPanorama 创建灵瞰
|
||||
func NewPanorama() *Panorama {
|
||||
return &Panorama{
|
||||
Tracer: NewTracer(nil),
|
||||
Metrics: NewMetricsCollector(nil),
|
||||
Health: NewHealthChecker(nil),
|
||||
}
|
||||
}
|
||||
|
||||
// RecordMessage 记录消息(自动增加指标)
|
||||
func (p *Panorama) RecordMessage(msg *types.UnifiedSynapseMessage, direction string, duration time.Duration) {
|
||||
labels := map[string]string{
|
||||
"type": msg.Type,
|
||||
"direction": direction,
|
||||
"sender": msg.Sender.AgentID,
|
||||
}
|
||||
|
||||
p.Metrics.IncrementCounter("synapse_messages_total", labels, 1)
|
||||
p.Metrics.RecordMetric("synapse_message_duration_seconds", MetricHistogram,
|
||||
duration.Seconds(), labels)
|
||||
}
|
||||
|
||||
// StartTaskTrace 开始任务追踪
|
||||
func (p *Panorama) StartTaskTrace(taskID, taskType, agentID string) string {
|
||||
trace := p.Tracer.StartTrace(taskID, fmt.Sprintf("task:%s", taskType), agentID)
|
||||
return trace.TraceID
|
||||
}
|
||||
|
||||
// ToJSON 导出为 JSON
|
||||
func (t *Trace) ToJSON() string {
|
||||
data, _ := json.MarshalIndent(t, "", " ")
|
||||
return string(data)
|
||||
}
|
||||
503
internal/components/pivot/pivot.go
Normal file
503
internal/components/pivot/pivot.go
Normal file
@@ -0,0 +1,503 @@
|
||||
// Package pivot 灵枢 - 紧急制动与治理层
|
||||
//
|
||||
// 取自《灵枢经》(黄帝内经下半部),
|
||||
// 讲的是针灸经络之枢纽。
|
||||
// 这是整个协议的"总闸"与"方向盘",
|
||||
// 不轻易触发,但触发时能以最小代价
|
||||
// 重置整个 Synapse 网络的状态。
|
||||
package pivot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Circuit Breaker - 熔断器
|
||||
// =============================================================================
|
||||
|
||||
// CircuitState 熔断器状态
|
||||
type CircuitState string
|
||||
|
||||
const (
|
||||
CircuitClosed CircuitState = "closed" // 关闭:正常流通
|
||||
CircuitOpen CircuitState = "open" // 打开:熔断,拒绝请求
|
||||
CircuitHalfOpen CircuitState = "half_open" // 半开:尝试恢复
|
||||
)
|
||||
|
||||
// CircuitBreaker 熔断器
|
||||
type CircuitBreaker struct {
|
||||
mu sync.RWMutex
|
||||
name string
|
||||
state CircuitState
|
||||
failureCount int
|
||||
successCount int
|
||||
threshold int // 失败阈值
|
||||
timeout time.Duration // 熔断超时
|
||||
lastFailure time.Time
|
||||
lastSuccess time.Time
|
||||
}
|
||||
|
||||
// CircuitBreakerConfig 熔断器配置
|
||||
type CircuitBreakerConfig struct {
|
||||
Threshold int
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// DefaultCircuitBreakerConfig 返回默认熔断器配置
|
||||
func DefaultCircuitBreakerConfig() *CircuitBreakerConfig {
|
||||
return &CircuitBreakerConfig{
|
||||
Threshold: 5,
|
||||
Timeout: 30 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// NewCircuitBreaker 创建熔断器
|
||||
func NewCircuitBreaker(name string, config *CircuitBreakerConfig) *CircuitBreaker {
|
||||
if config == nil {
|
||||
config = DefaultCircuitBreakerConfig()
|
||||
}
|
||||
return &CircuitBreaker{
|
||||
name: name,
|
||||
state: CircuitClosed,
|
||||
threshold: config.Threshold,
|
||||
timeout: config.Timeout,
|
||||
}
|
||||
}
|
||||
|
||||
// Allow 是否允许请求通过
|
||||
func (cb *CircuitBreaker) Allow() bool {
|
||||
cb.mu.RLock()
|
||||
defer cb.mu.RUnlock()
|
||||
|
||||
switch cb.state {
|
||||
case CircuitClosed:
|
||||
return true
|
||||
case CircuitOpen:
|
||||
// 检查是否超时,可以进入半开状态
|
||||
if time.Since(cb.lastFailure) > cb.timeout {
|
||||
cb.mu.RUnlock()
|
||||
cb.mu.Lock()
|
||||
if cb.state == CircuitOpen && time.Since(cb.lastFailure) > cb.timeout {
|
||||
cb.state = CircuitHalfOpen
|
||||
cb.successCount = 0
|
||||
log.Printf("[灵枢] 熔断器 %s 进入半开状态", cb.name)
|
||||
}
|
||||
cb.mu.Unlock()
|
||||
cb.mu.RLock()
|
||||
return cb.state == CircuitHalfOpen
|
||||
}
|
||||
return false
|
||||
case CircuitHalfOpen:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// RecordSuccess 记录成功
|
||||
func (cb *CircuitBreaker) RecordSuccess() {
|
||||
cb.mu.Lock()
|
||||
defer cb.mu.Unlock()
|
||||
|
||||
cb.lastSuccess = time.Now()
|
||||
|
||||
switch cb.state {
|
||||
case CircuitHalfOpen:
|
||||
cb.successCount++
|
||||
// 连续成功几次后关闭熔断
|
||||
if cb.successCount >= 3 {
|
||||
cb.state = CircuitClosed
|
||||
cb.failureCount = 0
|
||||
cb.successCount = 0
|
||||
log.Printf("[灵枢] 熔断器 %s 恢复关闭", cb.name)
|
||||
}
|
||||
case CircuitClosed:
|
||||
cb.failureCount = 0
|
||||
}
|
||||
}
|
||||
|
||||
// RecordFailure 记录失败
|
||||
func (cb *CircuitBreaker) RecordFailure() {
|
||||
cb.mu.Lock()
|
||||
defer cb.mu.Unlock()
|
||||
|
||||
cb.failureCount++
|
||||
cb.lastFailure = time.Now()
|
||||
|
||||
switch cb.state {
|
||||
case CircuitClosed:
|
||||
if cb.failureCount >= cb.threshold {
|
||||
cb.state = CircuitOpen
|
||||
log.Printf("[灵枢] 熔断器 %s 触发熔断 (失败: %d次)", cb.name, cb.failureCount)
|
||||
}
|
||||
case CircuitHalfOpen:
|
||||
cb.state = CircuitOpen
|
||||
log.Printf("[灵枢] 熔断器 %s 半开失败,重新熔断", cb.name)
|
||||
}
|
||||
}
|
||||
|
||||
// State 获取当前状态
|
||||
func (cb *CircuitBreaker) State() CircuitState {
|
||||
cb.mu.RLock()
|
||||
defer cb.mu.RUnlock()
|
||||
return cb.state
|
||||
}
|
||||
|
||||
// Reset 重置熔断器
|
||||
func (cb *CircuitBreaker) Reset() {
|
||||
cb.mu.Lock()
|
||||
defer cb.mu.Unlock()
|
||||
|
||||
cb.state = CircuitClosed
|
||||
cb.failureCount = 0
|
||||
cb.successCount = 0
|
||||
log.Printf("[灵枢] 熔断器 %s 已重置", cb.name)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Governance - 治理
|
||||
// =============================================================================
|
||||
|
||||
// GovernanceLevel 治理级别
|
||||
type GovernanceLevel int
|
||||
|
||||
const (
|
||||
GovLevelNormal GovernanceLevel = iota // 正常运行
|
||||
GovLevelWatch // 观察模式
|
||||
GovLevelRestricted // 受限模式
|
||||
GovLevelEmergency // 紧急模式
|
||||
GovLevelShutdown // 停机模式
|
||||
)
|
||||
|
||||
func (l GovernanceLevel) String() string {
|
||||
switch l {
|
||||
case GovLevelNormal:
|
||||
return "normal"
|
||||
case GovLevelWatch:
|
||||
return "watch"
|
||||
case GovLevelRestricted:
|
||||
return "restricted"
|
||||
case GovLevelEmergency:
|
||||
return "emergency"
|
||||
case GovLevelShutdown:
|
||||
return "shutdown"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
// GovernanceManager 治理管理器
|
||||
type GovernanceManager struct {
|
||||
mu sync.RWMutex
|
||||
level GovernanceLevel
|
||||
policies map[string]GovernancePolicy
|
||||
blacklist map[string]bool // 被封禁的 agent_id
|
||||
whitelist map[string]bool // 白名单
|
||||
config *GovernanceConfig
|
||||
}
|
||||
|
||||
// GovernancePolicy 治理策略
|
||||
type GovernancePolicy struct {
|
||||
ID string
|
||||
Name string
|
||||
Description string
|
||||
Enabled bool
|
||||
Level GovernanceLevel
|
||||
Evaluate func(ctx context.Context, msg *types.UnifiedSynapseMessage) (bool, string)
|
||||
}
|
||||
|
||||
// GovernanceConfig 治理配置
|
||||
type GovernanceConfig struct {
|
||||
InitialLevel GovernanceLevel
|
||||
}
|
||||
|
||||
// DefaultGovernanceConfig 返回默认治理配置
|
||||
func DefaultGovernanceConfig() *GovernanceConfig {
|
||||
return &GovernanceConfig{
|
||||
InitialLevel: GovLevelNormal,
|
||||
}
|
||||
}
|
||||
|
||||
// NewGovernanceManager 创建治理管理器
|
||||
func NewGovernanceManager(config *GovernanceConfig) *GovernanceManager {
|
||||
if config == nil {
|
||||
config = DefaultGovernanceConfig()
|
||||
}
|
||||
return &GovernanceManager{
|
||||
level: config.InitialLevel,
|
||||
policies: make(map[string]GovernancePolicy),
|
||||
blacklist: make(map[string]bool),
|
||||
whitelist: make(map[string]bool),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// SetLevel 设置治理级别
|
||||
func (gm *GovernanceManager) SetLevel(level GovernanceLevel) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
|
||||
gm.level = level
|
||||
log.Printf("[灵枢] 治理级别调整为: %s", level.String())
|
||||
}
|
||||
|
||||
// GetLevel 获取治理级别
|
||||
func (gm *GovernanceManager) GetLevel() GovernanceLevel {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
return gm.level
|
||||
}
|
||||
|
||||
// AddPolicy 添加治理策略
|
||||
func (gm *GovernanceManager) AddPolicy(policy GovernancePolicy) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
gm.policies[policy.ID] = policy
|
||||
}
|
||||
|
||||
// RemovePolicy 移除治理策略
|
||||
func (gm *GovernanceManager) RemovePolicy(policyID string) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
delete(gm.policies, policyID)
|
||||
}
|
||||
|
||||
// BanAgent 封禁 Agent
|
||||
func (gm *GovernanceManager) BanAgent(agentID, reason string) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
gm.blacklist[agentID] = true
|
||||
log.Printf("[灵枢] 封禁 Agent: %s (%s)", agentID, reason)
|
||||
}
|
||||
|
||||
// UnbanAgent 解封 Agent
|
||||
func (gm *GovernanceManager) UnbanAgent(agentID string) {
|
||||
gm.mu.Lock()
|
||||
defer gm.mu.Unlock()
|
||||
delete(gm.blacklist, agentID)
|
||||
log.Printf("[灵枢] 解封 Agent: %s", agentID)
|
||||
}
|
||||
|
||||
// IsBanned 检查是否被封禁
|
||||
func (gm *GovernanceManager) IsBanned(agentID string) bool {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
return gm.blacklist[agentID]
|
||||
}
|
||||
|
||||
// AllowMessage 检查是否允许消息通过
|
||||
func (gm *GovernanceManager) AllowMessage(ctx context.Context, msg *types.UnifiedSynapseMessage) (bool, string) {
|
||||
gm.mu.RLock()
|
||||
defer gm.mu.RUnlock()
|
||||
|
||||
// 停机模式,全部拒绝
|
||||
if gm.level >= GovLevelShutdown {
|
||||
return false, "system shutdown"
|
||||
}
|
||||
|
||||
// 检查黑名单
|
||||
if gm.blacklist[msg.Sender.AgentID] {
|
||||
return false, "sender banned"
|
||||
}
|
||||
|
||||
// 紧急模式,仅允许白名单
|
||||
if gm.level >= GovLevelEmergency {
|
||||
if !gm.whitelist[msg.Sender.AgentID] {
|
||||
return false, "emergency mode, whitelist only"
|
||||
}
|
||||
}
|
||||
|
||||
// 执行策略检查
|
||||
for _, policy := range gm.policies {
|
||||
if !policy.Enabled || policy.Level > gm.level {
|
||||
continue
|
||||
}
|
||||
allowed, reason := policy.Evaluate(ctx, msg)
|
||||
if !allowed {
|
||||
return false, fmt.Sprintf("policy %s: %s", policy.Name, reason)
|
||||
}
|
||||
}
|
||||
|
||||
return true, ""
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Protocol Upgrade - 协议升级
|
||||
// =============================================================================
|
||||
|
||||
// UpgradeManager 升级管理器
|
||||
type UpgradeManager struct {
|
||||
mu sync.RWMutex
|
||||
currentVersion string
|
||||
upgrades map[string]ProtocolUpgrade
|
||||
config *UpgradeConfig
|
||||
}
|
||||
|
||||
// ProtocolUpgrade 协议升级
|
||||
type ProtocolUpgrade struct {
|
||||
Version string
|
||||
Description string
|
||||
ReleasedAt time.Time
|
||||
Mandatory bool
|
||||
Apply func() error
|
||||
Rollback func() error
|
||||
}
|
||||
|
||||
// UpgradeConfig 升级配置
|
||||
type UpgradeConfig struct {
|
||||
AutoUpgrade bool
|
||||
}
|
||||
|
||||
// DefaultUpgradeConfig 返回默认升级配置
|
||||
func DefaultUpgradeConfig() *UpgradeConfig {
|
||||
return &UpgradeConfig{
|
||||
AutoUpgrade: false,
|
||||
}
|
||||
}
|
||||
|
||||
// NewUpgradeManager 创建升级管理器
|
||||
func NewUpgradeManager(initialVersion string, config *UpgradeConfig) *UpgradeManager {
|
||||
if config == nil {
|
||||
config = DefaultUpgradeConfig()
|
||||
}
|
||||
return &UpgradeManager{
|
||||
currentVersion: initialVersion,
|
||||
upgrades: make(map[string]ProtocolUpgrade),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// CurrentVersion 当前版本
|
||||
func (um *UpgradeManager) CurrentVersion() string {
|
||||
um.mu.RLock()
|
||||
defer um.mu.RUnlock()
|
||||
return um.currentVersion
|
||||
}
|
||||
|
||||
// RegisterUpgrade 注册升级
|
||||
func (um *UpgradeManager) RegisterUpgrade(upgrade ProtocolUpgrade) {
|
||||
um.mu.Lock()
|
||||
defer um.mu.Unlock()
|
||||
um.upgrades[upgrade.Version] = upgrade
|
||||
}
|
||||
|
||||
// ApplyUpgrade 应用升级
|
||||
func (um *UpgradeManager) ApplyUpgrade(version string) error {
|
||||
um.mu.Lock()
|
||||
defer um.mu.Unlock()
|
||||
|
||||
upgrade, ok := um.upgrades[version]
|
||||
if !ok {
|
||||
return fmt.Errorf("upgrade %s not found", version)
|
||||
}
|
||||
|
||||
if upgrade.Apply == nil {
|
||||
um.currentVersion = version
|
||||
log.Printf("[灵枢] 协议升级到: %s", version)
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := upgrade.Apply(); err != nil {
|
||||
return fmt.Errorf("upgrade failed: %w", err)
|
||||
}
|
||||
|
||||
um.currentVersion = version
|
||||
log.Printf("[灵枢] 协议升级成功: %s", version)
|
||||
return nil
|
||||
}
|
||||
|
||||
// RollbackUpgrade 回滚升级
|
||||
func (um *UpgradeManager) RollbackUpgrade(version string) error {
|
||||
um.mu.Lock()
|
||||
defer um.mu.Unlock()
|
||||
|
||||
upgrade, ok := um.upgrades[version]
|
||||
if !ok {
|
||||
return fmt.Errorf("upgrade %s not found", version)
|
||||
}
|
||||
|
||||
if upgrade.Rollback == nil {
|
||||
return fmt.Errorf("no rollback function for version %s", version)
|
||||
}
|
||||
|
||||
if err := upgrade.Rollback(); err != nil {
|
||||
return fmt.Errorf("rollback failed: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[灵枢] 协议回滚: %s", version)
|
||||
return nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Pivot - 灵枢整体入口
|
||||
// =============================================================================
|
||||
|
||||
// Pivot 灵枢 - 紧急制动与治理
|
||||
type Pivot struct {
|
||||
CircuitBreakers map[string]*CircuitBreaker
|
||||
Governance *GovernanceManager
|
||||
Upgrade *UpgradeManager
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewPivot 创建灵枢
|
||||
func NewPivot() *Pivot {
|
||||
return &Pivot{
|
||||
CircuitBreakers: make(map[string]*CircuitBreaker),
|
||||
Governance: NewGovernanceManager(nil),
|
||||
Upgrade: NewUpgradeManager("1.0.0", nil),
|
||||
}
|
||||
}
|
||||
|
||||
// GetCircuitBreaker 获取或创建熔断器
|
||||
func (p *Pivot) GetCircuitBreaker(name string) *CircuitBreaker {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if cb, ok := p.CircuitBreakers[name]; ok {
|
||||
return cb
|
||||
}
|
||||
|
||||
cb := NewCircuitBreaker(name, nil)
|
||||
p.CircuitBreakers[name] = cb
|
||||
return cb
|
||||
}
|
||||
|
||||
// EmergencyStop 紧急停止(一键熔断所有)
|
||||
func (p *Pivot) EmergencyStop(reason string) {
|
||||
log.Printf("[灵枢] ⚠️ 紧急制动启动: %s", reason)
|
||||
p.Governance.SetLevel(GovLevelEmergency)
|
||||
|
||||
for name, cb := range p.CircuitBreakers {
|
||||
cb.RecordFailure()
|
||||
log.Printf("[灵枢] 熔断器 %s 已熔断", name)
|
||||
}
|
||||
}
|
||||
|
||||
// Resume 恢复正常
|
||||
func (p *Pivot) Resume() {
|
||||
log.Printf("[灵枢] 系统恢复正常")
|
||||
p.Governance.SetLevel(GovLevelNormal)
|
||||
|
||||
for _, cb := range p.CircuitBreakers {
|
||||
cb.Reset()
|
||||
}
|
||||
}
|
||||
|
||||
// ToJSON 导出为 JSON
|
||||
func (gm *GovernanceManager) ToJSON() string {
|
||||
data, _ := json.MarshalIndent(map[string]interface{}{
|
||||
"level": gm.level.String(),
|
||||
"policies": len(gm.policies),
|
||||
"blacklist": len(gm.blacklist),
|
||||
"whitelist": len(gm.whitelist),
|
||||
}, "", " ")
|
||||
return string(data)
|
||||
}
|
||||
446
internal/components/sigil/sigil.go
Normal file
446
internal/components/sigil/sigil.go
Normal file
@@ -0,0 +1,446 @@
|
||||
// Package sigil 灵玺 - 身份与凭证层
|
||||
//
|
||||
// 皇帝的玉玺是最高凭证。在此协议中,
|
||||
// 每个 Agent 的初始身份都需经过"铸玺"过程,
|
||||
// 每一次交互都要"验玺",确保穿透零信任边界后
|
||||
// 的每一次握手都正统且不可篡改。
|
||||
package sigil
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"hash"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"synapse/pkg/types"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Agent Identity - Agent 身份
|
||||
// =============================================================================
|
||||
|
||||
// AgentIdentity Agent 身份凭证
|
||||
type AgentIdentity struct {
|
||||
// Agent 基本信息
|
||||
AgentID string `json:"agent_id"`
|
||||
AgentName string `json:"agent_name"`
|
||||
SystemID string `json:"system_id"`
|
||||
|
||||
// 身份凭证
|
||||
PublicKey string `json:"public_key,omitempty"` // 公钥(可选)
|
||||
PrivateKey string `json:"private_key,omitempty"` // 私钥(本地保存,不对外)
|
||||
AuthSecret string `json:"-"` // HMAC 密钥(不序列化)
|
||||
|
||||
// 权限与角色
|
||||
Roles []string `json:"roles,omitempty"`
|
||||
Permissions []string `json:"permissions,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
|
||||
// 生命周期
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||
RevokedAt *time.Time `json:"revoked_at,omitempty"`
|
||||
}
|
||||
|
||||
// IdentityManager 身份管理器
|
||||
type IdentityManager struct {
|
||||
mu sync.RWMutex
|
||||
identities map[string]*AgentIdentity // agent_id -> identity
|
||||
config *IdentityConfig
|
||||
}
|
||||
|
||||
// IdentityConfig 身份管理配置
|
||||
type IdentityConfig struct {
|
||||
DefaultAlgorithm string // 默认签名算法
|
||||
TokenTTL time.Duration // Token 有效期
|
||||
}
|
||||
|
||||
// DefaultIdentityConfig 返回默认身份配置
|
||||
func DefaultIdentityConfig() *IdentityConfig {
|
||||
return &IdentityConfig{
|
||||
DefaultAlgorithm: "HMAC-SHA256",
|
||||
TokenTTL: 24 * time.Hour,
|
||||
}
|
||||
}
|
||||
|
||||
// NewIdentityManager 创建身份管理器
|
||||
func NewIdentityManager(config *IdentityConfig) *IdentityManager {
|
||||
if config == nil {
|
||||
config = DefaultIdentityConfig()
|
||||
}
|
||||
return &IdentityManager{
|
||||
identities: make(map[string]*AgentIdentity),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateIdentity 铸玺 - 创建新身份
|
||||
func (im *IdentityManager) CreateIdentity(agentID, agentName, systemID string, authSecret string) (*AgentIdentity, error) {
|
||||
if agentID == "" {
|
||||
return nil, fmt.Errorf("agent_id is required")
|
||||
}
|
||||
|
||||
im.mu.Lock()
|
||||
defer im.mu.Unlock()
|
||||
|
||||
if _, exists := im.identities[agentID]; exists {
|
||||
return nil, fmt.Errorf("agent %s already exists", agentID)
|
||||
}
|
||||
|
||||
identity := &AgentIdentity{
|
||||
AgentID: agentID,
|
||||
AgentName: agentName,
|
||||
SystemID: systemID,
|
||||
AuthSecret: authSecret,
|
||||
Roles: []string{"agent"},
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
im.identities[agentID] = identity
|
||||
return identity, nil
|
||||
}
|
||||
|
||||
// GetIdentity 获取身份
|
||||
func (im *IdentityManager) GetIdentity(agentID string) (*AgentIdentity, error) {
|
||||
im.mu.RLock()
|
||||
defer im.mu.RUnlock()
|
||||
|
||||
identity, ok := im.identities[agentID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("agent %s not found", agentID)
|
||||
}
|
||||
return identity, nil
|
||||
}
|
||||
|
||||
// RevokeIdentity 废玺 - 撤销身份
|
||||
func (im *IdentityManager) RevokeIdentity(agentID string) error {
|
||||
im.mu.Lock()
|
||||
defer im.mu.Unlock()
|
||||
|
||||
identity, ok := im.identities[agentID]
|
||||
if !ok {
|
||||
return fmt.Errorf("agent %s not found", agentID)
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
identity.RevokedAt = &now
|
||||
identity.UpdatedAt = now
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsRevoked 检查是否已撤销
|
||||
func (im *IdentityManager) IsRevoked(agentID string) (bool, error) {
|
||||
im.mu.RLock()
|
||||
defer im.mu.RUnlock()
|
||||
|
||||
identity, ok := im.identities[agentID]
|
||||
if !ok {
|
||||
return false, fmt.Errorf("agent %s not found", agentID)
|
||||
}
|
||||
|
||||
return identity.RevokedAt != nil, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Signature - 签名验证
|
||||
// =============================================================================
|
||||
|
||||
// SignatureAlgorithm 签名算法
|
||||
type SignatureAlgorithm string
|
||||
|
||||
const (
|
||||
AlgHMACSHA256 SignatureAlgorithm = "HMAC-SHA256"
|
||||
AlgHMACSHA512 SignatureAlgorithm = "HMAC-SHA512"
|
||||
)
|
||||
|
||||
// Signer 签名器
|
||||
type Signer struct {
|
||||
algorithm SignatureAlgorithm
|
||||
secret string
|
||||
}
|
||||
|
||||
// NewSigner 创建签名器
|
||||
func NewSigner(algorithm SignatureAlgorithm, secret string) *Signer {
|
||||
if algorithm == "" {
|
||||
algorithm = AlgHMACSHA256
|
||||
}
|
||||
return &Signer{
|
||||
algorithm: algorithm,
|
||||
secret: secret,
|
||||
}
|
||||
}
|
||||
|
||||
// SignMessage 对消息签名
|
||||
func (s *Signer) SignMessage(msg *types.UnifiedSynapseMessage) error {
|
||||
if msg == nil {
|
||||
return fmt.Errorf("message is nil")
|
||||
}
|
||||
|
||||
// 构造待签名内容:sender_id + receiver_id + timestamp + payload
|
||||
payloadJSON, _ := json.Marshal(msg.Payload)
|
||||
signContent := fmt.Sprintf("%s|%s|%s|%s",
|
||||
msg.Sender.AgentID,
|
||||
msg.Receiver.AgentID,
|
||||
string(msg.Timestamp),
|
||||
string(payloadJSON),
|
||||
)
|
||||
|
||||
signature, err := s.sign([]byte(signContent))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
msg.Signature = hex.EncodeToString(signature)
|
||||
msg.SignatureAlgorithm = string(s.algorithm)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// VerifySignature 验证消息签名
|
||||
func (s *Signer) VerifySignature(msg *types.UnifiedSynapseMessage) (bool, error) {
|
||||
if msg == nil || msg.Signature == "" {
|
||||
return false, fmt.Errorf("no signature to verify")
|
||||
}
|
||||
|
||||
// 构造待签名内容
|
||||
payloadJSON, _ := json.Marshal(msg.Payload)
|
||||
signContent := fmt.Sprintf("%s|%s|%s|%s",
|
||||
msg.Sender.AgentID,
|
||||
msg.Receiver.AgentID,
|
||||
string(msg.Timestamp),
|
||||
string(payloadJSON),
|
||||
)
|
||||
|
||||
expectedSig, err := s.sign([]byte(signContent))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
actualSig, err := hex.DecodeString(msg.Signature)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("invalid signature format: %w", err)
|
||||
}
|
||||
|
||||
return hmac.Equal(expectedSig, actualSig), nil
|
||||
}
|
||||
|
||||
// sign 生成 HMAC 签名
|
||||
func (s *Signer) sign(data []byte) ([]byte, error) {
|
||||
var h hash.Hash
|
||||
|
||||
switch s.algorithm {
|
||||
case AlgHMACSHA256:
|
||||
h = hmac.New(sha256.New, []byte(s.secret))
|
||||
case AlgHMACSHA512:
|
||||
h = hmac.New(sha512.New, []byte(s.secret))
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported algorithm: %s", s.algorithm)
|
||||
}
|
||||
|
||||
h.Write(data)
|
||||
return h.Sum(nil), nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Auth Token - 认证令牌
|
||||
// =============================================================================
|
||||
|
||||
// AuthToken 认证令牌
|
||||
type AuthToken struct {
|
||||
TokenID string `json:"token_id"`
|
||||
AgentID string `json:"agent_id"`
|
||||
SystemID string `json:"system_id"`
|
||||
Roles []string `json:"roles"`
|
||||
IssuedAt time.Time `json:"issued_at"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// TokenManager 令牌管理器
|
||||
type TokenManager struct {
|
||||
mu sync.RWMutex
|
||||
tokens map[string]*AuthToken // token_id -> token
|
||||
config *TokenConfig
|
||||
signer *Signer
|
||||
}
|
||||
|
||||
// TokenConfig 令牌配置
|
||||
type TokenConfig struct {
|
||||
DefaultTTL time.Duration
|
||||
}
|
||||
|
||||
// DefaultTokenConfig 返回默认令牌配置
|
||||
func DefaultTokenConfig() *TokenConfig {
|
||||
return &TokenConfig{
|
||||
DefaultTTL: 24 * time.Hour,
|
||||
}
|
||||
}
|
||||
|
||||
// NewTokenManager 创建令牌管理器
|
||||
func NewTokenManager(signer *Signer, config *TokenConfig) *TokenManager {
|
||||
if config == nil {
|
||||
config = DefaultTokenConfig()
|
||||
}
|
||||
return &TokenManager{
|
||||
tokens: make(map[string]*AuthToken),
|
||||
config: config,
|
||||
signer: signer,
|
||||
}
|
||||
}
|
||||
|
||||
// IssueToken 颁发令牌
|
||||
func (tm *TokenManager) IssueToken(agentID, systemID string, roles []string) (*AuthToken, string, error) {
|
||||
tm.mu.Lock()
|
||||
defer tm.mu.Unlock()
|
||||
|
||||
tokenID := fmt.Sprintf("token-%d", time.Now().UnixNano())
|
||||
now := time.Now()
|
||||
|
||||
token := &AuthToken{
|
||||
TokenID: tokenID,
|
||||
AgentID: agentID,
|
||||
SystemID: systemID,
|
||||
Roles: roles,
|
||||
IssuedAt: now,
|
||||
ExpiresAt: now.Add(tm.config.DefaultTTL),
|
||||
}
|
||||
|
||||
tm.tokens[tokenID] = token
|
||||
|
||||
// 生成签名令牌字符串
|
||||
tokenJSON, _ := json.Marshal(token)
|
||||
signature, _ := tm.signer.sign(tokenJSON)
|
||||
signedToken := fmt.Sprintf("%s.%s", string(tokenJSON), hex.EncodeToString(signature))
|
||||
|
||||
return token, signedToken, nil
|
||||
}
|
||||
|
||||
// ValidateToken 验证令牌
|
||||
func (tm *TokenManager) ValidateToken(signedToken string) (*AuthToken, error) {
|
||||
// 解析令牌(简化实现)
|
||||
parts := splitToken(signedToken)
|
||||
if len(parts) != 2 {
|
||||
return nil, fmt.Errorf("invalid token format")
|
||||
}
|
||||
|
||||
tokenJSON := []byte(parts[0])
|
||||
signature, err := hex.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid signature format")
|
||||
}
|
||||
|
||||
// 验证签名
|
||||
expectedSig, err := tm.signer.sign(tokenJSON)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !hmac.Equal(expectedSig, signature) {
|
||||
return nil, fmt.Errorf("invalid token signature")
|
||||
}
|
||||
|
||||
var token AuthToken
|
||||
if err := json.Unmarshal(tokenJSON, &token); err != nil {
|
||||
return nil, fmt.Errorf("invalid token payload")
|
||||
}
|
||||
|
||||
// 检查过期
|
||||
if time.Now().After(token.ExpiresAt) {
|
||||
return nil, fmt.Errorf("token expired")
|
||||
}
|
||||
|
||||
return &token, nil
|
||||
}
|
||||
|
||||
// RevokeToken 撤销令牌
|
||||
func (tm *TokenManager) RevokeToken(tokenID string) error {
|
||||
tm.mu.Lock()
|
||||
defer tm.mu.Unlock()
|
||||
|
||||
delete(tm.tokens, tokenID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func splitToken(s string) []string {
|
||||
// 简化实现,找最后一个点
|
||||
for i := len(s) - 1; i >= 0; i-- {
|
||||
if s[i] == '.' {
|
||||
return []string{s[:i], s[i+1:]}
|
||||
}
|
||||
}
|
||||
return []string{s}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Authorization - 授权检查
|
||||
// =============================================================================
|
||||
|
||||
// Authorizer 授权检查器
|
||||
type Authorizer struct {
|
||||
identityMgr *IdentityManager
|
||||
}
|
||||
|
||||
// NewAuthorizer 创建授权检查器
|
||||
func NewAuthorizer(identityMgr *IdentityManager) *Authorizer {
|
||||
return &Authorizer{
|
||||
identityMgr: identityMgr,
|
||||
}
|
||||
}
|
||||
|
||||
// HasRole 检查角色
|
||||
func (a *Authorizer) HasRole(agentID, role string) (bool, error) {
|
||||
identity, err := a.identityMgr.GetIdentity(agentID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
for _, r := range identity.Roles {
|
||||
if r == role {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// HasPermission 检查权限
|
||||
func (a *Authorizer) HasPermission(agentID, permission string) (bool, error) {
|
||||
identity, err := a.identityMgr.GetIdentity(agentID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
for _, p := range identity.Permissions {
|
||||
if p == permission {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// CanSendMessage 检查是否可以发送消息
|
||||
func (a *Authorizer) CanSendMessage(fromAgentID, toAgentID string, msgType string) (bool, error) {
|
||||
// 检查发送方是否存在且未被撤销
|
||||
fromIdentity, err := a.identityMgr.GetIdentity(fromAgentID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if fromIdentity.RevokedAt != nil {
|
||||
return false, fmt.Errorf("sender identity revoked")
|
||||
}
|
||||
|
||||
// 检查接收方是否存在
|
||||
_, err = a.identityMgr.GetIdentity(toAgentID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
523
internal/components/speculum/speculum.go
Normal file
523
internal/components/speculum/speculum.go
Normal file
@@ -0,0 +1,523 @@
|
||||
// Package speculum 灵鉴 - 共识与裁决层
|
||||
//
|
||||
// 古有"以史为鉴",今有"以智为鉴"。
|
||||
// 此层不是粗暴的少数服从多数,而是让各方 Agent
|
||||
// 将推理过程"照"进公共镜面,通过对比逻辑链的
|
||||
// 严密性来达成共识,如青天明镜,照破虚妄。
|
||||
package speculum
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Consensus Engine - 共识引擎
|
||||
// =============================================================================
|
||||
|
||||
// ConsensusType 共识类型
|
||||
type ConsensusType string
|
||||
|
||||
const (
|
||||
ConsensusMajority ConsensusType = "majority" // 多数投票
|
||||
ConsensusSupermajority ConsensusType = "supermajority" // 绝对多数(2/3)
|
||||
ConsensusUnanimity ConsensusType = "unanimity" // 一致同意
|
||||
ConsensusWeighted ConsensusType = "weighted" // 加权投票
|
||||
ConsensusRanked ConsensusType = "ranked" // 排序投票
|
||||
)
|
||||
|
||||
// VoteOption 投票选项
|
||||
type VoteOption struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// Vote 投票
|
||||
type Vote struct {
|
||||
VoteID string
|
||||
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 -> 推理理由
|
||||
}
|
||||
|
||||
// VoteStatus 投票状态
|
||||
type VoteStatus string
|
||||
|
||||
const (
|
||||
VotePending VoteStatus = "pending"
|
||||
VoteActive VoteStatus = "active"
|
||||
VoteClosed VoteStatus = "closed"
|
||||
VoteTied VoteStatus = "tied"
|
||||
)
|
||||
|
||||
// VoteResult 投票结果
|
||||
type VoteResult struct {
|
||||
Winner string
|
||||
WinOption VoteOption
|
||||
VoteCounts map[string]int
|
||||
Passed bool
|
||||
Margin float64
|
||||
}
|
||||
|
||||
// ConsensusEngine 共识引擎
|
||||
type ConsensusEngine struct {
|
||||
mu sync.RWMutex
|
||||
votes map[string]*Vote
|
||||
config *ConsensusConfig
|
||||
}
|
||||
|
||||
// ConsensusConfig 共识配置
|
||||
type ConsensusConfig struct {
|
||||
DefaultType ConsensusType
|
||||
DefaultTimeout time.Duration
|
||||
QuorumSize int
|
||||
}
|
||||
|
||||
// DefaultConsensusConfig 返回默认共识配置
|
||||
func DefaultConsensusConfig() *ConsensusConfig {
|
||||
return &ConsensusConfig{
|
||||
DefaultType: ConsensusMajority,
|
||||
DefaultTimeout: 5 * time.Minute,
|
||||
QuorumSize: 1,
|
||||
}
|
||||
}
|
||||
|
||||
// NewConsensusEngine 创建共识引擎
|
||||
func NewConsensusEngine(config *ConsensusConfig) *ConsensusEngine {
|
||||
if config == nil {
|
||||
config = DefaultConsensusConfig()
|
||||
}
|
||||
return &ConsensusEngine{
|
||||
votes: make(map[string]*Vote),
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// InitiateVote 发起投票
|
||||
func (ce *ConsensusEngine) InitiateVote(
|
||||
voteID, question string,
|
||||
options []VoteOption,
|
||||
initiator string,
|
||||
participants []string,
|
||||
consensusType ConsensusType,
|
||||
deadline time.Time,
|
||||
) (*Vote, error) {
|
||||
|
||||
if voteID == "" {
|
||||
voteID = fmt.Sprintf("vote-%d", time.Now().UnixNano())
|
||||
}
|
||||
if consensusType == "" {
|
||||
consensusType = ce.config.DefaultType
|
||||
}
|
||||
if deadline.IsZero() {
|
||||
deadline = time.Now().Add(ce.config.DefaultTimeout)
|
||||
}
|
||||
|
||||
ce.mu.Lock()
|
||||
defer ce.mu.Unlock()
|
||||
|
||||
vote := &Vote{
|
||||
VoteID: voteID,
|
||||
Question: question,
|
||||
Options: options,
|
||||
Type: consensusType,
|
||||
Initiator: initiator,
|
||||
Participants: participants,
|
||||
Votes: make(map[string]string),
|
||||
Weights: make(map[string]float64),
|
||||
Status: VoteActive,
|
||||
Deadline: deadline,
|
||||
Reasoning: make(map[string]string),
|
||||
}
|
||||
|
||||
// 默认权重相同
|
||||
for _, p := range participants {
|
||||
vote.Weights[p] = 1.0
|
||||
}
|
||||
|
||||
ce.votes[voteID] = vote
|
||||
|
||||
log.Printf("[灵鉴] 发起投票: %s (发起者: %s, 类型: %s, 参与者: %d人)",
|
||||
voteID, initiator, consensusType, len(participants))
|
||||
|
||||
return vote, nil
|
||||
}
|
||||
|
||||
// SubmitVote 提交投票
|
||||
func (ce *ConsensusEngine) SubmitVote(voteID, voterID, optionID, reasoning string) error {
|
||||
ce.mu.Lock()
|
||||
defer ce.mu.Unlock()
|
||||
|
||||
vote, ok := ce.votes[voteID]
|
||||
if !ok {
|
||||
return fmt.Errorf("vote %s not found", voteID)
|
||||
}
|
||||
|
||||
if vote.Status != VoteActive {
|
||||
return fmt.Errorf("vote is not active (status: %s)", vote.Status)
|
||||
}
|
||||
|
||||
// 检查是否是参与者
|
||||
isParticipant := false
|
||||
for _, p := range vote.Participants {
|
||||
if p == voterID {
|
||||
isParticipant = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isParticipant {
|
||||
return fmt.Errorf("voter %s is not a participant", voterID)
|
||||
}
|
||||
|
||||
vote.Votes[voterID] = optionID
|
||||
if reasoning != "" {
|
||||
vote.Reasoning[voterID] = reasoning
|
||||
}
|
||||
|
||||
log.Printf("[灵鉴] %s 投票: %s -> %s", voterID, voteID, optionID)
|
||||
|
||||
// 检查是否所有参与者都已投票,可以提前结束
|
||||
if len(vote.Votes) >= len(vote.Participants) {
|
||||
ce.countVotesLocked(vote)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CloseVote 关闭投票并统计结果
|
||||
func (ce *ConsensusEngine) CloseVote(voteID string) (*VoteResult, error) {
|
||||
ce.mu.Lock()
|
||||
defer ce.mu.Unlock()
|
||||
|
||||
vote, ok := ce.votes[voteID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("vote %s not found", voteID)
|
||||
}
|
||||
|
||||
if vote.Status != VoteActive {
|
||||
return vote.Result, nil
|
||||
}
|
||||
|
||||
return ce.countVotesLocked(vote), nil
|
||||
}
|
||||
|
||||
// countVotesLocked 统计投票(调用者需持有锁)
|
||||
func (ce *ConsensusEngine) countVotesLocked(vote *Vote) *VoteResult {
|
||||
vote.Status = VoteClosed
|
||||
|
||||
// 统计票数
|
||||
voteCounts := make(map[string]int)
|
||||
for _, optID := range vote.Votes {
|
||||
voteCounts[optID]++
|
||||
}
|
||||
|
||||
// 找出获胜者
|
||||
var winner string
|
||||
maxVotes := 0
|
||||
for optID, count := range voteCounts {
|
||||
if count > maxVotes {
|
||||
maxVotes = count
|
||||
winner = optID
|
||||
}
|
||||
}
|
||||
|
||||
// 计算是否通过
|
||||
totalVotes := len(vote.Votes)
|
||||
required := ce.getRequiredVotes(vote, totalVotes)
|
||||
passed := maxVotes >= required && totalVotes >= ce.config.QuorumSize
|
||||
|
||||
// 查找获胜选项
|
||||
var winOption VoteOption
|
||||
for _, opt := range vote.Options {
|
||||
if opt.ID == winner {
|
||||
winOption = opt
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
result := &VoteResult{
|
||||
Winner: winner,
|
||||
WinOption: winOption,
|
||||
VoteCounts: voteCounts,
|
||||
Passed: passed,
|
||||
Margin: float64(maxVotes) / float64(totalVotes),
|
||||
}
|
||||
|
||||
vote.Result = result
|
||||
|
||||
log.Printf("[灵鉴] 投票结果: %s -> %s (通过: %v, 得票率: %.1f%%)",
|
||||
vote.VoteID, winner, passed, result.Margin*100)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// getRequiredVotes 获取所需票数
|
||||
func (ce *ConsensusEngine) getRequiredVotes(vote *Vote, total int) int {
|
||||
switch vote.Type {
|
||||
case ConsensusUnanimity:
|
||||
return total
|
||||
case ConsensusSupermajority:
|
||||
return (total*2)/3 + 1
|
||||
case ConsensusMajority:
|
||||
return total/2 + 1
|
||||
default:
|
||||
return total/2 + 1
|
||||
}
|
||||
}
|
||||
|
||||
// GetVote 获取投票信息
|
||||
func (ce *ConsensusEngine) GetVote(voteID string) (*Vote, error) {
|
||||
ce.mu.RLock()
|
||||
defer ce.mu.RUnlock()
|
||||
|
||||
vote, ok := ce.votes[voteID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("vote %s not found", voteID)
|
||||
}
|
||||
return vote, nil
|
||||
}
|
||||
|
||||
// GetAllVotes 获取所有投票
|
||||
func (ce *ConsensusEngine) GetAllVotes() []*Vote {
|
||||
ce.mu.RLock()
|
||||
defer ce.mu.RUnlock()
|
||||
|
||||
votes := make([]*Vote, 0, len(ce.votes))
|
||||
for _, v := range ce.votes {
|
||||
votes = append(votes, v)
|
||||
}
|
||||
return votes
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Arbitration - 仲裁机制
|
||||
// =============================================================================
|
||||
|
||||
// Arbitrator 仲裁者
|
||||
type Arbitrator struct {
|
||||
consensusEngine *ConsensusEngine
|
||||
rules []ArbitrationRule
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// ArbitrationRule 仲裁规则
|
||||
type ArbitrationRule struct {
|
||||
ID string
|
||||
Name string
|
||||
Description string
|
||||
Priority int
|
||||
Evaluate func(ctx context.Context, dispute *Dispute) (string, error)
|
||||
}
|
||||
|
||||
// Dispute 争议
|
||||
type Dispute struct {
|
||||
DisputeID string
|
||||
Topic string
|
||||
Description string
|
||||
Parties []string
|
||||
Evidence map[string][]byte
|
||||
SubmittedAt time.Time
|
||||
}
|
||||
|
||||
// ArbitrationResult 仲裁结果
|
||||
type ArbitrationResult struct {
|
||||
DisputeID string
|
||||
Winner string
|
||||
Reason string
|
||||
Evidence []string
|
||||
DecidedAt time.Time
|
||||
}
|
||||
|
||||
// NewArbitrator 创建仲裁者
|
||||
func NewArbitrator(consensusEngine *ConsensusEngine) *Arbitrator {
|
||||
return &Arbitrator{
|
||||
consensusEngine: consensusEngine,
|
||||
rules: make([]ArbitrationRule, 0),
|
||||
}
|
||||
}
|
||||
|
||||
// AddRule 添加仲裁规则
|
||||
func (a *Arbitrator) AddRule(rule ArbitrationRule) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
|
||||
a.rules = append(a.rules, rule)
|
||||
}
|
||||
|
||||
// Arbitrate 仲裁
|
||||
func (a *Arbitrator) Arbitrate(ctx context.Context, dispute *Dispute) (*ArbitrationResult, error) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
|
||||
log.Printf("[灵鉴] 开始仲裁: %s (%s)", dispute.DisputeID, dispute.Topic)
|
||||
|
||||
// 按优先级执行规则
|
||||
for _, rule := range a.rules {
|
||||
result, err := rule.Evaluate(ctx, dispute)
|
||||
if err != nil {
|
||||
log.Printf("[灵鉴] 规则 %s 执行失败: %v", rule.Name, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if result != "" {
|
||||
return &ArbitrationResult{
|
||||
DisputeID: dispute.DisputeID,
|
||||
Winner: result,
|
||||
Reason: fmt.Sprintf("规则 %s 判定", rule.Name),
|
||||
DecidedAt: time.Now(),
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有规则匹配,使用投票
|
||||
return a.arbitrateByVote(ctx, dispute)
|
||||
}
|
||||
|
||||
// arbitrateByVote 通过投票仲裁
|
||||
func (a *Arbitrator) arbitrateByVote(ctx context.Context, dispute *Dispute) (*ArbitrationResult, error) {
|
||||
options := make([]VoteOption, len(dispute.Parties))
|
||||
for i, p := range dispute.Parties {
|
||||
options[i] = VoteOption{
|
||||
ID: p,
|
||||
Title: p,
|
||||
}
|
||||
}
|
||||
|
||||
vote, err := a.consensusEngine.InitiateVote(
|
||||
fmt.Sprintf("arbitration-%s", dispute.DisputeID),
|
||||
dispute.Topic,
|
||||
options,
|
||||
"arbitrator",
|
||||
dispute.Parties,
|
||||
ConsensusMajority,
|
||||
time.Now().Add(5*time.Minute),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result, err := a.consensusEngine.CloseVote(vote.VoteID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &ArbitrationResult{
|
||||
DisputeID: dispute.DisputeID,
|
||||
Winner: result.Winner,
|
||||
Reason: "投票裁决",
|
||||
DecidedAt: time.Now(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Reasoning Mirror - 推理镜面
|
||||
// =============================================================================
|
||||
|
||||
// ReasoningMirror 推理镜面
|
||||
// 让各方 Agent 将推理过程"照"进公共镜面,
|
||||
// 通过对比逻辑链的严密性来达成共识
|
||||
type ReasoningMirror struct {
|
||||
mu sync.RWMutex
|
||||
reasonings map[string]*ReasoningChain // chain_id -> 推理链
|
||||
}
|
||||
|
||||
// ReasoningChain 推理链
|
||||
type ReasoningChain struct {
|
||||
ChainID string
|
||||
AgentID string
|
||||
Topic string
|
||||
Steps []ReasoningStep
|
||||
Score float64
|
||||
SubmittedAt time.Time
|
||||
}
|
||||
|
||||
// ReasoningStep 推理步骤
|
||||
type ReasoningStep struct {
|
||||
StepID string
|
||||
Description string
|
||||
Evidence []string
|
||||
Confidence float64
|
||||
Next []string // 下一步的ID
|
||||
}
|
||||
|
||||
// NewReasoningMirror 创建推理镜面
|
||||
func NewReasoningMirror() *ReasoningMirror {
|
||||
return &ReasoningMirror{
|
||||
reasonings: make(map[string]*ReasoningChain),
|
||||
}
|
||||
}
|
||||
|
||||
// SubmitReasoning 提交推理链
|
||||
func (rm *ReasoningMirror) SubmitReasoning(chain *ReasoningChain) error {
|
||||
if chain == nil {
|
||||
return fmt.Errorf("reasoning chain is nil")
|
||||
}
|
||||
|
||||
rm.mu.Lock()
|
||||
defer rm.mu.Unlock()
|
||||
|
||||
rm.reasonings[chain.ChainID] = chain
|
||||
log.Printf("[灵鉴] %s 提交推理链: %s (步骤: %d)", chain.AgentID, chain.Topic, len(chain.Steps))
|
||||
return nil
|
||||
}
|
||||
|
||||
// CompareReasonings 比较推理链的严密性
|
||||
func (rm *ReasoningMirror) CompareReasonings(chainIDs []string) (string, error) {
|
||||
rm.mu.RLock()
|
||||
defer rm.mu.RUnlock()
|
||||
|
||||
var bestChain string
|
||||
bestScore := -1.0
|
||||
|
||||
for _, id := range chainIDs {
|
||||
chain, ok := rm.reasonings[id]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
// 计算推理链得分(简化:平均置信度 * 步骤数权重)
|
||||
if chain.Score > bestScore {
|
||||
bestScore = chain.Score
|
||||
bestChain = id
|
||||
}
|
||||
}
|
||||
|
||||
if bestChain == "" {
|
||||
return "", fmt.Errorf("no valid reasoning chains found")
|
||||
}
|
||||
|
||||
log.Printf("[灵鉴] 推理比较胜出: %s (得分: %.2f)", bestChain, bestScore)
|
||||
return bestChain, nil
|
||||
}
|
||||
|
||||
// GetReasoning 获取推理链
|
||||
func (rm *ReasoningMirror) GetReasoning(chainID string) (*ReasoningChain, error) {
|
||||
rm.mu.RLock()
|
||||
defer rm.mu.RUnlock()
|
||||
|
||||
chain, ok := rm.reasonings[chainID]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("reasoning chain %s not found", chainID)
|
||||
}
|
||||
return chain, nil
|
||||
}
|
||||
|
||||
// ToJSON 导出为 JSON
|
||||
func (v *Vote) ToJSON() string {
|
||||
data, _ := json.MarshalIndent(v, "", " ")
|
||||
return string(data)
|
||||
}
|
||||
Reference in New Issue
Block a user