MemoryMatrix

类 MemoryMatrix 在 core/memory_model.py: 记忆矩阵 — 管理用户的所有任务记忆

    结构:
      主记忆(General) — 日常交互
      ├── 物理记忆(Physics) — 备课专用
      ├── 编程记忆(Coding) — 开发专用
      └── ...按需创建

    用法:
      matrix = MemoryMatrix("user_001")
      matr | 方法: __init__, activate, deactivate, current, store, retrieve, get_context, list_tasks, get_status

class MemoryMatrix:
    """
    记忆矩阵 — 管理用户的所有任务记忆

    结构:
      主记忆(General) — 日常交互
      ├── 物理记忆(Physics) — 备课专用
      ├── 编程记忆(Coding) — 开发专用
      └── ...按需创建

    用法:
      matrix = MemoryMatrix("user_001")
      matrix.activate("physics")  # 激活物理记忆
      matrix.store("...", "...")  # 存入当前激活记忆
      matrix.deactivate()         # 回到主记忆
    """

    def __init__(self, user_id: str = "default"):
        self.user_id = user_id
        self._main = MemoryModel(user_id)
        self._forks: Dict[str, MemoryModel] = {}
        self._active: Optional[str] = None  # 当前激活的任务名

    def activate(self, task_name: str):
        """激活一个任务记忆(不存在则创建)"""
        if task_name not in self._forks:
            # 从主记忆分叉
            self._forks[task_name] = self._main.fork_for_task(task_name)
            logger.info(f"创建任务记忆: {task_name}")
        self._active = task_name

    def deactivate(self):
        """停用任务记忆，合并回主记忆"""
        if self._active and self._active in self._forks:
            self._main.merge_from(self._forks[self._active])
            # 保留分叉不删除(下次可复用)
        self._active = None

    @property
    def current(self) -> MemoryModel:
        """获取当前活跃的记忆模型"""
        if self._active and self._active in self._forks:
            return self._forks[self._active]
        return self._main

    def store(self, message: str, result: str, analysis=None):
        """存入当前活跃记忆"""
        self.current.store_interaction(message, result, analysis)

    def retrieve(self, query: str, top_k: int = 5) -> List[Dict]:
        """从当前活跃记忆检索"""
        return self.current.retrieve(query, top_k)

    def get_context(self, query: str) -> str:
        """获取上下文(优先当前任务+补充主记忆)"""
        task_ctx = self.current.retrieve_context(query)
        if self._active:
            main_ctx = self._main.retrieve_context(query)
            if task_ctx and main_ctx:
                return f"[任务:{self._active}] {task_ctx}\n[通用] {main_ctx}"
        return task_ctx

    def list_tasks(self) -> List[str]:
        """列出所有


activate

方法 MemoryMatrix.activate():
        """激活一个任务记忆(不存在则创建)"""
        if task_name not in self._forks:
            # 从主记忆分叉

def activate(self):
        """激活一个任务记忆(不存在则创建)"""
        if task_name not in self._forks:
            # 从主记忆分叉
            self._forks[task_name] = self._main.fork_for_task(task_name)
            logger.info(f"创建任务记忆: {task_name}")
        self._active = task_name


deactivate

方法 MemoryMatrix.deactivate():
        """停用任务记忆，合并回主记忆"""
        if self._active and self._active in self._forks:
            se

def deactivate(self):
        """停用任务记忆，合并回主记忆"""
        if self._active and self._active in self._forks:
            self._main.merge_from(self._forks[self._active])
            # 保留分叉不删除(下次可复用)
        self._active = None

    @property


store

方法 MemoryMatrix.store():
        """存入当前活跃记忆"""
        self.current.store_interaction(message, result, analysis)

def store(self):
        """存入当前活跃记忆"""
        self.current.store_interaction(message, result, analysis)


router.py

文件 core/router.py: 虫群统一推理路由器
- 本地小模型(tiny/small/medium): 快速响应，简单任务
- 云端GLM-5.1(Modal): 复杂推理，需要深度思考的任务
- 自动路由：按任务复杂度选择模型
- 降级机制：云端不可用时回退本地 | 定义: class SwarmRouter, def __init__, def _classify_complexity, def route, def _route_forced, def _route_local, def _route_cloud, def get_status, def get_router

#!/usr/bin/env python3
"""
虫群统一推理路由器
- 本地小模型(tiny/small/medium): 快速响应，简单任务
- 云端GLM-5.1(Modal): 复杂推理，需要深度思考的任务
- 自动路由：按任务复杂度选择模型
- 降级机制：云端不可用时回退本地
"""

import os
import time
from typing import Dict, List, Optional

from core.modal_glm import ModalGLMBackend, get_glm_backend
from core.local_inference import LocalModelBackend, get_local_backend

class SwarmRouter:
    """
    虫群推理路由器

    路由策略：
    1. 简单任务（闲聊、格式化、短回答）→ 本地tiny模型
    2. 通用任务（对话、翻译、摘要）→ 本地small/medium模型
    3. 复杂任务（推理、分析、编程、数学）→


SwarmRouter

类 SwarmRouter 在 core/router.py: 虫群推理路由器

    路由策略：
    1. 简单任务（闲聊、格式化、短回答）→ 本地tiny模型
    2. 通用任务（对话、翻译、摘要）→ 本地small/medium模型
    3. 复杂任务（推理、分析、编程、数学）→ 云端GLM-5.1
    4. 云端不可用 → 降级到本地最强模型 | 方法: __init__, _classify_complexity, route, _route_forced, _route_local, _route_cloud, get_status

class SwarmRouter:
    """
    虫群推理路由器

    路由策略：
    1. 简单任务（闲聊、格式化、短回答）→ 本地tiny模型
    2. 通用任务（对话、翻译、摘要）→ 本地small/medium模型
    3. 复杂任务（推理、分析、编程、数学）→ 云端GLM-5.1
    4. 云端不可用 → 降级到本地最强模型
    """

    # 简单任务关键词
    SIMPLE_KEYWORDS = [
        "你好", "hello", "hi", "嗨", "早上好", "下午好",
        "谢谢", "再见", "好的", "确认",
    ]

    # 复杂任务关键词
    COMPLEX_KEYWORDS = [
        "为什么", "分析", "推理", "证明", "计算", "编程", "代码",
        "对比", "评估", "优化", "设计", "架构", "解释",
        "为什么", "how", "why", "explain", "analyze",
        "数学", "逻辑", "算法", "策略", "方案",
    ]

    def __init__(
        self,
        local_backend=None,
        cloud_backend=None,
        # 兼容旧接口：传入registry时自动创建backends
        registry=None,
    ):
        if registry is not None:
            # MOA引擎传入registry时的兼容模式
            self._registry = registry
        self.local = local_backend or get_local_backend()
        self.cloud = cloud_backend or get_glm_backend()

        # 默认本地模型
        self.default_local_model = "tiny"

        # 统计
        self._route_stats = {
            "local_simple": 0,
            "local_general": 0,
            "cloud_complex": 0,
            "cloud_fallback": 0,
            "errors": 0,
        }

    def _classify_complexity(self, query: str) -> str:
        """分类任务复杂度: simple / general / complex"""
        query_lower = query.lower().strip()

        # 极短输入 → 简单
        if len(query_lower) <= 5:
            return "simple"

        # 匹配关键词
        for kw in self.SIMPLE_KEYWORDS:
            if kw in query_lower:
                return "simple"

        for kw in self.COMPLEX_KEYWORDS:
            if kw in query_lower:
                return "complex"

        # 中等长度默认通用
        return "general"

    def route(
        self,
        query: str,
        force_model: str = None,
        max_tokens: int = 512,
    ) -> Dict:
        """
        智能路由推理

        参数:
            query: 用户输入
            force_model: 强制指定模型("tiny"/"


conversation.py

文件 core/conversation.py: 虫群智能体系统 — 对话上下文管理
管理多轮对话历史、上下文窗口滑动、会话隔离 | 定义: class Message, def __init__, def to_dict, def from_dict, def token_estimate, class Conversation, def __init__, def add, def _trim, def _total_tokens

json logging os threading time uuid collections typing

#!/usr/bin/env python3
"""
虫群智能体系统 — 对话上下文管理
管理多轮对话历史、上下文窗口滑动、会话隔离
"""

import json
import logging
import os
import threading
import time
import uuid
from collections import deque
from typing import Dict, List, Optional, Tuple

logger = logging.getLogger(__name__)

# 默认存储路径
DEFAULT_STORE_PATH = "/home/admin/swarm/data/conversations"

class Message:
    """单条消息"""

    def __init__(self, role: str, content: str,
                 model: str = "", metadata: dict = None):
        self.role = role


Message

类 Message 在 core/conversation.py: 单条消息 | 方法: __init__, to_dict, from_dict, token_estimate

class Message:
    """单条消息"""

    def __init__(self, role: str, content: str,
                 model: str = "", metadata: dict = None):
        self.role = role  # user / assistant / system
        self.content = content
        self.model = model
        self.metadata = metadata or {}
        self.timestamp = time.time()

    def to_dict(self) -> dict:
        return {
            "role": self.role,
            "content": self.content,
            "model": self.model,
            "metadata": self.metadata,
            "timestamp": self.timestamp,
        }

    @classmethod
    def from_dict(cls, d: dict) -> "Message":
        msg = cls(d["role"], d["content"],
                  d.get("model", ""), d.get("metadata", {}))
        msg.timestamp = d.get("timestamp", time.time())
        return msg

    def token_estimate(self) -> int:
        """估算token数（中文约1.5字/token，英文约4字符/token）"""
        cn_chars = sum(1 for c in self.content if '\u4e00' <= c <= '\u9fff')
        en_chars = len(self.content) - cn_chars
        return int(cn_chars / 1.5 + en_chars / 4) + 1


Conversation

类 Conversation 在 core/conversation.py: 单个对话会话 | 方法: __init__, add, _trim, _total_tokens, get_context, get_recent, get_user_messages, to_dict, from_dict

class Conversation:
    """单个对话会话"""

    def __init__(self, conversation_id: str = "", max_messages: int = 50,
                 max_tokens: int = 4000):
        self.conversation_id = conversation_id or str(uuid.uuid4())[:8]
        self.max_messages = max_messages
        self.max_tokens = max_tokens
        self.messages: List[Message] = []
        self.created_at = time.time()
        self.updated_at = time.time()
        self.summary = ""  # 对话摘要

    def add(self, role: str, content: str, model: str = "",
            metadata: dict = None) -> Message:
        """添加消息"""
        msg = Message(role, content, model, metadata)
        self.messages.append(msg)
        self.updated_at = time.time()
        # 超出上限时滑动窗口
        self._trim()
        return msg

    def _trim(self):
        """滑动窗口裁剪：保留最近的消息，不超过token限制"""
        while len(self.messages) > self.max_messages:
            self.messages.pop(0)

        # token限制裁剪
        while self._total_tokens() > self.max_tokens and len(self.messages) > 2:
            self.messages.pop(0)

    def _total_tokens(self) -> int:
        return sum(m.token_estimate() for m in self.messages)

    def get_context(self, max_tokens: int = None) -> List[dict]:
        """
        获取上下文窗口，返回OpenAI兼容的messages格式。
        保留系统提示 + 最近对话
        """
        max_tokens = max_tokens or self.max_tokens
        result = []
        token_count = 0

        # 从最新消息往前取
        for msg in reversed(self.messages):
            est = msg.token_estimate()
            if token_count + est > max_tokens:
                break
            result.insert(0, {
                "role": msg.role,
                "content": msg.content,
            })
            token_count += est

        return result

    def get_recent(self, n: int = 5) -> List[Message]:
        """获取最近N条消息"""
        return self.messages[-n:] if len(self.messages) >= n else self.messages

    def get_user_messages(self) -> List[str]:
        """获取所有用户消息"""
        return [m.content for m in self.messag


ConversationManager

对话上下文管理器 — 管理多个会话

类 ConversationManager 在 core/conversation.py: 对话上下文管理器 — 管理多个会话 | 方法: __init__, new_conversation, get_active, get_or_create, switch, list_conversations, delete_conversation, add_message, get_context, build_api_messages, _save_conversation, _load_all, get_stats

class ConversationManager:
    """对话上下文管理器 — 管理多个会话"""

    def __init__(self, store_path: str = DEFAULT_STORE_PATH,
                 max_conversations: int = 100):
        self.store_path = store_path
        self.max_conversations = max_conversations
        self._conversations: Dict[str, Conversation] = {}
        self._active_id: Optional[str] = None
        self._lock = threading.Lock()
        # 启动时加载
        self._load_all()

    # ----------------------------------------------------------
    # 会话管理
    # ----------------------------------------------------------

    def new_conversation(self, conversation_id: str = "") -> str:
        """创建新会话"""
        conv = Conversation(conversation_id)
        with self._lock:
            self._conversations[conv.conversation_id] = conv
            self._active_id = conv.conversation_id
        logger.info(f"新会话: {conv.conversation_id}")
        return conv.conversation_id

    def get_active(self) -> Optional[Conversation]:
        """获取当前活跃会话"""
        if self._active_id and self._active_id in self._conversations:
            return self._conversations[self._active_id]
        return None

    def get_or_create(self, conversation_id: str = "") -> Conversation:
        """获取或创建会话"""
        if conversation_id and conversation_id in self._conversations:
            return self._conversations[conversation_id]
        conv = Conversation(conversation_id)
        with self._lock:
            self._conversations[conv.conversation_id] = conv
            self._active_id = conv.conversation_id
        return conv

    def switch(self, conversation_id: str) -> bool:
        """切换活跃会话"""
        if conversation_id in self._conversations:
            self._active_id = conversation_id
            return True
        return False

    def list_conversations(self) -> List[dict]:
        """列出所有会话摘要"""
        result = []
        for cid, conv in self._conversations.items():
            result.append({
                "id": cid,
                "messages":


文件 core/auto_trainer.py: 虫群v7.1 — 自动训练器
实现模型的自动训练、参数扩展、持续优化

核心机制:
  1. should_train(): 根据数据积累量判断是否触发训练
  2. auto_train(): 执行单次训练(增量)
  3. grow_param(): 参数扩展(d_model/n_heads/n_layers逐步增大)
  4. 训练历史追踪，防止过拟合

设计原则:
  - 积少成多: 小批 | 定义: class AutoTrainer, def __init__, def _load_state, def _save_state, def notify_new_data, def should_train, def auto_train, def _simulate_train, def grow_param, def get_status

#!/usr/bin/env python3
"""
虫群v7.1 — 自动训练器
实现模型的自动训练、参数扩展、持续优化

核心机制:
  1. should_train(): 根据数据积累量判断是否触发训练
  2. auto_train(): 执行单次训练(增量)
  3. grow_param(): 参数扩展(d_model/n_heads/n_layers逐步增大)
  4. 训练历史追踪，防止过拟合

设计原则:
  - 积少成多: 小批量数据不断喂养，模型持续进化
  - 按需启动: 只在数据量足够时触发，避免浪费算力
  - 渐进扩展: 先练好小模型，再扩展参数量
"""

import json
import logging
import os
import time
from datetime import datetime
from typing import Dict, List, Optional, Tuple

logger = logging.getLogger(__name__)

# 训练触发阈值配置
TRAIN_CONFIG = {
    "min


AutoTrainer

类 AutoTrainer 在 core/auto_trainer.py: 自动训练器 — 模型持续进化引擎

    使用方式:
      trainer = AutoTrainer("my_queen", role="queen")
      if trainer.should_train():
          result = trainer.auto_train() | 方法: __init__, _load_state, _save_state, notify_new_data, should_train, auto_train, _simulate_train, grow_param, get_status

class AutoTrainer:
    """
    自动训练器 — 模型持续进化引擎

    使用方式:
      trainer = AutoTrainer("my_queen", role="queen")
      if trainer.should_train():
          result = trainer.auto_train()
    """

    def __init__(self, model_name: str, role: str = "queen",
                 base_dir: str = "/home/admin/swarm/training/seeds"):
        self.model_name = model_name
        self.role = role
        self.base_dir = os.path.join(base_dir, model_name)

        # 训练状态
        self._state_file = os.path.join(self.base_dir, "trainer_state.json")
        self._state = self._load_state()

        # 数据计数
        self._new_data_count = self._state.get("new_data_count", 0)

    def _load_state(self) -> Dict:
        """加载训练状态"""
        if os.path.exists(self._state_file):
            with open(self._state_file, "r") as f:
                return json.load(f)
        return {
            "model_name": self.model_name,
            "role": self.role,
            "current_gen": 0,
            "total_train_rounds": 0,
            "total_data_fed": 0,
            "new_data_count": 0,
            "last_train_time": None,
            "loss_history": [],
            "current_loss": None,
        }

    def _save_state(self):
        """保存训练状态"""
        os.makedirs(os.path.dirname(self._state_file), exist_ok=True)
        with open(self._state_file, "w") as f:
            json.dump(self._state, f, indent=2, ensure_ascii=False)

    # ============================================================
    # 核心方法(后续A2-A4逐步实现)
    # ============================================================

    def notify_new_data(self, count: int = 1):
        """通知有新数据到达"""
        self._new_data_count += count
        self._state["new_data_count"] = self._new_data_count
        self._save_state()
        logger.info(f"自动训练器: +{count}条新数据, 累计{self._new_data_count}")

    def should_train(self) -> bool:
        """判断是否应该触发训练"""
        if self._new_data_count < TRAIN_CONFIG["min_new_data"]:
            return Fa


方法 AutoTrainer.notify_new_data():
        """通知有新数据到达"""
        self._new_data_count += count
        self._state["new_data_count"]

def notify_new_data(self):
        """通知有新数据到达"""
        self._new_data_count += count
        self._state["new_data_count"] = self._new_data_count
        self._save_state()
        logger.info(f"自动训练器: +{count}条新数据, 累计{self._new_data_count}")


文件 core/model_adapter.py: 虫群模型适配器 — 统一不同API的调用接口
每个提供商一个适配器，暴露统一的 call(prompt, tools) 方法 | 定义: class
class, class ModelAdapter, def __init__, def call, class ZhipuAdapter, def __init__, def call, class NvidiaNimAdapter, def __init__, def call

#!/usr/bin/env python3
"""
虫群模型适配器 — 统一不同API的调用接口
每个提供商一个适配器，暴露统一的 call(prompt, tools) 方法
"""

import os
import time
import json
from typing import Dict, List, Optional, Any
from dataclasses import dataclass

@dataclass
class CallResult:
    """模型调用结果"""
    text: str                    # 回复文本
    tool_calls: List[Dict]       # 工具调用列表
    model: str                   # 实际使用的模型
    provider: str                # 提供商
    latency_ms: float            # 延迟(ms)
    tokens_in: int = 0           # 输入t


CallResult

类 CallResult 在 core/model_adapter.py: 模型调用结果 | 方法:

class CallResult:
    """模型调用结果"""
    text: str                    # 回复文本
    tool_calls: List[Dict]       # 工具调用列表
    model: str                   # 实际使用的模型
    provider: str                # 提供商
    latency_ms: float            # 延迟(ms)
    tokens_in: int = 0           # 输入token数
    tokens_out: int = 0          # 输出token数
    thinking: str = ""           # 思维链内容
    error: str = ""              # 错误信息


ModelAdapter

类 ModelAdapter 在 core/model_adapter.py: 模型调用适配器基类 | 方法: __init__, call

class ModelAdapter:
    """模型调用适配器基类"""

    def __init__(self, provider: str, api_key: str = "", base_url: str = ""):
        self.provider = provider
        self.api_key = api_key
        self.base_url = base_url

    async def call(self, messages: List[Dict], model: str = "",
                   tools: List[Dict] = None, max_tokens: int = 500,
                   temperature: float = 0.7) -> CallResult:
        raise NotImplementedError


ZhipuAdapter

类 ZhipuAdapter 在 core/model_adapter.py: 智谱AI适配器 | 方法: __init__, call

class ZhipuAdapter:
    """智谱AI适配器"""

    def __init__(self, api_key: str = ""):
        key = api_key or os.environ.get("GLM_API_KEY", "")
        super().__init__("zhipu", key, "https://open.bigmodel.cn/api/paas/v4")

    async def call(self, messages: List[Dict], model: str = "glm-4.7-flash",
                   tools: List[Dict] = None, max_tokens: int = 500,
                   temperature: float = 0.7) -> CallResult:
        import httpx
        t0 = time.time()
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        body = {
            "model": model,
            "messages": messages,
            "max_tokens": max_tokens,
            "temperature": temperature,
        }
        if tools:
            body["tools"] = tools
            body["tool_choice"] = "auto"

        try:
            async with httpx.AsyncClient(timeout=60) as client:
                r = await client.post(
                    f"{self.base_url}/chat/completions",
                    headers=headers, json=body
                )
            ms = round((time.time() - t0) * 1000)
            if r.status_code != 200:
                return CallResult(text="", tool_calls=[], model=model,
                                  provider=self.provider, latency_ms=ms,
                                  error=f"HTTP {r.status_code}: {r.text[:200]}")

            data = r.json()
            choice = data["choices"][0]
            msg = choice["message"]

            # 提取工具调用
            tool_calls = []
            if "tool_calls" in msg and msg["tool_calls"]:
                for tc in msg["tool_calls"]:
                    tool_calls.append({
                        "name": tc["function"]["name"],
                        "arguments": tc["function"]["arguments"]
                    })

            # 提取思维链
            thinking = ""
            if "reasoning_content" in msg:
                thin


NvidiaNimAdapter

类 NvidiaNimAdapter 在 core/model_adapter.py: NVIDIA NIM适配器 | 方法: __init__, call

class NvidiaNimAdapter:
    """NVIDIA NIM适配器"""

    def __init__(self, api_key: str = ""):
        key = api_key or os.environ.get("NVIDIA_KEY", "")
        super().__init__("nvidia_nim", key, "https://integrate.api.nvidia.com/v1")

    async def call(self, messages: List[Dict], model: str = "meta/llama-4-maverick-17b-128e-instruct",
                   tools: List[Dict] = None, max_tokens: int = 500,
                   temperature: float = 0.7) -> CallResult:
        import httpx
        t0 = time.time()
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        body = {
            "model": model,
            "messages": messages,
            "max_tokens": max_tokens,
            "temperature": temperature,
        }
        if tools:
            body["tools"] = tools
            body["tool_choice"] = "auto"

        try:
            async with httpx.AsyncClient(timeout=35) as client:
                r = await client.post(
                    f"{self.base_url}/chat/completions",
                    headers=headers, json=body
                )
            ms = round((time.time() - t0) * 1000)
            if r.status_code != 200:
                return CallResult(text="", tool_calls=[], model=model,
                                  provider=self.provider, latency_ms=ms,
                                  error=f"HTTP {r.status_code}: {r.text[:200]}")

            data = r.json()
            choice = data["choices"][0]
            msg = choice["message"]

            tool_calls = []
            if "tool_calls" in msg and msg["tool_calls"]:
                for tc in msg["tool_calls"]:
                    tool_calls.append({
                        "name": tc["function"]["name"],
                        "arguments": tc["function"]["arguments"]
                    })

            thinking = ""
            if "reasoning_content" in msg:
                thinking =


SiliconFlowAdapter

类 SiliconFlowAdapter 在 core/model_adapter.py: 硅基流动适配器 | 方法: __init__, call

class SiliconFlowAdapter:
    """硅基流动适配器"""

    def __init__(self, api_key: str = ""):
        key = api_key or os.environ.get("SILICONFLOW_KEY", "")
        super().__init__("siliconflow", key, "https://api.siliconflow.cn/v1")

    async def call(self, messages: List[Dict], model: str = "Qwen/Qwen2.5-7B-Instruct",
                   tools: List[Dict] = None, max_tokens: int = 500,
                   temperature: float = 0.7) -> CallResult:
        import httpx
        t0 = time.time()
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        body = {
            "model": model,
            "messages": messages,
            "max_tokens": max_tokens,
            "temperature": temperature,
        }
        if tools:
            body["tools"] = tools
            body["tool_choice"] = "auto"

        try:
            async with httpx.AsyncClient(timeout=30) as client:
                r = await client.post(
                    f"{self.base_url}/chat/completions",
                    headers=headers, json=body
                )
            ms = round((time.time() - t0) * 1000)
            if r.status_code != 200:
                return CallResult(text="", tool_calls=[], model=model,
                                  provider=self.provider, latency_ms=ms,
                                  error=f"HTTP {r.status_code}: {r.text[:200]}")

            data = r.json()
            choice = data["choices"][0]
            msg = choice["message"]

            tool_calls = []
            if "tool_calls" in msg and msg["tool_calls"]:
                for tc in msg["tool_calls"]:
                    tool_calls.append({
                        "name": tc["function"]["name"],
                        "arguments": tc["function"]["arguments"]
                    })

            usage = data.get("usage", {})
            return CallResult(
                text=msg.get("content", "")


SiliconFlowEmbeddingAdapter

类 SiliconFlowEmbeddingAdapter 在 core/model_adapter.py: 硅基流动嵌入模型适配器 | 方法: __init__, embed

class SiliconFlowEmbeddingAdapter:
    """硅基流动嵌入模型适配器"""

    def __init__(self, api_key: str = ""):
        key = api_key or os.environ.get("SILICONFLOW_KEY", "")
        super().__init__("siliconflow", key, "https://api.siliconflow.cn/v1")

    async def embed(self, texts: List[str], model: str = "BAAI/bge-m3",
                    encoding_format: str = "float") -> Dict:
        """获取文本嵌入向量"""
        import httpx
        t0 = time.time()
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        body = {
            "model": model,
            "input": texts,
            "encoding_format": encoding_format,
        }
        try:
            async with httpx.AsyncClient(timeout=30) as client:
                r = await client.post(
                    f"{self.base_url}/embeddings",
                    headers=headers, json=body
                )
            ms = round((time.time() - t0) * 1000)
            if r.status_code != 200:
                return {"error": f"HTTP {r.status_code}: {r.text[:200]}", "latency_ms": ms}
            data = r.json()
            return {
                "embeddings": [d["embedding"] for d in data["data"]],
                "model": data.get("model", model),
                "usage": data.get("usage", {}),
                "latency_ms": ms
            }
        except Exception as e:
            ms = round((time.time() - t0) * 1000)
            return {"error": str(e), "latency_ms": ms}


SiliconFlowRerankerAdapter

硅基流动重排序模型适配器

类 SiliconFlowRerankerAdapter 在 core/model_adapter.py: 硅基流动重排序模型适配器 | 方法: __init__, rerank

class SiliconFlowRerankerAdapter:
    """硅基流动重排序模型适配器"""

    def __init__(self, api_key: str = ""):
        key = api_key or os.environ.get("SILICONFLOW_KEY", "")
        super().__init__("siliconflow", key, "https://api.siliconflow.cn/v1")

    async def rerank(self, query: str, documents: List[str],
                     model: str = "BAAI/bge-reranker-v2-m3", top_n: int = 5) -> Dict:
        """对文档进行重排序"""
        import httpx
        t0 = time.time()
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        body = {
            "model": model,
            "query": query,
            "documents": documents,
            "top_n": min(top_n, len(documents)),
            "return_documents": True,
        }
        try:
            async with httpx.AsyncClient(timeout=30) as client:
                r = await client.post(
                    f"{self.base_url}/rerank",
                    headers=headers, json=body
                )
            ms = round((time.time() - t0) * 1000)
            if r.status_code != 200:
                return {"error": f"HTTP {r.status_code}: {r.text[:200]}", "latency_ms": ms}
            data = r.json()
            return {
                "results": data.get("results", []),
                "model": data.get("model", model),
                "latency_ms": ms
            }
        except Exception as e:
            ms = round((time.time() - t0) * 1000)
            return {"error": str(e), "latency_ms": ms}

# 适配器工厂


test

函数 test() 在 core/model_adapter.py:

def test():
        print("=== 模型适配器测试 ===\n")

        # 测试智谱
        zhipu = ZhipuAdapter()
        if zhipu.api_key:
            r = await zhipu.call(
                messages=[{"role": "user", "content": "1+1=? 只回复OK"}],
                model="glm-4-flash-250414",
                max_tokens=10
            )
            print(f"智谱 GLM-4-Flash: {r.text[:50]} ({r.latency_ms}ms)")
            if r.error:
                print(f"  错误: {r.error}")
        else:
            print("智谱: 无API Key, 跳过")

        # 测试NIM
        nim = NvidiaNimAdapter()
        if nim.api_key:
            r = await nim.call(
                messages=[{"role": "user", "content": "1+1=? 只回复OK"}],
                model="meta/llama-4-maverick-17b-128e-instruct",
                max_tokens=10
            )
            print(f"NIM Llama-4: {r.text[:50]} ({r.latency_ms}ms)")
            if r.error:
                print(f"  错误: {r.error}")
        else:
            print("NIM: 无API Key, 跳过")

        print("\n✅ 适配器测试完成")

    asyncio.run(test())


文件 core/swarm_node.py: 虫群v8 — 集成核心 (Swarm Integration Core)

三层架构统一入口：
1. 参数化记忆模型 — 数据存参数，模型即数据库
2. 聚合协议 — 临时服务器，按需组网
3. 经济系统 — 算力货币，好友免费，虫皇税收

核心流程：
  用户交互 → 记忆即时写入 → 组建临时服务器 → 调度推理 → 计费 → 结果聚合 | 定义: class SwarmNode, def __init__, def start, def stop, def chat, def smart_query, def store_memory, def recall_memory, def add_friend, def join_circle

#!/usr/bin/env python3
"""
虫群v8 — 集成核心 (Swarm Integration Core)

三层架构统一入口：
1. 参数化记忆模型 — 数据存参数，模型即数据库
2. 聚合协议 — 临时服务器，按需组网
3. 经济系统 — 算力货币，好友免费，虫皇税收

核心流程：
  用户交互 → 记忆即时写入 → 组建临时服务器 → 调度推理 → 计费 → 结果聚合
"""

import hashlib
import logging
import time
import threading
from datetime import datetime
from typing import Dict, List, Optional

logger = logging.getLogger(__name__)

from core.parametric_memory import ParametricMemoryModel, MemoryEncoder
from core.aggregation_protocol.protocol import Aggregati


SwarmNode

类 SwarmNode 在 core/swarm_node.py: 虫群节点 — 个人端完整实例

    每个用户运行一个SwarmNode，包含：
    - 参数化记忆模型：存储个人记忆
    - 聚合协议客户端：加入网络、组建临时服务器
    - 经济账户：算力交易

    这是"虫后"的完整实现 | 方法: __init__, start, stop, chat, smart_query, store_memory, recall_memory, add_friend, join_circle, list_compute, get_balance, connect_to, discover_network, get_status

class SwarmNode:
    """
    虫群节点 — 个人端完整实例

    每个用户运行一个SwarmNode，包含：
    - 参数化记忆模型：存储个人记忆
    - 聚合协议客户端：加入网络、组建临时服务器
    - 经济账户：算力交易

    这是"虫后"的完整实现
    """

    def __init__(
        self,
        node_id: str,
        name: str,
        permission_level: PermissionLevel = PermissionLevel.QUEEN,
        model_config: str = "tiny",
        lora_rank: int = 4,
        write_mode: str = "instant",
        initial_balance: float = 100.0,
    ):
        self.node_id = node_id
        self.name = name
        self.permission_level = permission_level

        # 1. 参数化记忆模型
        self.memory = ParametricMemoryModel(
            model_config=model_config,
            lora_rank=lora_rank,
            write_mode=write_mode,
            accumulate_steps=5,
            micro_epochs=3,
        )

        # 2. 聚合协议
        cap = NodeCapability(model_types=["memory", "chat"], compute_score=1.0, specializations=["memory", "chat"])
        role = NodeRole.HIVE if permission_level == PermissionLevel.OVERMIND else NodeRole.QUEEN
        self.protocol = AggregationProtocol(
            node_id=node_id,
            role=role,
            name=name,
            permission_level=permission_level,
            capabilities=["memory", "chat"],
            compute_score=cap.compute_score,
        )

        # 3. 经济系统
        self.economy = SwarmEconomy()
        self.economy.register_node(node_id, initial_balance=initial_balance)

        # 4. 推理服务
        from core.inference_service import InferenceService, DistributedInferenceBridge
        self.inference = InferenceService(self.memory, node_id)
        self.inference_bridge = DistributedInferenceBridge()
        self.inference_bridge.register_service(node_id, self.inference)

        # 5. API推理 + MOA聚合
        from core.api_inference import APIInferenceManager
        from core.moa_aggregator import MOAAggregator, AggregationStrategy, ModelAnswer
        self.api_manager = APIInferenceManager.from_env()
        self.moa = MOAAggregator(AggregationStra


start

方法 SwarmNode.start():
        """启动节点"""
        self.protocol.start()
        print(f"[SwarmNode] {self.name} 启动完成")

def start(self):
        """启动节点"""
        self.protocol.start()
        print(f"[SwarmNode] {self.name} 启动完成")


stop

方法 SwarmNode.stop():
        """停止节点"""
        self.memory.save()
        print(f"[SwarmNode] {self.name} 已停止")

    #


方法 SwarmNode.add_friend():
        """添加好友（双方免费调用）"""
        self.economy.add_friend(self.node_id, friend_id)
        self.ec

def add_friend(self):
        """添加好友（双方免费调用）"""
        self.economy.add_friend(self.node_id, friend_id)
        self.economy.add_friend(friend_id, self.node_id)


方法 SwarmNode.join_circle():
        """加入圈子（圈内免费/折扣）"""
        self.economy.create_circle(circle_name, self.node_id)
        f

def join_circle(self):
        """加入圈子（圈内免费/折扣）"""
        self.economy.create_circle(circle_name, self.node_id)
        for mid in member_ids:
            self.economy.join_circle(circle_name, mid)


方法 SwarmNode.list_compute():
        """挂出算力出售"""
        from core.aggregation_protocol.economy_types import ResourceType

def list_compute(self):
        """挂出算力出售"""
        from core.aggregation_protocol.economy_types import ResourceType
        self.economy.sell_compute(
            provider_id=self.node_id,
            resource=ResourceType.INFERENCE,
            units=units,
            price=price_per_unit,
            friend_free=friend_free,
        )


方法 SwarmNode.connect_to():
        """连接到另一个节点（本地模拟）"""
        # 注册对方节点到协议
        other_info = other_node.protocol.node_info

def connect_to(self):
        """连接到另一个节点（本地模拟）"""
        # 注册对方节点到协议
        other_info = other_node.protocol.node_info
        self.protocol.add_remote_node(
            node_id=other_info.node_id,
            name=other_info.name,
            permission_level=other_info.permission_level,
            capabilities=other_info.capability.specializations,
            compute_score=other_info.capability.compute_score,
        )
        # 注册经济账户
        try:
            bal = self.economy.currency.get_balance(other_node.node_id)
        except:
            bal = None
        if not bal:
            self.economy.register_node(other_node.node_id, initial_balance=100.0)


SwarmNetwork

虫群网络 — 多节点模拟/管理

    用于本地测试和演示

类 SwarmNetwork 在 core/swarm_node.py: 虫群网络 — 多节点模拟/管理

    用于本地测试和演示 | 方法: __init__, create_node, connect_all, add_friendship, create_circle, get_network_status

class SwarmNetwork:
    """
    虫群网络 — 多节点模拟/管理

    用于本地测试和演示
    """

    def __init__(self):
        self.nodes: Dict[str, SwarmNode] = {}
        self.economy = SwarmEconomy()

    def create_node(self, node_id: str, name: str,
                    permission: PermissionLevel = PermissionLevel.QUEEN,
                    model_config: str = "tiny",
                    initial_balance: float = 100.0) -> SwarmNode:
        """创建并注册一个节点"""
        node = SwarmNode(
            node_id=node_id,
            name=name,
            permission_level=permission,
            model_config=model_config,
            initial_balance=initial_balance,
        )
        node.start()
        self.nodes[node_id] = node
        return node

    def connect_all(self):
        """所有节点互相连接"""
        node_list = list(self.nodes.values())
        for i, node_a in enumerate(node_list):
            for j, node_b in enumerate(node_list):
                if i != j:
                    node_a.connect_to(node_b)

    def add_friendship(self, id_a: str, id_b: str):
        """建立好友关系"""
        self.nodes[id_a].add_friend(id_b)

    def create_circle(self, name: str, member_ids: List[str]):
        """创建圈子"""
        creator = member_ids[0] if member_ids else ""
        self.economy.create_circle(name, creator)
        for mid in member_ids:
            self.economy.join_circle(name, mid)
            # 同步到各节点的economy
            if mid in self.nodes:
                self.nodes[mid].economy.create_circle(name, mid)
                for other_id in member_ids:
                    if other_id != mid:
                        self.nodes[mid].economy.join_circle(name, other_id)

    def get_network_status(self) -> Dict:
        """获取全网状态"""
        return {
            "total_nodes": len(self.nodes),
            "nodes": {nid: node.get_status() for nid, node in self.nodes.items()},
        }


方法 SwarmNetwork.connect_all():
        """所有节点互相连接"""
        node_list = list(self.nodes.values())
        for i, node_a in enume

def connect_all(self):
        """所有节点互相连接"""
        node_list = list(self.nodes.values())
        for i, node_a in enumerate(node_list):
            for j, node_b in enumerate(node_list):
                if i != j:
                    node_a.connect_to(node_b)


方法 SwarmNetwork.add_friendship():
        """建立好友关系"""
        self.nodes[id_a].add_friend(id_b)

def add_friendship(self):
        """建立好友关系"""
        self.nodes[id_a].add_friend(id_b)


方法 SwarmNetwork.create_circle():
        """创建圈子"""
        creator = member_ids[0] if member_ids else ""
        self.economy.creat

def create_circle(self):
        """创建圈子"""
        creator = member_ids[0] if member_ids else ""
        self.economy.create_circle(name, creator)
        for mid in member_ids:
            self.economy.join_circle(name, mid)
            # 同步到各节点的economy
            if mid in self.nodes:
                self.nodes[mid].economy.create_circle(name, mid)
                for other_id in member_ids:
                    if other_id != mid:
                        self.nodes[mid].economy.join_circle(name, other_id)


文件 core/api_inference.py: API推理适配器 — 对接智谱GLM和NIM的云端大模型
支持：智谱GLM-4-flash(免费)/GLM-4-plus, NIM多模型 | 定义: class
class, class
class, class ZhipuAdapter, def __init__, def chat, def chat_sync, class NIMAdapter, def __init__, def chat_sync, class APIInferenceManager

os json time logging hashlib typing dataclasses

"""
API推理适配器 — 对接智谱GLM和NIM的云端大模型
支持：智谱GLM-4-flash(免费)/GLM-4-plus, NIM多模型
"""
import os
import json
import time
import logging
import hashlib
from typing import List, Dict, Optional
from dataclasses import dataclass, field

logger = logging.getLogger(__name__)

@dataclass
class APIModelConfig:
    """API模型配置"""
    provider: str        # zhipu / nim
    model_name: str      # glm-4-flash / nim-text etc
    api_key: str
    base_url: str
    max_tokens: int = 512
    temperature: float = 0.7
    t


APIModelConfig

类 APIModelConfig 在 core/api_inference.py: API模型配置 | 方法:

class APIModelConfig:
    """API模型配置"""
    provider: str        # zhipu / nim
    model_name: str      # glm-4-flash / nim-text etc
    api_key: str
    base_url: str
    max_tokens: int = 512
    temperature: float = 0.7
    timeout: int = 30
    priority: int = 0    # 越高越优先
    free: bool = True    # 是否免费

@dataclass


APIInferenceResult

类 APIInferenceResult 在 core/api_inference.py: API推理结果 | 方法:

class APIInferenceResult:
    """API推理结果"""
    answer: str
    model: str
    provider: str
    latency_ms: float
    tokens_used: int = 0
    success: bool = True
    error: str = ""


ZhipuAdapter

类 ZhipuAdapter 在 core/api_inference.py: 智谱GLM适配器 | 方法: __init__, chat, chat_sync

class ZhipuAdapter:
    """智谱GLM适配器"""

    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://open.bigmodel.cn/api/paas/v4/chat/completions"

    async def chat(self, model: str, messages: List[Dict],
                   max_tokens: int = 512, temperature: float = 0.7) -> APIInferenceResult:
        import urllib.request
        start = time.time()
        payload = json.dumps({
            "model": model,
            "messages": messages,
            "max_tokens": max_tokens,
            "temperature": temperature
        }).encode()
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        req = urllib.request.Request(self.base_url, data=payload, headers=headers)
        try:
            with urllib.request.urlopen(req, timeout=30) as resp:
                data = json.loads(resp.read().decode())
                answer = data["choices"][0]["message"]["content"]
                tokens = data.get("usage", {}).get("total_tokens", 0)
                latency = (time.time() - start) * 1000
                return APIInferenceResult(
                    answer=answer, model=model, provider="zhipu",
                    latency_ms=latency, tokens_used=tokens, success=True
                )
        except Exception as e:
            latency = (time.time() - start) * 1000
            return APIInferenceResult(
                answer="", model=model, provider="zhipu",
                latency_ms=latency, success=False, error=str(e)
            )

    def chat_sync(self, model: str, messages: List[Dict],
                  max_tokens: int = 512, temperature: float = 0.7) -> APIInferenceResult:
        """同步版本"""
        import urllib.request
        start = time.time()
        payload = json.dumps({
            "model": model,
            "messages": messages,
            "max_tokens": max_tokens,
            "temperature": temperature
        }).encode()


NIMAdapter

类 NIMAdapter 在 core/api_inference.py: NIM(NVIDIA)适配器 | 方法: __init__, chat_sync

class NIMAdapter:
    """NIM(NVIDIA)适配器"""

    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://integrate.api.nvidia.com/v1/chat/completions"

    def chat_sync(self, model: str, messages: List[Dict],
                  max_tokens: int = 512, temperature: float = 0.7) -> APIInferenceResult:
        import urllib.request
        start = time.time()
        payload = json.dumps({
            "model": model,
            "messages": messages,
            "max_tokens": max_tokens,
            "temperature": temperature
        }).encode()
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        req = urllib.request.Request(self.base_url, data=payload, headers=headers)
        try:
            with urllib.request.urlopen(req, timeout=60) as resp:
                data = json.loads(resp.read().decode())
                answer = data["choices"][0]["message"]["content"]
                tokens = data.get("usage", {}).get("total_tokens", 0)
                latency = (time.time() - start) * 1000
                logger.info(f"[NIM] {model} 回答成功, {latency:.0f}ms, {tokens}tokens")
                return APIInferenceResult(
                    answer=answer, model=model, provider="nim",
                    latency_ms=latency, tokens_used=tokens, success=True
                )
        except Exception as e:
            latency = (time.time() - start) * 1000
            logger.warning(f"[NIM] {model} 调用失败: {e}")
            return APIInferenceResult(
                answer="", model=model, provider="nim",
                latency_ms=latency, success=False, error=str(e)
            )


APIInferenceManager

API推理管理器 — 统一管理多个API模型

类 APIInferenceManager 在 core/api_inference.py: API推理管理器 — 统一管理多个API模型 | 方法: __init__, add_provider, register_model, get_available_models, infer, infer_multi, _call, _update_stats, from_env

class APIInferenceManager:
    """API推理管理器 — 统一管理多个API模型"""

    def __init__(self):
        self.adapters: Dict[str, object] = {}  # provider -> adapter
        self.models: List[APIModelConfig] = []
        self.stats = {"total_calls": 0, "success": 0, "failed": 0, "total_ms": 0}

    def add_provider(self, provider: str, api_key: str):
        """添加API提供商"""
        if provider == "zhipu":
            self.adapters["zhipu"] = ZhipuAdapter(api_key)
        elif provider == "nim":
            self.adapters["nim"] = NIMAdapter(api_key)
        else:
            raise ValueError(f"未知提供商: {provider}")
        logger.info(f"[APIManager] 添加提供商: {provider}")

    def register_model(self, config: APIModelConfig):
        """注册可用模型"""
        self.models.append(config)
        # 按优先级排序
        self.models.sort(key=lambda m: m.priority, reverse=True)
        logger.info(f"[APIManager] 注册模型: {config.provider}/{config.model_name}, 优先级={config.priority}")

    def get_available_models(self, free_only: bool = False) -> List[APIModelConfig]:
        """获取可用模型列表"""
        models = self.models
        if free_only:
            models = [m for m in models if m.free]
        return models

    def infer(self, question: str, context: str = "",
              model_name: str = None, max_tokens: int = 512) -> APIInferenceResult:
        """单模型推理"""
        messages = []
        if context:
            messages.append({"role": "system", "content": context})
        messages.append({"role": "user", "content": question})

        # 指定模型
        if model_name:
            for m in self.models:
                if m.model_name == model_name:
                    adapter = self.adapters.get(m.provider)
                    if adapter:
                        result = adapter.chat_sync(m.model_name, messages, max_tokens, m.temperature)
                        self._update_stats(result)
                        return result

        # 自动选择最高优先级可用模型
        for m in self.models:


方法 APIInferenceManager.add_provider():
        """添加API提供商"""
        if provider == "zhipu":
            self.adapters["zhipu"] = ZhipuAd

def add_provider(self):
        """添加API提供商"""
        if provider == "zhipu":
            self.adapters["zhipu"] = ZhipuAdapter(api_key)
        elif provider == "nim":
            self.adapters["nim"] = NIMAdapter(api_key)
        else:
            raise ValueError(f"未知提供商: {provider}")
        logger.info(f"[APIManager] 添加提供商: {provider}")


方法 APIInferenceManager.register_model():
        """注册可用模型"""
        self.models.append(config)
        # 按优先级排序
        self.models.sort(k

def register_model(self):
        """注册可用模型"""
        self.models.append(config)
        # 按优先级排序
        self.models.sort(key=lambda m: m.priority, reverse=True)
        logger.info(f"[APIManager] 注册模型: {config.provider}/{config.model_name}, 优先级={config.priority}")


文件 core/aggregation_protocol/__init__.py: 虫群聚合协议 — 统一入口 | 定义:

.types .discovery .transport .scheduler .permission .protocol .economy_types .currency .social .marketplace .economy

"""
虫群聚合协议 — 统一入口
"""

from .types import (
    NodeInfo, NodeCapability, PermissionLevel,
    AggregationStrategy, TaskForce, TaskForceStatus,
    AggregationTask, ProtocolMessage, PermissionGrant,
)
from .discovery import NodeRegistry
from .transport import MessageBus, LocalTransport
from .scheduler import TaskForceManager, AggregationStrategy
from .permission import PermissionManager, PermissionLevel
from .protocol import AggregationProtocol
from .economy_types import (
    ResourceType, Pric


currency.py

文件 core/aggregation_protocol/currency.py: 虫群经济系统 — 算力货币(Compute Credit)

核心逻辑：
- 每个节点有CC账户
- 虫皇收税：每笔交易抽取税率
- 贡献算力→获得CC，使用算力→消费CC
- 虫皇将税收分配给高贡献成员(提升权限) | 定义: class ComputeCredit, def __init__, def create_account, def get_account, def get_balance, def transfer, def charge_usage, def distribute_tax, def set_price, def set_reserved_sale

hashlib time datetime typing .economy_types

#!/usr/bin/env python3
"""
虫群经济系统 — 算力货币(Compute Credit)

核心逻辑：
- 每个节点有CC账户
- 虫皇收税：每笔交易抽取税率
- 贡献算力→获得CC，使用算力→消费CC
- 虫皇将税收分配给高贡献成员(提升权限)
"""

import hashlib
import time
from datetime import datetime
from typing import Dict, List, Optional, Tuple

from .economy_types import (
    Account, Transaction, TransactionType, ResourceType, ComputePrice, PricingMode
)

class ComputeCredit:
    """算力货币系统"""

    # 虫皇税率
    TAX_RATE = 0.05  # 5%交易税
    # 新用户赠送
    SIGNUP_BONUS = 100.0
    # 算力兑换率：1单位推理


ComputeCredit

类 ComputeCredit 在 core/aggregation_protocol/currency.py: 算力货币系统 | 方法: __init__, create_account, get_account, get_balance, transfer, charge_usage, distribute_tax, set_price, set_reserved_sale, get_stats, get_leaderboard

class ComputeCredit:
    """算力货币系统"""

    # 虫皇税率
    TAX_RATE = 0.05  # 5%交易税
    # 新用户赠送
    SIGNUP_BONUS = 100.0
    # 算力兑换率：1单位推理 = 1 CC
    UNIT_RATES = {
        ResourceType.INFERENCE: 1.0,
        ResourceType.TRAINING: 2.0,
        ResourceType.MEMORY_WRITE: 0.5,
        ResourceType.STORAGE: 0.1,
    }

    def __init__(self, overmind_id: str = "overmind"):
        self.overmind_id = overmind_id
        self.accounts: Dict[str, Account] = {}
        self.transactions: List[Transaction] = []
        self.overmind_balance = 0.0  # 虫皇税收余额
        self._tax_distributions: List[Dict] = []

    # ============================================================
    # 账户管理
    # ============================================================

    def create_account(self, node_id: str, initial_balance: float = None) -> Account:
        """创建账户"""
        if node_id in self.accounts:
            return self.accounts[node_id]
        acc = Account(
            node_id=node_id,
            balance=initial_balance if initial_balance is not None else self.SIGNUP_BONUS,
        )
        # 默认定价
        acc.pricing["inference"] = ComputePrice(
            resource_type=ResourceType.INFERENCE,
            mode=PricingMode.PER_TOKEN,
            price_per_unit=0.01,
            friend_discount=1.0,   # 好友免费
            circle_discount=1.0,   # 圈子免费
            min_price=0.001,
        )
        acc.pricing["training"] = ComputePrice(
            resource_type=ResourceType.TRAINING,
            mode=PricingMode.PER_HOUR,
            price_per_unit=0.5,
            friend_discount=0.8,   # 好友8折
            circle_discount=0.9,   # 圈子9折
            min_price=0.1,
        )
        self.accounts[node_id] = acc
        return acc

    def get_account(self, node_id: str) -> Optional[Account]:
        return self.accounts.get(node_id)

    def get_balance(self, node_id: str) -> float:
        acc = self.accounts.get(node_id)
        return acc.balance if acc else 0.0

    # =====


方法 ComputeCredit.set_price():
        """节点自定义定价"""
        acc = self.accounts.get(node_id)
        if not acc:
            retu

def set_price(self):
        """节点自定义定价"""
        acc = self.accounts.get(node_id)
        if not acc:
            return
        acc.pricing[resource.value] = ComputePrice(
            resource_type=resource,
            mode=PricingMode.PER_TOKEN,
            price_per_unit=price_per_unit,
            friend_discount=friend_discount,
            circle_discount=circle_discount,
            min_price=min_price,
        )


方法 ComputeCredit.set_reserved_sale():
        """设定预留出售算力量"""
        acc = self.accounts.get(node_id)
        if acc:
            acc.re


文件 core/aggregation_protocol/task_dispatcher.py: 虫群任务分配器
- 基于推理能力的负载均衡
- 任务队列管理
- 结果聚合 | 定义: class
class, class TaskDistributor, def __init__, def register_handler, def submit_task, def _dispatch_next, def _select_best_node, def _select_by_gateway, def _get_node_status, def _execute_task

logging threading time uuid dataclasses datetime typing .types

#!/usr/bin/env python3
"""
虫群任务分配器
- 基于推理能力的负载均衡
- 任务队列管理
- 结果聚合
"""
import logging
import threading
import time
import uuid
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Callable, Dict, List, Optional

from .types import NodeInfo, NodeRole, TaskResult, TaskStatus

logger = logging.getLogger(__name__)

@dataclass
class Task:
    """任务单元"""
    task_id: str
    task_type: str  # inference/memory/aggregation
    payload: Dict[str, Any]
    priority


Task

类 Task 在 core/aggregation_protocol/task_dispatcher.py: 任务单元 | 方法:

class Task:
    """任务单元"""
    task_id: str
    task_type: str  # inference/memory/aggregation
    payload: Dict[str, Any]
    priority: int = 0
    timeout: float = 60.0

    created_at: datetime = field(default_factory=datetime.now)
    assigned_to: str = ""  # 节点ID
    status: TaskStatus = TaskStatus.PENDING

    result: Any = None
    error: str = ""


TaskDistributor

类 TaskDistributor 在 core/aggregation_protocol/task_dispatcher.py: 任务分配器

    策略：
    1. 基于节点推理能力评分
    2. 考虑节点负载和健康度
    3. 支持任务优先级
    4. 失败自动重试 | 方法: __init__, register_handler, submit_task, _dispatch_next, _select_best_node, _select_by_gateway, _get_node_status, _execute_task, _default_inference, get_task_status, get_stats, wait_task

class TaskDistributor:
    """
    任务分配器

    策略：
    1. 基于节点推理能力评分
    2. 考虑节点负载和健康度
    3. 支持任务优先级
    4. 失败自动重试
    """

    def __init__(self, node_registry, gateway=None):
        self.registry = node_registry
        self.gateway = gateway  # 统一推理网关

        # 任务队列
        self._pending_tasks: List[Task] = []
        self._running_tasks: Dict[str, Task] = {}
        self._completed_tasks: Dict[str, Task] = {}

        self._lock = threading.RLock()
        self._task_handlers: Dict[str, Callable] = {}

        # 配置
        self.max_concurrent = 5  # 最大并发任务
        self.retry_count = 2  # 重试次数

    def register_handler(self, task_type: str, handler: Callable):
        """注册任务处理器"""
        self._task_handlers[task_type] = handler

    def submit_task(self, task_type: str, payload: Dict,
                   priority: int = 0, timeout: float = 60.0) -> str:
        """提交任务"""
        task = Task(
            task_id=str(uuid.uuid4())[:8],
            task_type=task_type,
            payload=payload,
            priority=priority,
            timeout=timeout,
        )

        with self._lock:
            self._pending_tasks.append(task)
            # 按优先级排序
            self._pending_tasks.sort(key=lambda t: -t.priority)

        logger.info(f"任务提交: {task.task_id} ({task_type})")
        self._dispatch_next()
        return task.task_id

    def _dispatch_next(self):
        """分发下一个任务"""
        with self._lock:
            # 检查并发限制
            if len(self._running_tasks) >= self.max_concurrent:
                return

            if not self._pending_tasks:
                return

            task = self._pending_tasks.pop(0)

        # 选择最佳节点
        target_node = self._select_best_node(task)

        if not target_node:
            # 无可用节点，放回队列
            with self._lock:
                self._pending_tasks.insert(0, task)
            logger.warning(f"无可用节点，任务 {task.task_id} 等待中")


方法 TaskDistributor.register_handler():
        """注册任务处理器"""
        self._task_handlers[task_type] = handler

def register_handler(self):
        """注册任务处理器"""
        self._task_handlers[task_type] = handler


marketplace.py

文件 core/aggregation_protocol/marketplace.py: 虫群经济系统 — 算力交易市场

核心逻辑：
- 节点发布可用算力(含价格)
- 需求方搜索并购买算力
- 好友/圈子自动免费
- 权限调用不走市场(走税收) | 定义: class ComputeListing, def __init__, def consume, def to_dict, class Marketplace, def __init__, def list_compute, def search, def purchase, def purchase_cheapest

hashlib time datetime typing .economy_types .currency .social

#!/usr/bin/env python3
"""
虫群经济系统 — 算力交易市场

核心逻辑：
- 节点发布可用算力(含价格)
- 需求方搜索并购买算力
- 好友/圈子自动免费
- 权限调用不走市场(走税收)
"""

import hashlib
import time
from datetime import datetime
from typing import Dict, List, Optional, Tuple

from .economy_types import ResourceType, ComputePrice, PricingMode
from .currency import ComputeCredit
from .social import SocialGraph

class ComputeListing:
    """算力出售挂单"""

    def __init__(self, provider_id: str, resource: ResourceType,
                 available_units: flo


ComputeListing

类 ComputeListing 在 core/aggregation_protocol/marketplace.py: 算力出售挂单 | 方法: __init__, consume, to_dict

class ComputeListing:
    """算力出售挂单"""

    def __init__(self, provider_id: str, resource: ResourceType,
                 available_units: float, price: ComputePrice,
                 description: str = ""):
        self.listing_id = hashlib.md5(
            f"{provider_id}{resource.value}{time.time()}".encode()
        ).hexdigest()[:10]
        self.provider_id = provider_id
        self.resource = resource
        self.available_units = available_units
        self.remaining_units = available_units
        self.price = price
        self.description = description
        self.created_at = datetime.now()
        self.active = True

    def consume(self, units: float) -> bool:
        """消费算力"""
        if units > self.remaining_units:
            return False
        self.remaining_units -= units
        if self.remaining_units <= 0:
            self.active = False
        return True

    def to_dict(self) -> Dict:
        return {
            "listing_id": self.listing_id,
            "provider": self.provider_id,
            "resource": self.resource.value,
            "available": self.remaining_units,
            "price_per_unit": self.price.price_per_unit,
            "friend_free": self.price.friend_discount >= 1.0,
            "circle_free": self.price.circle_discount >= 1.0,
            "active": self.active,
        }


Marketplace

类 Marketplace 在 core/aggregation_protocol/marketplace.py: 算力交易市场 | 方法: __init__, list_compute, search, purchase, purchase_cheapest, get_stats

class Marketplace:
    """算力交易市场"""

    def __init__(self, currency: ComputeCredit, social: SocialGraph):
        self.currency = currency
        self.social = social
        self.listings: Dict[str, ComputeListing] = {}   # listing_id -> Listing
        self.provider_listings: Dict[str, List[str]] = {} # provider -> [listing_ids]
        self.trade_history: List[Dict] = []

    # ============================================================
    # 发布算力
    # ============================================================

    def list_compute(self, provider_id: str, resource: ResourceType,
                     units: float, price_per_unit: float = 0.01,
                     friend_discount: float = 1.0,
                     circle_discount: float = 1.0,
                     min_price: float = 0.001,
                     desc: str = "") -> Optional[ComputeListing]:
        """
        发布算力出售
        provider_id: 出售方节点ID
        resource: 资源类型
        units: 可用算力量
        price_per_unit: 单价(CC)
        friend_discount: 好友折扣(1.0=免费)
        circle_discount: 圈子折扣(1.0=免费)
        """
        acc = self.currency.get_account(provider_id)
        if not acc:
            return None

        price = ComputePrice(
            resource_type=resource,
            mode=PricingMode.PER_TOKEN,
            price_per_unit=price_per_unit,
            friend_discount=friend_discount,
            circle_discount=circle_discount,
            min_price=min_price,
        )

        listing = ComputeListing(
            provider_id=provider_id,
            resource=resource,
            available_units=units,
            price=price,
            description=desc,
        )

        self.listings[listing.listing_id] = listing
        self.provider_listings.setdefault(provider_id, []).append(listing.listing_id)
        return listing

    # ============================================================
    # 搜索算力
    # ======================================================


permission.py

文件 core/aggregation_protocol/permission.py: 虫群聚合协议 — 权限管理

核心设计：
- 权限 = 调用系统内其他人的模型的权限
- 虫皇(OVERMIND): 可调用系统所有在线模型
- 脑虫(CEREBRATE): 可调用管辖区域内模型
- 虫后(QUEEN): 可调用授权范围内的模型
- 子虫(DRONE): 仅能被调用，不能主动调用

临时授权机制：
- 虫皇可以给任何节点授权
- 脑虫可以给管辖内的虫后授权
- 虫后可以邀请其他虫 | 定义: class PermissionManager, def __init__, def can_call_node, def get_callable_nodes, def get_max_callable_count, def grant_permission, def revoke_permission, def register_region, def add_to_region, def _is_in_region

hashlib logging threading time collections datetime typing .types

#!/usr/bin/env python3
"""
虫群聚合协议 — 权限管理

核心设计：
- 权限 = 调用系统内其他人的模型的权限
- 虫皇(OVERMIND): 可调用系统所有在线模型
- 脑虫(CEREBRATE): 可调用管辖区域内模型
- 虫后(QUEEN): 可调用授权范围内的模型
- 子虫(DRONE): 仅能被调用，不能主动调用

临时授权机制：
- 虫皇可以给任何节点授权
- 脑虫可以给管辖内的虫后授权
- 虫后可以邀请其他虫后加入临时服务器
- 授权可设过期时间
"""

import hashlib
import logging
import threading
import time
from collections import defaultdict
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Set

from .types import (
    NodeInfo, NodeRole, PermissionLevel, Perm


PermissionManager

类 PermissionManager 在 core/aggregation_protocol/permission.py: 权限管理器 — 控制模型调用范围和数量

    类似服务器集群的RBAC权限系统：
    - 角色决定基础权限
    - 授权(Grant)扩展具体权限
    - 权限检查在每次调用前执行 | 方法: __init__, can_call_node, get_callable_nodes, get_max_callable_count, grant_permission, revoke_permission, register_region, add_to_region, _is_in_region, _has_grant, set_node_permission, get_node_permission, get_stats

class PermissionManager:
    """
    权限管理器 — 控制模型调用范围和数量

    类似服务器集群的RBAC权限系统：
    - 角色决定基础权限
    - 授权(Grant)扩展具体权限
    - 权限检查在每次调用前执行
    """

    def __init__(self, self_permission: PermissionLevel = PermissionLevel.QUEEN):
        self.self_permission = self_permission

        # 权限授予记录 grant_id -> PermissionGrant
        self._grants: Dict[str, PermissionGrant] = {}

        # 节点权限缓存 node_id -> PermissionLevel
        self._node_permissions: Dict[str, PermissionLevel] = {}

        # 区域管理 cerebrate_id -> set of queen_ids
        self._regions: Dict[str, Set[str]] = defaultdict(set)

        # 线程安全
        self._lock = threading.RLock()

        # 统计
        self._stats = {
            "permission_checks": 0,
            "granted": 0,
            "denied": 0,
            "grants_issued": 0,
        }

    # ============================================================
    # 权限检查
    # ============================================================

    def can_call_node(self, caller_id: str, target_id: str,
                      node_registry=None) -> bool:
        """
        检查调用者是否有权调用目标节点

        规则：
        1. 虫皇可调用所有在线模型
        2. 脑虫可调用管辖区域内模型
        3. 虫后只能调用被授权的模型
        4. 子虫不能主动调用
        """
        with self._lock:
            self._stats["permission_checks"] += 1

            caller_level = self._node_permissions.get(caller_id, PermissionLevel.DRONE)

            # 规则1：虫皇可调用一切
            if caller_level == PermissionLevel.OVERMIND:
                self._stats["granted"] += 1
                return True

            # 规则2：脑虫可调用管辖区域内的
            if caller_level == PermissionLevel.CEREBRATE:
                # 检查目标是否在管辖区域内
                if self._is_in_region(caller_id, target_id):
                    self._stats["granted"] += 1
                    return True

            # 规则3：虫后检查授权
            if caller_level == PermissionLevel.QUEEN:
                if self._has_grant(ca


方法 PermissionManager.register_region():
        """注册脑虫管辖区域"""
        with self._lock:
            self._regions[cerebrate_id] = set(queen

def register_region(self):
        """注册脑虫管辖区域"""
        with self._lock:
            self._regions[cerebrate_id] = set(queen_ids)
            for qid in queen_ids:
                self._node_permissions[qid] = PermissionLevel.QUEEN
            self._node_permissions[cerebrate_id] = PermissionLevel.CEREBRATE


方法 PermissionManager.add_to_region():
        """将虫后添加到区域"""
        with self._lock:
            self._regions[cerebrate_id].add(queen_i


方法 PermissionManager.set_node_permission():
        """设置节点权限等级"""
        with self._lock:
            self._node_permissions[node_id] = level

def set_node_permission(self):
        """设置节点权限等级"""
        with self._lock:
            self._node_permissions[node_id] = level


文件 core/aggregation_protocol/economy_types.py: 虫群经济系统 — 类型定义

核心概念：
- 算力即货币(Compute Credit)
- 虫皇收税(系统服务费)
- 成员间算力交易(按量收费)
- 好友/圈子免费调用
- 权限=税收分配的强制调用权 | 定义: class ResourceType, class PricingMode, class TransactionType, class CircleRole, class
class, def calc_cost, class
class, def to_dict, class
class, def can_afford

#!/usr/bin/env python3
"""
虫群经济系统 — 类型定义

核心概念：
- 算力即货币(Compute Credit)
- 虫皇收税(系统服务费)
- 成员间算力交易(按量收费)
- 好友/圈子免费调用
- 权限=税收分配的强制调用权
"""

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional
from datetime import datetime

class ResourceType(Enum):
    """算力资源类型"""
    INFERENCE = "inference"       # 推理调用
    TRAINING = "training"         # 训练算力
    MEMORY_WRITE = "memory_write" # 记忆写入
    STORAGE = "storage"           # 存储空间

class PricingMode(Enu


ResourceType

类 ResourceType 在 core/aggregation_protocol/economy_types.py: 算力资源类型 | 方法:

class ResourceType:
    """算力资源类型"""
    INFERENCE = "inference"       # 推理调用
    TRAINING = "training"         # 训练算力
    MEMORY_WRITE = "memory_write" # 记忆写入
    STORAGE = "storage"           # 存储空间


PricingMode

类 PricingMode 在 core/aggregation_protocol/economy_types.py: 定价模式 | 方法:

class PricingMode:
    """定价模式"""
    PER_TOKEN = "per_token"           # 按token计费
    PER_REQUEST = "per_request"       # 按次计费
    PER_HOUR = "per_hour"             # 按时计费
    FIXED_MONTHLY = "fixed_monthly"   # 固定月费


TransactionType

类 TransactionType 在 core/aggregation_protocol/economy_types.py: 交易类型 | 方法:

class TransactionType:
    """交易类型"""
    TAX = "tax"                    # 虫皇税收
    TRADE = "trade"                # 成员交易
    GIFT = "gift"                  # 好友/圈子免费
    PERMISSION_CALL = "perm_call"  # 权限强制调用
    REWARD = "reward"              # 贡献奖励


CircleRole

类 CircleRole 在 core/aggregation_protocol/economy_types.py: 圈子角色 | 方法:

class CircleRole:
    """圈子角色"""
    OWNER = "owner"       # 圈主
    ADMIN = "admin"       # 管理员
    MEMBER = "member"     # 普通成员
    GUEST = "guest"       # 访客

@dataclass


ComputePrice

类 ComputePrice 在 core/aggregation_protocol/economy_types.py: 算力定价 | 方法: calc_cost

class ComputePrice:
    """算力定价"""
    resource_type: ResourceType
    mode: PricingMode
    price_per_unit: float          # 每单位算力价格(CC)
    friend_discount: float = 0.0   # 好友折扣(0=免费)
    circle_discount: float = 0.0   # 圈子折扣(0=免费)
    min_price: float = 0.0         # 最低价(防恶意低价)

    def calc_cost(self, units: float, is_friend: bool = False,
                  is_circle: bool = False) -> float:
        """计算费用"""
        base = self.price_per_unit * units
        if is_friend and self.friend_discount >= 1.0:
            return 0.0  # 好友免费
        if is_circle and self.circle_discount >= 1.0:
            return 0.0  # 圈子免费
        discount = 0.0
        if is_friend:
            discount = self.friend_discount
        elif is_circle:
            discount = self.circle_discount
        return max(base * (1.0 - discount), self.min_price * units)

@dataclass


Transaction

类 Transaction 在 core/aggregation_protocol/economy_types.py: 交易记录 | 方法: to_dict

class Transaction:
    """交易记录"""
    tx_id: str
    from_node: str           # 付款方
    to_node: str             # 收款方
    amount: float            # 金额(CC)
    tx_type: TransactionType
    resource_type: ResourceType = ResourceType.INFERENCE
    units: float = 0.0       # 算力单位数
    description: str = ""
    timestamp: datetime = field(default_factory=datetime.now)

    def to_dict(self) -> Dict:
        return {
            "tx_id": self.tx_id,
            "from": self.from_node,
            "to": self.to_node,
            "amount": self.amount,
            "type": self.tx_type.value,
            "resource": self.resource_type.value,
            "units": self.units,
            "time": self.timestamp.isoformat(),
        }

@dataclass


Account

类 Account 在 core/aggregation_protocol/economy_types.py: 算力账户 | 方法: can_afford, to_dict

class Account:
    """算力账户"""
    node_id: str
    balance: float = 100.0              # 余额(CC)，新用户赠送100
    total_earned: float = 0.0           # 总收入
    total_spent: float = 0.0            # 总支出
    tax_paid: float = 0.0               # 已缴税
    contribution_score: float = 0.0     # 贡献分(决定权限)
    reserved_for_sale: float = 0.0      # 预留出售算力
    pricing: Dict[str, ComputePrice] = field(default_factory=dict)

    def can_afford(self, amount: float) -> bool:
        return self.balance >= amount

    def to_dict(self) -> Dict:
        return {
            "node_id": self.node_id,
            "balance": round(self.balance, 2),
            "total_earned": round(self.total_earned, 2),
            "total_spent": round(self.total_spent, 2),
            "tax_paid": round(self.tax_paid, 2),
            "contribution": round(self.contribution_score, 2),
            "reserved_sale": round(self.reserved_for_sale, 2),
        }

@dataclass


Friendship

类 Friendship 在 core/aggregation_protocol/economy_types.py: 好友关系 | 方法: to_dict

class Friendship:
    """好友关系"""
    node_a: str
    node_b: str
    created_at: datetime = field(default_factory=datetime.now)
    is_mutual: bool = True  # 双向好友

    def to_dict(self) -> Dict:
        return {"a": self.node_a, "b": self.node_b, "mutual": self.is_mutual}

@dataclass


Circle

类 Circle 在 core/aggregation_protocol/economy_types.py: 圈子 | 方法: add_member, remove_member, is_member, to_dict

class Circle:
    """圈子"""
    circle_id: str
    name: str
    owner: str
    members: Dict[str, CircleRole] = field(default_factory=dict)
    free_call: bool = True       # 圈内免费调用
    created_at: datetime = field(default_factory=datetime.now)

    def add_member(self, node_id: str, role: CircleRole = CircleRole.MEMBER):
        self.members[node_id] = role

    def remove_member(self, node_id: str):
        self.members.pop(node_id, None)

    def is_member(self, node_id: str) -> bool:
        return node_id in self.members

    def to_dict(self) -> Dict:
        return {
            "circle_id": self.circle_id,
            "name": self.name,
            "owner": self.owner,
            "members": len(self.members),
            "free_call": self.free_call,
        }


方法 Circle.add_member():
        self.members[node_id] = role

def add_member(self):
        self.members[node_id] = role


方法 Circle.remove_member():
        self.members.pop(node_id, None)

def remove_member(self):
        self.members.pop(node_id, None)


函数 add_member(self, node_id: str, role: CircleRole = CircleRole.MEMBER) 在 core/aggregation_protocol/economy_types.py:

def add_member(self, node_id: str, role: CircleRole = CircleRole.MEMBER):
        self.members[node_id] = role

    def remove_member(self, node_id: str):
        self.members.pop(node_id, None)

    def is_member(self, node_id: str) -> bool:
        return node_id in self.members

    def to_dict(self) -> Dict:
        return {
            "circle_id": self.circle_id,
            "name": self.name,
            "owner": self.owner,
            "members": len(self.members),
            "free_call": self.free_call,
        }


scheduler.py

文件 core/aggregation_protocol/scheduler.py: 虫群聚合协议 — 任务调度器

核心功能：
- 接收任务请求
- 组建临时服务器(TaskForce)
- 分配任务到各节点
- 聚合各节点结果
- 任务完成后解散临时服务器

类比GPU集群：
- 任务调度器 = SLURM/调度系统
- 临时服务器 = 临时分配的GPU组
- 节点 = 单块GPU | 定义: class TaskForceManager, def __init__, def create_taskforce, def complete_taskforce, def fail_taskforce, def submit_task, def get_taskforce, def get_active_taskforces, def aggregate_results, def _vote_aggregate

hashlib logging threading time collections datetime typing .types .discovery .transport

#!/usr/bin/env python3
"""
虫群聚合协议 — 任务调度器

核心功能：
- 接收任务请求
- 组建临时服务器(TaskForce)
- 分配任务到各节点
- 聚合各节点结果
- 任务完成后解散临时服务器

类比GPU集群：
- 任务调度器 = SLURM/调度系统
- 临时服务器 = 临时分配的GPU组
- 节点 = 单块GPU
"""

import hashlib
import logging
import threading
import time
from collections import deque
from datetime import datetime
from typing import Callable, Dict, List, Optional

from .types import (
    AggregationStrategy, AggregationTask, TaskForce, TaskForceStatus,
    NodeInfo, NodeStatus, ProtocolMessage,
)
from .disc


TaskForceManager

临时服务器管理器

    生命周期：创建 → 组建 → 运行 → 完成 → 解散

类 TaskForceManager 在 core/aggregation_protocol/scheduler.py: 临时服务器管理器

    生命周期：创建 → 组建 → 运行 → 完成 → 解散 | 方法: __init__, create_taskforce, complete_taskforce, fail_taskforce, submit_task, get_taskforce, get_active_taskforces, aggregate_results, _vote_aggregate, _sequential_aggregate, _parameter_average, _adaptive_mix, _gen_id, get_stats

class TaskForceManager:
    """
    临时服务器管理器

    生命周期：创建 → 组建 → 运行 → 完成 → 解散
    """

    def __init__(self, node_registry: NodeRegistry, message_bus: MessageBus):
        self.registry = node_registry
        self.bus = message_bus

        # 活跃的临时服务器 taskforce_id -> TaskForce
        self._taskforces: Dict[str, TaskForce] = {}
        self._lock = threading.RLock()

        # 任务队列
        self._task_queue = deque()

        # 统计
        self._stats = {
            "taskforces_created": 0,
            "taskforces_completed": 0,
            "taskforces_failed": 0,
            "tasks_processed": 0,
        }

    # ============================================================
    # 临时服务器生命周期
    # ============================================================

    def create_taskforce(self, task: AggregationTask) -> Optional[TaskForce]:
        """
        为任务创建临时服务器

        类似GPU集群分配资源：
        1. 分析任务需要的能力
        2. 从可用节点中选择
        3. 组建临时服务器
        4. 通知成员节点
        """
        # 1. 发现合适的节点
        candidates = self.registry.discover_for_task(
            required_caps=task.required_capabilities,
            min_nodes=task.min_nodes,
            max_nodes=task.max_nodes,
            exclude=[task.requester],
        )

        if len(candidates) < task.min_nodes:
            logger.warning(f"节点不足: 需要{task.min_nodes}，找到{len(candidates)}")
            return None

        # 2. 创建临时服务器
        tf_id = self._gen_id("tf")
        tf = TaskForce(
            taskforce_id=tf_id,
            name=f"TaskForce-{tf_id}",
            coordinator=task.requester,
            strategy=task.strategy,
            task_description=task.query,
        )

        # 3. 添加成员
        for node in candidates:
            tf.add_member(node.node_id)
            # 更新节点的当前任务列表
            node.current_taskforces.append(tf_id)

        # 4. 记录
        with self._lock:
            self._taskforces[tf_id] = tf
            task.taskforce_id = tf_id


方法 TaskForceManager.complete_taskforce():
        """完成任务，解散临时服务器"""
        with self._lock:
            tf = self._taskforces.get(tf_id)

def complete_taskforce(self):
        """完成任务，解散临时服务器"""
        with self._lock:
            tf = self._taskforces.get(tf_id)
            if not tf:
                return

            tf.status = TaskForceStatus.COMPLETED
            tf.completed_at = datetime.now()
            tf.results = result

            # 清理成员节点的任务列表
            for member_id in tf.members:
                node = self.registry.get_node(member_id)
                if node and tf_id in node.current_taskforces:
                    node.current_taskforces.remove(tf_id)

            self._stats["taskforces_completed"] += 1

        # 通知解散
        self.bus.broadcast("leave_taskforce", {
            "taskforce_id": tf_id,
            "status": "completed",
        })

        logger.info(f"临时服务器解散: {tf_id}")


方法 TaskForceManager.fail_taskforce():
        """临时服务器失败"""
        with self._lock:
            tf = self._taskforces.get(tf_id)

def fail_taskforce(self):
        """临时服务器失败"""
        with self._lock:
            tf = self._taskforces.get(tf_id)
            if not tf:
                return

            tf.status = TaskForceStatus.FAILED
            tf.completed_at = datetime.now()

            for member_id in tf.members:
                node = self.registry.get_node(member_id)
                if node and tf_id in node.current_taskforces:
                    node.current_taskforces.remove(tf_id)

            self._stats["taskforces_failed"] += 1

    # ============================================================
    # 任务调度
    # ============================================================


文件 core/aggregation_protocol/http_transport.py: 虫群聚合协议 — HTTP传输层

支持跨节点通信：
- HTTP长轮询/短轮询
- 自动重试
- 心跳检测 | 定义: class HttpTransport, def __init__, def add_node, def remove_node, def get_nodes, def send_message, def broadcast_message, def poll_messages, def start_polling, def stop_polling

hashlib json logging threading time datetime typing concurrent.futures dataclasses enum .types

#!/usr/bin/env python3
"""
虫群聚合协议 — HTTP传输层

支持跨节点通信：
- HTTP长轮询/短轮询
- 自动重试
- 心跳检测
"""

import hashlib
import json
import logging
import threading
import time
from datetime import datetime
from typing import Callable, Dict, List, Optional
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from enum import Enum

try:
    import requests
    HAS_REQUESTS = True
except ImportError:
    HAS_REQUESTS = False

from .types import ProtocolMessage, NodeInfo, NodeRol


HttpTransport

类 HttpTransport 在 core/aggregation_protocol/http_transport.py: HTTP传输层 — 节点间跨网络通信

    工作模式：
    1. 短轮询：定期拉取其他节点的消息
    2. 心跳：定期发送心跳维持连接
    3. 重试：失败自动重试 | 方法: __init__, add_node, remove_node, get_nodes, send_message, broadcast_message, poll_messages, start_polling, stop_polling, _polling_loop, send_heartbeat, _serialize_message, _deserialize_message, get_stats

class HttpTransport:
    """
    HTTP传输层 — 节点间跨网络通信

    工作模式：
    1. 短轮询：定期拉取其他节点的消息
    2. 心跳：定期发送心跳维持连接
    3. 重试：失败自动重试
    """

    def __init__(self, node_info: NodeInfo, poll_interval: float = 2.0,
                 heartbeat_interval: float = 10.0, timeout: float = 5.0):
        self.node_info = node_info
        self.poll_interval = poll_interval
        self.heartbeat_interval = heartbeat_interval
        self.timeout = timeout

        # 远程节点地址表
        self._nodes: Dict[str, str] = {}  # node_id -> url
        self._lock = threading.RLock()

        # 消息处理回调
        self._handlers: Dict[str, Callable] = {}

        # 运行状态
        self._running = False
        self._executor: Optional[ThreadPoolExecutor] = None

        # 统计
        self._stats = {
            "sent": 0,
            "received": 0,
            "errors": 0,
        }

        # 序列化为JSON的设置
        self._json_encoder = json.JSONEncoder(default=str)

    # ============================================================
    # 节点管理
    # ============================================================

    def add_node(self, node_id: str, url: str):
        """添加远程节点"""
        with self._lock:
            self._nodes[node_id] = url
            logger.info(f"添加远程节点: {node_id} -> {url}")

    def remove_node(self, node_id: str):
        """移除远程节点"""
        with self._lock:
            self._nodes.pop(node_id, None)
            logger.info(f"移除远程节点: {node_id}")

    def get_nodes(self) -> Dict[str, str]:
        """获取所有远程节点"""
        with self._lock:
            return dict(self._nodes)

    # ============================================================
    # 消息发送
    # ============================================================

    def send_message(self, msg: ProtocolMessage) -> bool:
        """发送消息到指定节点"""
        if not HAS_REQUESTS:
            logger.warning("requests库未安装，无法发送HTTP消息")
            return False

        with self._lock:


方法 HttpTransport.add_node():
        """添加远程节点"""
        with self._lock:
            self._nodes[node_id] = url
            lo

def add_node(self):
        """添加远程节点"""
        with self._lock:
            self._nodes[node_id] = url
            logger.info(f"添加远程节点: {node_id} -> {url}")


方法 HttpTransport.remove_node():
        """移除远程节点"""
        with self._lock:
            self._nodes.pop(node_id, None)

def remove_node(self):
        """移除远程节点"""
        with self._lock:
            self._nodes.pop(node_id, None)
            logger.info(f"移除远程节点: {node_id}")


方法 HttpTransport.start_polling():
        """启动消息轮询"""
        self._running = True
        self._message_callback = callback

def start_polling(self):
        """启动消息轮询"""
        self._running = True
        self._message_callback = callback

        self._executor = ThreadPoolExecutor(max_workers=1)
        self._executor.submit(self._polling_loop)

        logger.info(f"HTTP传输层启动轮询: {self.node_info.node_id}")


方法 HttpTransport.stop_polling():
        """停止消息轮询"""
        self._running = False
        if self._executor:
            self._exe

def stop_polling(self):
        """停止消息轮询"""
        self._running = False
        if self._executor:
            self._executor.shutdown(wait=False)
        logger.info(f"HTTP传输层停止轮询: {self.node_info.node_id}")


HttpServer

类 HttpServer 在 core/aggregation_protocol/http_transport.py: HTTP服务端 — 接收来自其他节点的消息

    提供REST API：
    - POST /message — 接收消息
    - GET /messages/{node_id} — 拉取消息
    - POST /heartbeat — 心跳 | 方法: __init__, create_app, receive_message, get_messages, heartbeat, health, start, start_background, _deserialize_message, _get_node_messages, queue_message

class HttpServer:
    """
    HTTP服务端 — 接收来自其他节点的消息

    提供REST API：
    - POST /message — 接收消息
    - GET /messages/{node_id} — 拉取消息
    - POST /heartbeat — 心跳
    """

    def __init__(self, port: int = 8080):
        self.port = port
        self._app = None
        self._runner = None

    def create_app(self) -> 'Flask':
        """创建Flask应用"""
        try:
            from flask import Flask, request, jsonify
        except ImportError:
            logger.warning("Flask未安装，无法创建HTTP服务")
            return None

        app = Flask(__name__)

        @app.route('/message', methods=['POST'])
        def receive_message():
            """接收消息"""
            data = request.json
            msg = self._deserialize_message(data)
            if msg and self._on_message:
                self._on_message(msg)
            return jsonify({"status": "ok"})

        @app.route('/messages/<node_id>', methods=['GET'])
        def get_messages(node_id):
            """拉取消息"""
            messages = self._get_node_messages(node_id)
            return jsonify({"messages": messages})

        @app.route('/heartbeat', methods=['POST'])
        def heartbeat():
            """接收心跳"""
            data = request.json
            if self._on_heartbeat:
                self._on_heartbeat(data)
            return jsonify({"status": "ok"})

        @app.route('/health', methods=['GET'])
        def health():
            return jsonify({"status": "healthy"})

        self._app = app
        return app

    def start(self, on_message=None, on_heartbeat=None):
        """启动HTTP服务"""
        if not self._app:
            self.create_app()

        self._on_message = on_message
        self._on_heartbeat = on_heartbeat

        # 消息队列
        self._message_queues: Dict[str, List] = {}

        try:
            from werkzeug.serving import make_server
            self._server = make_server('0.0.0.0', self.port, self._app)


方法 HttpServer.receive_message():
            """接收消息"""
            data = request.json
            msg = self._deserialize_message(

def receive_message(self):
            """接收消息"""
            data = request.json
            msg = self._deserialize_message(data)
            if msg and self._on_message:
                self._on_message(msg)
            return jsonify({"status": "ok"})

        @app.route('/messages/<node_id>', methods=['GET'])
        def get_messages(node_id):
            """拉取消息"""
            messages = self._get_node_messages(node_id)
            return jsonify({"messages": messages})

        @app.route('/heartbeat', methods=['POST'])
        def heartbeat():
            """接收心跳"""
            data = request.json
            if self._on_heartbeat:
                self._on_heartbeat(data)
            return jsonify({"status": "ok"})

        @app.route('/health', methods=['GET'])
        def health():
            return jsonify({"status": "healthy"})

        self._app = app
        return app


方法 HttpServer.get_messages():
            """拉取消息"""
            messages = self._get_node_messages(node_id)
            return j

def get_messages(self):
            """拉取消息"""
            messages = self._get_node_messages(node_id)
            return jsonify({"messages": messages})

        @app.route('/heartbeat', methods=['POST'])
        def heartbeat():
            """接收心跳"""
            data = request.json
            if self._on_heartbeat:
                self._on_heartbeat(data)
            return jsonify({"status": "ok"})

        @app.route('/health', methods=['GET'])
        def health():
            return jsonify({"status": "healthy"})

        self._app = app
        return app


heartbeat

方法 HttpServer.heartbeat():
            """接收心跳"""
            data = request.json
            if self._on_heartbeat:

def heartbeat(self):
            """接收心跳"""
            data = request.json
            if self._on_heartbeat:
                self._on_heartbeat(data)
            return jsonify({"status": "ok"})

        @app.route('/health', methods=['GET'])
        def health():
            return jsonify({"status": "healthy"})

        self._app = app
        return app


health

方法 HttpServer.health():
            return jsonify({"status": "healthy"})

        self._app = app
        return a

def health(self):
            return jsonify({"status": "healthy"})

        self._app = app
        return app


start

方法 HttpServer.start():
        """启动HTTP服务"""
        if not self._app:
            self.create_app()

        sel

def start(self):
        """启动HTTP服务"""
        if not self._app:
            self.create_app()

        self._on_message = on_message
        self._on_heartbeat = on_heartbeat

        # 消息队列
        self._message_queues: Dict[str, List] = {}

        try:
            from werkzeug.serving import make_server
            self._server = make_server('0.0.0.0', self.port, self._app)
            self._server.serve_forever()
        except Exception as e:
            logger.error(f"HTTP服务启动失败: {e}")


方法 HttpServer.start_background():
        """后台启动HTTP服务"""
        import threading
        self._on_message = on_message
        sel

def start_background(self):
        """后台启动HTTP服务"""
        import threading
        self._on_message = on_message
        self._on_heartbeat = on_heartbeat

        if not self._app:
            self.create_app()

        thread = threading.Thread(target=self.start, daemon=True)
        thread.start()

        logger.info(f"HTTP服务后台启动: 0.0.0.0:{self.port}")


方法 HttpServer.queue_message():
        """将消息放入队列"""
        if msg.receiver not in self._message_queues:
            self._messag

def queue_message(self):
        """将消息放入队列"""
        if msg.receiver not in self._message_queues:
            self._message_queues[msg.receiver] = []

        queue = self._message_queues[msg.receiver]
        queue.append({
            "msg_id": msg.msg_id,
            "sender": msg.sender,
            "receiver": msg.receiver,
            "msg_type": msg.msg_type,
            "payload": msg.payload,
            "timestamp": msg.timestamp.isoformat(),
            "ttl": msg.ttl,
        })

        # 限制队列长度
        if len(queue) > 100:
            self._message_queues[msg.receiver] = queue[-100:]


discovery.py

文件 core/aggregation_protocol/discovery.py: 虫群节点发现服务
- 中心化节点注册
- 节点健康状态追踪
- 自动故障检测 | 定义: class
class, class NodeRegistry, def __init__, def register, def unregister, def update_heartbeat, def get_alive_nodes, def get_all_nodes, def get_node_url, def check_node_health

asyncio logging threading time dataclasses datetime typing .types

#!/usr/bin/env python3
"""
虫群节点发现服务
- 中心化节点注册
- 节点健康状态追踪
- 自动故障检测
"""

import asyncio
import logging
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Set

from .types import NodeInfo, NodeRole

logger = logging.getLogger(__name__)

@dataclass
class NodeRegistration:
    """节点注册信息"""
    node_info: NodeInfo
    registered_at: datetime = field(default_factory=datetime.now)
    last_heartbeat: da


NodeRegistration

类 NodeRegistration 在 core/aggregation_protocol/discovery.py: 节点注册信息 | 方法:

class NodeRegistration:
    """节点注册信息"""
    node_info: NodeInfo
    registered_at: datetime = field(default_factory=datetime.now)
    last_heartbeat: datetime = field(default_factory=datetime.now)
    health_score: float = 1.0  # 0-1, 健康度
    consecutive_failures: int = 0
    url: str = ""  # HTTP访问地址


NodeRegistry

类 NodeRegistry 在 core/aggregation_protocol/discovery.py: 节点注册中心

    功能：
    - 节点注册/注销
    - 节点发现
    - 心跳更新
    - 健康检测 | 方法: __init__, register, unregister, update_heartbeat, get_alive_nodes, get_all_nodes, get_node_url, check_node_health, get_stats, start_health_check, stop_health_check, _health_check_loop, _perform_health_check

class NodeRegistry:
    """
    节点注册中心

    功能：
    - 节点注册/注销
    - 节点发现
    - 心跳更新
    - 健康检测
    """

    def __init__(self, self_node_id: str = ""):
        self.self_node_id = self_node_id
        self._nodes: Dict[str, NodeRegistration] = {}
        self._lock = threading.RLock()

        # 配置
        self.heartbeat_timeout = 60  # 秒，超时判定离线
        self.health_check_interval = 30  # 秒，健康检测间隔
        self._running = False
        self._health_thread: Optional[threading.Thread] = None

    def register(self, node_info: NodeInfo, url: str = "") -> bool:
        """注册节点"""
        with self._lock:
            existing = self._nodes.get(node_info.node_id)
            if existing:
                # 更新已存在节点
                existing.last_heartbeat = datetime.now()
                existing.url = url or existing.url
                existing.consecutive_failures = 0
                logger.info(f"节点更新注册: {node_info.node_id} @ {url}")
            else:
                # 新节点注册
                self._nodes[node_info.node_id] = NodeRegistration(
                    node_info=node_info,
                    url=url,
                )
                logger.info(f"节点注册: {node_info.node_id} ({node_info.role.value}) @ {url}")
            return True

    def unregister(self, node_id: str) -> bool:
        """注销节点"""
        with self._lock:
            if node_id in self._nodes:
                del self._nodes[node_id]
                logger.info(f"节点注销: {node_id}")
                return True
            return False

    def update_heartbeat(self, node_id: str) -> bool:
        """更新节点心跳"""
        with self._lock:
            node = self._nodes.get(node_id)
            if node:
                node.last_heartbeat = datetime.now()
                node.consecutive_failures = 0
                node.health_score = min(1.0, node.health_score + 0.1)
                return True
            return False

    def get_alive_nodes(self, role: NodeRole = None) -> List[NodeInfo]:


方法 NodeRegistry.start_health_check():
        """启动健康检测"""
        if self._running:
            return
        self._running = True

def start_health_check(self):
        """启动健康检测"""
        if self._running:
            return
        self._running = True
        self._health_thread = threading.Thread(target=self._health_check_loop, daemon=True)
        self._health_thread.start()
        logger.info("节点健康检测已启动")


方法 NodeRegistry.stop_health_check():
        """停止健康检测"""
        self._running = False
        if self._health_thread:
            self

def stop_health_check(self):
        """停止健康检测"""
        self._running = False
        if self._health_thread:
            self._health_thread.join(timeout=5)
        logger.info("节点健康检测已停止")


PeerDiscovery

类 PeerDiscovery 在 core/aggregation_protocol/discovery.py: 节点发现客户端

    功能：
    - 注册到中心节点
    - 定时同步节点列表
    - 广播自身存在 | 方法: __init__, add_known_peer, start_discovery, stop_discovery, _discovery_loop, _discover_peers

class PeerDiscovery:
    """
    节点发现客户端

    功能：
    - 注册到中心节点
    - 定时同步节点列表
    - 广播自身存在
    """

    def __init__(self, registry: NodeRegistry, http_port: int = 8080):
        self.registry = registry
        self.http_port = http_port
        self._running = False
        self._discovery_thread: Optional[threading.Thread] = None
        self._known_peers: Set[str] = set()  # 已知的对等节点地址

    def add_known_peer(self, peer_url: str):
        """添加已知对等节点"""
        if peer_url and peer_url not in self._known_peers:
            self._known_peers.add(peer_url)
            logger.info(f"添加对等节点: {peer_url}")

    def start_discovery(self, self_url: str = ""):
        """启动节点发现"""
        if self._running:
            return
        self._running = True

        # 注册自身
        from .types import NodeInfo, NodeRole
        self_node = NodeInfo(
            node_id=self.registry.self_node_id or "unknown",
            role=NodeRole.WORKER,
            capabilities=[],
            status="online",
        )
        self.registry.register(self_node, self_url)

        # 启动发现线程
        self._discovery_thread = threading.Thread(
            target=self._discovery_loop,
            daemon=True
        )
        self._discovery_thread.start()

        # 启动健康检测
        self.registry.start_health_check()

        logger.info(f"节点发现已启动: {self_url}")

    def stop_discovery(self):
        """停止节点发现"""
        self._running = False
        self.registry.stop_health_check()
        if self._discovery_thread:
            self._discovery_thread.join(timeout=5)
        logger.info("节点发现已停止")

    def _discovery_loop(self):
        """发现循环"""
        while self._running:
            try:
                self._discover_peers()
            except Exception as e:
                logger.debug(f"节点发现异常: {e}")
            time.sleep(30)  # 30秒发现一次

    def _discover_peers(self):
        """发现对等节点"""
        import requests

        for peer_url in


方法 PeerDiscovery.add_known_peer():
        """添加已知对等节点"""
        if peer_url and peer_url not in self._known_peers:
            self.

def add_known_peer(self):
        """添加已知对等节点"""
        if peer_url and peer_url not in self._known_peers:
            self._known_peers.add(peer_url)
            logger.info(f"添加对等节点: {peer_url}")


方法 PeerDiscovery.start_discovery():
        """启动节点发现"""
        if self._running:
            return
        self._running = True

def start_discovery(self):
        """启动节点发现"""
        if self._running:
            return
        self._running = True

        # 注册自身
        from .types import NodeInfo, NodeRole
        self_node = NodeInfo(
            node_id=self.registry.self_node_id or "unknown",
            role=NodeRole.WORKER,
            capabilities=[],
            status="online",
        )
        self.registry.register(self_node, self_url)

        # 启动发现线程
        self._discovery_thread = threading.Thread(
            target=self._discovery_loop,
            daemon=True
        )
        self._discovery_thread.start()

        # 启动健康检测
        self.registry.start_health_check()

        logger.info(f"节点发现已启动: {self_url}")


方法 PeerDiscovery.stop_discovery():
        """停止节点发现"""
        self._running = False
        self.registry.stop_health_check()

def stop_discovery(self):
        """停止节点发现"""
        self._running = False
        self.registry.stop_health_check()
        if self._discovery_thread:
            self._discovery_thread.join(timeout=5)
        logger.info("节点发现已停止")


protocol.py

文件 core/aggregation_protocol/protocol.py: 虫群聚合协议 — 主入口

AggregationProtocol 是整个聚合协议的统一入口，整合：
- 节点发现(discovery)
- 通信层(transport)
- 任务调度(scheduler)
- 权限管理(permission)

使用方式：
    protocol = AggregationProtocol(
        node_id="queen_zhangming", | 定义: class AggregationProtocol, def __init__, def start, def stop, def add_remote_node, def add_local_node, def remove_node, def submit_task, def _setup_message_handlers, def _handle_discover

hashlib logging threading time datetime typing .types .discovery .transport .scheduler .permission

#!/usr/bin/env python3
"""
虫群聚合协议 — 主入口

AggregationProtocol 是整个聚合协议的统一入口，整合：
- 节点发现(discovery)
- 通信层(transport)
- 任务调度(scheduler)
- 权限管理(permission)

使用方式：
    protocol = AggregationProtocol(
        node_id="queen_zhangming",
        role=NodeRole.QUEEN,
        address="http://localhost:8080",
    )
    protocol.start()

    # 提交聚合任务
    result = protocol.submit_task("分析这段代码的性能瓶颈", ...)

    # 关闭
    protocol.stop()
"""

import hashlib
import logging
import threading
import time
from


AggregationProtocol

类 AggregationProtocol 在 core/aggregation_protocol/protocol.py: 虫群聚合协议 — 核心入口

    设计理念：
    - 像GPU集群一样，将分散的设备临时组合成服务器
    - 每个设备可同时参与多个临时服务器
    - 权限控制调用范围和数量
    - 任务完成自动解散，设备回归空闲池 | 方法: __init__, start, stop, add_remote_node, add_local_node, remove_node, submit_task, _setup_message_handlers, _handle_discover, _handle_join, _handle_leave, _handle_task_assign, _handle_task_result, _handle_heartbeat, _heartbeat_loop, _gen_id, get_status, discover_nodes

class AggregationProtocol:
    """
    虫群聚合协议 — 核心入口

    设计理念：
    - 像GPU集群一样，将分散的设备临时组合成服务器
    - 每个设备可同时参与多个临时服务器
    - 权限控制调用范围和数量
    - 任务完成自动解散，设备回归空闲池
    """

    def __init__(
        self,
        node_id: str,
        role: NodeRole = NodeRole.QUEEN,
        name: str = "",
        address: str = "",
        permission_level: PermissionLevel = PermissionLevel.QUEEN,
        capabilities: List[str] = None,
        compute_score: float = 1.0,
        max_concurrent: int = 3,
        heartbeat_timeout: float = 30.0,
    ):
        # 自身节点信息
        self.node_info = NodeInfo(
            node_id=node_id,
            name=name or node_id,
            role=role,
            status=NodeStatus.ONLINE,
            address=address,
            capability=NodeCapability(
                specializations=capabilities or ["general"],
                compute_score=compute_score,
                max_concurrent=max_concurrent,
            ),
            permission_level=permission_level,
        )

        # 核心组件
        self.registry = NodeRegistry(node_id, heartbeat_timeout)
        self.bus = MessageBus(self.node_info)
        self.scheduler = TaskForceManager(self.registry, self.bus)
        self.permission = PermissionManager(permission_level)

        # 本地传输（同一进程内通信）
        self._local_transport = LocalTransport()

        # 运行状态
        self._running = False
        self._heartbeat_thread = None

        # 消息处理
        self._setup_message_handlers()

        # 统计
        self._stats = {
            "start_time": None,
            "tasks_submitted": 0,
            "tasks_completed": 0,
            "messages_sent": 0,
        }

    # ============================================================
    # 生命周期
    # ============================================================

    def start(self):
        """启动聚合协议"""
        if self._running:
            return

        self._running = True
        self.node_info.status = NodeStatus.ONLINE


start

方法 AggregationProtocol.start():
        """启动聚合协议"""
        if self._running:
            return

        self._running =

def start(self):
        """启动聚合协议"""
        if self._running:
            return

        self._running = True
        self.node_info.status = NodeStatus.ONLINE

        # 注册自身
        self.registry.register(self.node_info)
        self.bus.register_node_address(self.node_info.node_id, self.node_info.address)
        self._local_transport.register_bus(self.node_info.node_id, self.bus)
        self.permission.set_node_permission(self.node_info.node_id, self.node_info.permission_level)

        # 启动消息总线
        self.bus.start()

        # 启动心跳线程
        self._heartbeat_thread = threading.Thread(
            target=self._heartbeat_loop, daemon=True
        )
        self._heartbeat_thread.start()

        self._stats["start_time"] = datetime.now().isoformat()
        logger.info(f"聚合协议启动: {self.node_info.node_id} ({self.node_info.role.value})")


stop

方法 AggregationProtocol.stop():
        """停止聚合协议"""
        self._running = False
        self.node_info.status = NodeStatus.OFFLI