函数 get_pipeline() 在 deploy/windows/swarm/web_interface.py: <!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>虫群智能体 v7.1</title>
    <style>
        * { m

def get_pipeline():
    global pipeline
    if pipeline is None:
        pipeline = create_default_pipeline()
    return pipeline

# ============ HTML模板 ============

HTML_INDEX = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>虫群智能体 v7.1</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, "Microsoft YaHei", sans-serif; background: #0a0a0a; color: #e0e0e0; height: 100vh; display: flex; flex-direction: column; }

        /* 顶栏 */
        .header { background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); padding: 12px 24px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #333; }
        .header h1 { font-size: 18px; color: #00d4ff; }
        .header .status { font-size: 12px; color: #888; }
        .header .status .dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: #00ff88; margin-right: 4px; }

        /* 主体 */
        .main { flex: 1; display: flex; overflow: hidden; }

        /* 侧栏 */
        .sidebar { width: 260px; background: #111; border-right: 1px solid #222; padding: 16px; overflow-y: auto; }
        .sidebar h3 { color: #00d4ff; font-size: 13px; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px; }
        .sidebar .info-item { padding: 6px 0; font-size: 12px; color: #999; border-bottom: 1px solid #1a1a1a; }
        .sidebar .info-item span { color: #00ff88; float: right; }

        /* 聊天区 */
        .chat-area { flex: 1; display: flex; flex-direction: column; }
        .messages { flex: 1; overflow-y: auto; padding: 20px; }
        .msg { margin-bottom: 16px; display: flex; }
        .msg.user { justify-content: flex-end; }
        .msg .bubble { max-width: 70%; padding: 10px 16px; border-radius: 12px; font-size: 14px; line-height: 1.6; }
        .msg.user .bubble { background: #16213e; color:


index

函数 index() 在 deploy/windows/swarm/web_interface.py:

def index():
    return render_template_string(HTML_INDEX)

@app.route("/api/status")


函数 api_status() 在 deploy/windows/swarm/web_interface.py: 系统状态

def api_status():
    """系统状态"""
    try:
        registry = get_registry()
        # 确保默认模型已初始化
        if not registry.list_models():
            from core.model_registry import init_default_models
            init_default_models()
        models = registry.list_models()
        local_count = sum(1 for m in models if m.model_type == ModelType.LOCAL)
        api_count = sum(1 for m in models if m.model_type == ModelType.API)
        from core.memory_core import MemoryCore
        mem = MemoryCore()
        mem_stats = mem.get_stats()
        return jsonify({
            "model_count": len(models),
            "local_count": local_count,
            "api_count": api_count,
            "mem_count": mem_stats.get("total_memories", 0),
            "status": "running",
        })
    except Exception as e:
        return jsonify({"error": str(e), "status": "error"})

@app.route("/api/chat", methods=["POST"])


函数 api_chat() 在 deploy/windows/swarm/web_interface.py: 对话接口

def api_chat():
    """对话接口"""
    data = request.json or {}
    message = data.get("message", "").strip()
    if not message:
        return jsonify({"response": "请输入消息", "analysis": None})

    # 1. 技能管线分析
    pipeline = get_pipeline()
    skill_results = pipeline.execute(message)
    analysis = {}
    for name, output in skill_results.items():
        if output.success and output.result:
            analysis[name] = output.result

    # 2. MOA处理
    try:
        a = get_agent()
        result = a.chat_detailed(message)
        response = result.final_response
        analysis["model"] = result.primary_model
    except Exception as e:
        response = f"处理异常: {str(e)}"
        analysis["model"] = "error"

    return jsonify({
        "response": response,
        "analysis": analysis,
    })

@app.route("/api/chat/stream", methods=["POST"])


函数 api_chat_stream() 在 deploy/windows/swarm/web_interface.py: 流式对话接口（SSE）

def api_chat_stream():
    """流式对话接口（SSE）"""
    data = request.json or {}
    message = data.get("message", "").strip()
    if not message:
        def empty():
            yield f"data: {json.dumps({'chunk': '请输入消息', 'done': True})}\n\n"
        return Response(empty(), mimetype="text/event-stream")

    a = get_agent()

    def generate():
        for chunk, meta in a.engine.process_stream(message):
            payload = {
                "chunk": chunk,
                "model": meta.get("model", ""),
                "done": meta.get("done", False),
            }
            yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"

    return Response(generate(), mimetype="text/event-stream")

@app.route("/api/skills", methods=["POST"])


仅技能分析（不调用模型）

函数 api_skills() 在 deploy/windows/swarm/web_interface.py: 仅技能分析（不调用模型）

def api_skills():
    """仅技能分析（不调用模型）"""
    data = request.json or {}
    message = data.get("message", "").strip()
    if not message:
        return jsonify({"error": "空消息"})

    pipeline = get_pipeline()
    results = pipeline.execute(message)
    return jsonify({
        name: {"success": o.success, "result": o.result, "confidence": o.confidence}
        for name, o in results.items()
    })

@app.route("/api/perf")


函数 api_perf() 在 deploy/windows/swarm/web_interface.py: 性能报告

def api_perf():
    """性能报告"""
    from core.performance_monitor import get_monitor
    monitor = get_monitor()
    return jsonify(monitor.get_report())

@app.route("/api/health")


函数 api_health() 在 deploy/windows/swarm/web_interface.py: 模型健康状态

def api_health():
    """模型健康状态"""
    from core.health_checker import get_health_checker
    checker = get_health_checker()
    return jsonify(checker.get_report())

@app.route("/api/cache")


函数 api_cache() 在 deploy/windows/swarm/web_interface.py: 缓存统计

def api_cache():
    """缓存统计"""
    from core.smart_cache import get_cache
    cache = get_cache()
    return jsonify({
        "stats": cache.get_stats(),
        "top_entries": cache.get_top_entries(10),
    })

@app.route("/api/models/local")


函数 api_local_models() 在 deploy/windows/swarm/web_interface.py: 本地推理模型列表和状态

def api_local_models():
    """本地推理模型列表和状态"""
    from core.local_inference import get_local_backend
    backend = get_local_backend()
    status = backend.get_status()
    models_info = {}
    for model_id in status["available_models"]:
        info = backend.get_model_info(model_id)
        models_info[model_id] = info or {}
    return jsonify({
        "available": status["available_models"],
        "loaded": status["loaded_models"],
        "max_loaded": status["max_loaded"],
        "device": status["device"],
        "details": models_info,
    })

@app.route("/api/models/local/<model_id>/infer", methods=["POST"])


函数 api_local_infer(model_id) 在 deploy/windows/swarm/web_interface.py: 本地模型推理

def api_local_infer(model_id):
    """本地模型推理"""
    from core.local_inference import get_local_backend
    backend = get_local_backend()
    data = request.json or {}
    query = data.get("query", "")
    max_tokens = data.get("max_tokens", 128)
    temperature = data.get("temperature", 0.7)

    if not query:
        return jsonify({"error": "缺少query参数"}), 400

    result = backend.infer(model_id, query, max_new_tokens=max_tokens, temperature=temperature)
    return jsonify(result)

# ============ 入口 ============

if __name__ == "__main__":
    print("🐝 虫群智能体 v3.0 Web界面启动中...")
    print("   访问: http://localhost:5000")
    app.run(host="0.0.0.0", port=5000, debug=False)


文件 deploy/windows/swarm/network/__init__.py: 虫群智能体系统 — 网络模块 | 定义:

#!/usr/bin/env python3
"""
虫群智能体系统 — 网络模块
"""

from network.swarm_network import SwarmNode, SwarmNetwork


文件 deploy/windows/swarm/network/swarm_network.py: 虫群智能体系统 — 网络协议层
P2P通信协议 + 联邦学习协调 + 节点发现 | 定义: class SwarmNode, def __init__, def to_dict, class SwarmNetwork, def __init__, def register_peer, def unregister_peer, def discover_nodes, def heartbeat, def create_message

hashlib json logging time uuid typing datetime

#!/usr/bin/env python3
"""
虫群智能体系统 — 网络协议层
P2P通信协议 + 联邦学习协调 + 节点发现
"""

import hashlib
import json
import logging
import time
import uuid
from typing import Dict, List, Optional
from datetime import datetime

logger = logging.getLogger(__name__)

class SwarmNode:
    """虫群节点 — 表示网络中的一个智能体实例"""

    def __init__(self, node_id: str = None, host: str = "localhost",
                 port: int = 8765, capabilities: List[str] = None):
        self.node_id = node_id or str(uuid.uuid4())[:12]
        s


SwarmNode

虫群节点 — 表示网络中的一个智能体实例

类 SwarmNode 在 deploy/windows/swarm/network/swarm_network.py: 虫群节点 — 表示网络中的一个智能体实例 | 方法: __init__, to_dict

class SwarmNode:
    """虫群节点 — 表示网络中的一个智能体实例"""

    def __init__(self, node_id: str = None, host: str = "localhost",
                 port: int = 8765, capabilities: List[str] = None):
        self.node_id = node_id or str(uuid.uuid4())[:12]
        self.host = host
        self.port = port
        self.capabilities = capabilities or ["chat", "memory"]
        self.status = "online"
        self.last_heartbeat = datetime.now()
        self.performance_score = 1.0

    def to_dict(self) -> Dict:
        return {
            "node_id": self.node_id,
            "host": self.host,
            "port": self.port,
            "capabilities": self.capabilities,
            "status": self.status,
            "last_heartbeat": self.last_heartbeat.isoformat(),
            "performance_score": self.performance_score,
        }


SwarmNetwork

虫群网络 — 管理节点发现、消息路由和联邦协调

类 SwarmNetwork 在 deploy/windows/swarm/network/swarm_network.py: 虫群网络 — 管理节点发现、消息路由和联邦协调 | 方法: __init__, register_peer, unregister_peer, discover_nodes, heartbeat, create_message, validate_message, register_handler, handle_message, start_federation_round, get_federation_state, get_network_status, _checksum

class SwarmNetwork:
    """虫群网络 — 管理节点发现、消息路由和联邦协调"""

    def __init__(self, local_node: SwarmNode = None):
        self.local_node = local_node or SwarmNode()
        self.peers: Dict[str, SwarmNode] = {}
        self.message_handlers = {}
        self._federation_state = {
            "round": 0,
            "participants": [],
            "aggregation_pending": False,
        }
        logger.info(f"虫群网络初始化: 节点={self.local_node.node_id}")

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

    def register_peer(self, node: SwarmNode):
        """注册对等节点"""
        self.peers[node.node_id] = node
        logger.info(f"注册对等节点: {node.node_id}@{node.host}:{node.port}")

    def unregister_peer(self, node_id: str):
        """注销对等节点"""
        self.peers.pop(node_id, None)

    def discover_nodes(self, capability: str = None) -> List[SwarmNode]:
        """发现具有特定能力的节点"""
        nodes = [self.local_node] + list(self.peers.values())
        if capability:
            nodes = [n for n in nodes if capability in n.capabilities]
        return [n for n in nodes if n.status == "online"]

    def heartbeat(self):
        """发送心跳"""
        self.local_node.last_heartbeat = datetime.now()
        # 清理超时节点（超过60秒无心跳）
        now = datetime.now()
        timeout = 60
        expired = [
            nid for nid, n in self.peers.items()
            if (now - n.last_heartbeat).total_seconds() > timeout
        ]
        for nid in expired:
            self.peers[nid].status = "offline"
            logger.warning(f"节点超时: {nid}")

    # ============================================================
    # 消息协议
    # ============================================================

    def create_message(self, msg_type: str, payload: Dict,
                       target: str = None) -> Dict:
        """创建标准化的虫群消息"""
        msg = {
            "protocol": "swarm-v2",
            "version": "2.0",
            "msg_id":


方法 SwarmNetwork.register_peer():
        """注册对等节点"""
        self.peers[node.node_id] = node
        logger.info(f"注册对等节点: {node.no

def register_peer(self):
        """注册对等节点"""
        self.peers[node.node_id] = node
        logger.info(f"注册对等节点: {node.node_id}@{node.host}:{node.port}")


方法 SwarmNetwork.unregister_peer():
        """注销对等节点"""
        self.peers.pop(node_id, None)

def unregister_peer(self):
        """注销对等节点"""
        self.peers.pop(node_id, None)


heartbeat

方法 SwarmNetwork.heartbeat():
        """发送心跳"""
        self.local_node.last_heartbeat = datetime.now()
        # 清理超时节点（超过60秒无心

def heartbeat(self):
        """发送心跳"""
        self.local_node.last_heartbeat = datetime.now()
        # 清理超时节点（超过60秒无心跳）
        now = datetime.now()
        timeout = 60
        expired = [
            nid for nid, n in self.peers.items()
            if (now - n.last_heartbeat).total_seconds() > timeout
        ]
        for nid in expired:
            self.peers[nid].status = "offline"
            logger.warning(f"节点超时: {nid}")

    # ============================================================
    # 消息协议
    # ============================================================


方法 SwarmNetwork.register_handler():
        """注册消息处理器"""
        self.message_handlers[msg_type] = handler

def register_handler(self):
        """注册消息处理器"""
        self.message_handlers[msg_type] = handler


方法 SwarmNetwork.handle_message():
        """处理收到的消息"""
        if not self.validate_message(msg):
            logger.warning(f"消息验证失

def handle_message(self):
        """处理收到的消息"""
        if not self.validate_message(msg):
            logger.warning(f"消息验证失败: {msg.get('msg_id')}")
            return

        msg_type = msg.get("msg_type")
        handler = self.message_handlers.get(msg_type)
        if handler:
            handler(msg)
        else:
            logger.warning(f"无处理器: {msg_type}")

    # ============================================================
    # 联邦学习协调
    # ============================================================


文件 deploy/windows/swarm/core/memory_core.py: 虫群智能体系统 — 统一记忆核心
合并 enhanced_memory_core / v2 / simple_memory_core 三者功能
SQLite存储 + 重要性评分 + 自动分类 + 过期清理 | 定义: class MemoryCore, def __new__, def _init_db, def _init_categories, def _start_cleanup_thread, def store, def retrieve, def get_relevant_context, def get_stats, def cleanup_expired

hashlib json logging os re sqlite3 threading time collections datetime typing core.types

#!/usr/bin/env python3
"""
虫群智能体系统 — 统一记忆核心
合并 enhanced_memory_core / v2 / simple_memory_core 三者功能
SQLite存储 + 重要性评分 + 自动分类 + 过期清理
"""

import hashlib
import json
import logging
import os
import re
import sqlite3
import threading
import time
from collections import Counter
from datetime import datetime, timedelta
from typing import Dict, List, Optional

from core.types import MemoryCategory, MemoryRecord

logger = logging.getLogger(__name__)

# 默认数据库路径
DEFAULT_DB_PATH = "/home/admin/swarm/data/me


MemoryCore

类 MemoryCore 在 deploy/windows/swarm/core/memory_core.py: 统一记忆核心 — 单例 | 方法: __new__, _init_db, _init_categories, _start_cleanup_thread, store, retrieve, get_relevant_context, get_stats, cleanup_expired, _detect_category, _calc_importance, _generate_tags, _default_retention, _increment_access, _cleanup_worker

class MemoryCore:
    """统一记忆核心 — 单例"""

    _instance = None

    def __new__(cls, db_path: str = DEFAULT_DB_PATH):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._db_path = db_path
            cls._instance._lock = threading.Lock()
            cls._instance._init_db()
            cls._instance._init_categories()
            # 启动后台清理
            cls._instance._start_cleanup_thread()
        return cls._instance

    # ============================================================
    # 初始化
    # ============================================================

    def _init_db(self):
        """初始化数据库表和索引"""
        # :memory: 模式不需要创建目录
        db_dir = os.path.dirname(self._db_path)
        if db_dir:
            os.makedirs(db_dir, exist_ok=True)
        conn = sqlite3.connect(self._db_path)
        c = conn.cursor()
        c.execute("""
            CREATE TABLE IF NOT EXISTS memories (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                memory_id TEXT UNIQUE,
                user_id TEXT,
                conversation_id TEXT,
                title TEXT,
                user_message TEXT,
                ai_response TEXT,
                category TEXT DEFAULT 'general',
                importance REAL DEFAULT 0.5,
                priority INTEGER DEFAULT 1,
                access_count INTEGER DEFAULT 0,
                tags TEXT,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                last_accessed DATETIME,
                expires_at DATETIME
            )
        """)
        for idx in ["idx_user", "idx_category", "idx_importance", "idx_expires"]:
            try:
                c.execute(f"CREATE INDEX IF NOT EXISTS {idx} ON memories({idx.replace('idx_', '')})")
            except Exception:
                pass
        conn.commit()
        conn.close()

    def _init_categories(self):
        """初始化分类关键词映射"""
        self._category_keywords = {
            MemoryCategory.GREE


文件 deploy/windows/swarm/core/health_checker.py: 虫群智能体系统 — 模型健康检查与自动故障转移
监控模型可用性，失败时自动降级到备选模型 | 定义: class HealthStatus, def __init__, def record_success, def record_failure, def can_try, def get_status_summary, class ModelHealthChecker, def __new__, def initialize, def _update_failover_order

logging threading time collections typing datetime core.types core.model_registry

#!/usr/bin/env python3
"""
虫群智能体系统 — 模型健康检查与自动故障转移
监控模型可用性，失败时自动降级到备选模型
"""

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

from core.types import ModelStatus
from core.model_registry import ModelRegistry, get_registry

logger = logging.getLogger(__name__)

class HealthStatus:
    """单个模型的健康状态"""

    def __init__(self, model_id: str):
        self.model_id = model_id


HealthStatus

类 HealthStatus 在 deploy/windows/swarm/core/health_checker.py: 单个模型的健康状态 | 方法: __init__, record_success, record_failure, can_try, get_status_summary

class HealthStatus:
    """单个模型的健康状态"""

    def __init__(self, model_id: str):
        self.model_id = model_id
        self.is_healthy = True
        self.last_check_time = None
        self.last_success_time = None
        self.last_failure_time = None
        self.consecutive_failures = 0
        self.consecutive_successes = 0
        self.total_checks = 0
        self.total_failures = 0
        self.avg_latency_ms = 0.0
        self._latencies = []  # 最近10次延迟

        # 熔断器状态
        self.circuit_open = False  # 熔断器是否打开（打开=不再尝试）
        self.circuit_open_time = None  # 熔断器打开时间
        self.half_open_attempts = 0  # 半开状态尝试次数

    def record_success(self, latency_ms: float):
        """记录成功"""
        self.consecutive_failures = 0
        self.consecutive_successes += 1
        self.total_checks += 1
        self.last_success_time = datetime.now()
        self.last_check_time = datetime.now()
        self.is_healthy = True

        # 延迟记录
        self._latencies.append(latency_ms)
        if len(self._latencies) > 10:
            self._latencies.pop(0)
        self.avg_latency_ms = sum(self._latencies) / len(self._latencies)

        # 熔断器：连续3次成功后关闭
        if self.circuit_open and self.consecutive_successes >= 3:
            self.circuit_open = False
            self.circuit_open_time = None
            self.half_open_attempts = 0
            logger.info(f"模型 {self.model_id} 熔断器关闭，恢复服务")

    def record_failure(self):
        """记录失败"""
        self.consecutive_successes = 0
        self.consecutive_failures += 1
        self.total_checks += 1
        self.total_failures += 1
        self.last_failure_time = datetime.now()
        self.last_check_time = datetime.now()

        # 熔断器：连续5次失败后打开
        if self.consecutive_failures >= 5 and not self.circuit_open:
            self.circuit_open = True
            self.circuit_open_time = datetime.now()
            self.is_healthy = False
            logger.warning(f"模型 {self.model_id} 熔断器打开，停止尝试")

    def can_try(self) -> bool:


方法 HealthStatus.record_success():
        """记录成功"""
        self.consecutive_failures = 0
        self.consecutive_successes += 1

def record_success(self):
        """记录成功"""
        self.consecutive_failures = 0
        self.consecutive_successes += 1
        self.total_checks += 1
        self.last_success_time = datetime.now()
        self.last_check_time = datetime.now()
        self.is_healthy = True

        # 延迟记录
        self._latencies.append(latency_ms)
        if len(self._latencies) > 10:
            self._latencies.pop(0)
        self.avg_latency_ms = sum(self._latencies) / len(self._latencies)

        # 熔断器：连续3次成功后关闭
        if self.circuit_open and self.consecutive_successes >= 3:
            self.circuit_open = False
            self.circuit_open_time = None
            self.half_open_attempts = 0
            logger.info(f"模型 {self.model_id} 熔断器关闭，恢复服务")


方法 HealthStatus.record_failure():
        """记录失败"""
        self.consecutive_successes = 0
        self.consecutive_failures += 1

def record_failure(self):
        """记录失败"""
        self.consecutive_successes = 0
        self.consecutive_failures += 1
        self.total_checks += 1
        self.total_failures += 1
        self.last_failure_time = datetime.now()
        self.last_check_time = datetime.now()

        # 熔断器：连续5次失败后打开
        if self.consecutive_failures >= 5 and not self.circuit_open:
            self.circuit_open = True
            self.circuit_open_time = datetime.now()
            self.is_healthy = False
            logger.warning(f"模型 {self.model_id} 熔断器打开，停止尝试")


ModelHealthChecker

模型健康检查器 — 单例

类 ModelHealthChecker 在 deploy/windows/swarm/core/health_checker.py: 模型健康检查器 — 单例 | 方法: __new__, initialize, _update_failover_order, record_success, record_failure, get_healthy_models, get_fallback, check_health, check_all, get_report, _get_api_key, _get_model_name

class ModelHealthChecker:
    """模型健康检查器 — 单例"""

    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)
                cls._instance._health = {}
                cls._instance._registry = None
                cls._instance._failover_order = []  # 故障转移顺序
                cls._instance._initialized = False
            return cls._instance

    def initialize(self, registry: ModelRegistry = None):
        """初始化健康检查器"""
        self._registry = registry or get_registry()
        # 初始化所有已注册模型的健康状态
        for model in self._registry.list_models():
            if model.model_id not in self._health:
                self._health[model.model_id] = HealthStatus(model.model_id)
        # 默认故障转移顺序：API优先 → 本地兜底
        self._update_failover_order()
        self._initialized = True
        logger.info(f"健康检查器初始化: {len(self._health)}个模型")

    def _update_failover_order(self):
        """更新故障转移顺序：本地模型在最后兜底"""
        api_models = []
        local_models = []
        for mid, hs in self._health.items():
            model = self._registry.get(mid)
            if model and model.is_local:
                local_models.append(mid)
            else:
                api_models.append(mid)
        # API优先，本地兜底
        self._failover_order = api_models + local_models
        logger.info(f"故障转移顺序: {' → '.join(self._failover_order)}")

    # ----------------------------------------------------------
    # 健康状态记录
    # ----------------------------------------------------------

    def record_success(self, model_id: str, latency_ms: float):
        """记录模型调用成功"""
        if model_id not in self._health:
            self._health[model_id] = HealthStatus(model_id)
        self._health[model_id].record_success(latency_ms)

        # 如果从不可用恢复，更新注册表状态
        if self._health[model_id].is_healthy:
            model = self._registry.get(model_id)
            if model and model.status != Mode


initialize

方法 ModelHealthChecker.initialize():
        """初始化健康检查器"""
        self._registry = registry or get_registry()
        # 初始化所有已注册模型的健康状

def initialize(self):
        """初始化健康检查器"""
        self._registry = registry or get_registry()
        # 初始化所有已注册模型的健康状态
        for model in self._registry.list_models():
            if model.model_id not in self._health:
                self._health[model.model_id] = HealthStatus(model.model_id)
        # 默认故障转移顺序：API优先 → 本地兜底
        self._update_failover_order()
        self._initialized = True
        logger.info(f"健康检查器初始化: {len(self._health)}个模型")


方法 ModelHealthChecker.record_success():
        """记录模型调用成功"""
        if model_id not in self._health:
            self._health[model_id]

def record_success(self):
        """记录模型调用成功"""
        if model_id not in self._health:
            self._health[model_id] = HealthStatus(model_id)
        self._health[model_id].record_success(latency_ms)

        # 如果从不可用恢复，更新注册表状态
        if self._health[model_id].is_healthy:
            model = self._registry.get(model_id)
            if model and model.status != ModelStatus.ACTIVE:
                self._registry.set_status(model_id, ModelStatus.ACTIVE)


方法 ModelHealthChecker.record_failure():
        """记录模型调用失败"""
        if model_id not in self._health:
            self._health[model_id]

def record_failure(self):
        """记录模型调用失败"""
        if model_id not in self._health:
            self._health[model_id] = HealthStatus(model_id)
        self._health[model_id].record_failure()

        # 如果不健康，更新注册表状态
        hs = self._health[model_id]
        if not hs.is_healthy or hs.circuit_open:
            self._registry.set_status(model_id, ModelStatus.ERROR)

    # ----------------------------------------------------------
    # 故障转移
    # ----------------------------------------------------------


文件 deploy/windows/swarm/core/task_tree.py: 虫群v7 — 任务模型树(Task Tree)
知识树结构的按需加载任务模型群

设计思路（类比高中物理课程体系）:
- 高中物理 = 力学 + 电学 + 热学 + 光学 ...
- 力学 = 运动学 + 动力学 + 动量 + 能量 ...
- 每个知识点 = 一个任务模型(Drone)
- 上课时只加载当前章节的模型，用完卸载
- 这样内存中永远只有需要的模型在运行 | 定义: class TaskNode, def __init__, def to_dict, class TaskTree, def __init__, def _init_default_tree, def execute, def record_usage, def _ensure_loaded, def _evict_one

#!/usr/bin/env python3
"""
虫群v7 — 任务模型树(Task Tree)
知识树结构的按需加载任务模型群

设计思路（类比高中物理课程体系）:
- 高中物理 = 力学 + 电学 + 热学 + 光学 ...
- 力学 = 运动学 + 动力学 + 动量 + 能量 ...
- 每个知识点 = 一个任务模型(Drone)
- 上课时只加载当前章节的模型，用完卸载
- 这样内存中永远只有需要的模型在运行
"""

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

logger = logging.getLogger(__name__)

# ============================================================
# 任务节点 — 知识树的叶子/分支
# =======================================


TaskNode

类 TaskNode 在 deploy/windows/swarm/core/task_tree.py: 任务节点 — 知识树的一个节点

    可以是分支（如"力学"）或叶子（如"牛顿第二定律"）
    叶子节点关联一个具体的任务模型 | 方法: __init__, to_dict

class TaskNode:
    """
    任务节点 — 知识树的一个节点

    可以是分支（如"力学"）或叶子（如"牛顿第二定律"）
    叶子节点关联一个具体的任务模型
    """

    def __init__(self, node_id: str, name: str,
                 domain: str = "", parent_id: str = "",
                 is_leaf: bool = False, model_id: str = ""):
        self.node_id = node_id
        self.name = name
        self.domain = domain
        self.parent_id = parent_id
        self.is_leaf = is_leaf
        self.model_id = model_id        # 叶子节点关联的模型ID
        self.children: List[str] = []    # 子节点ID列表

        # 运行时状态
        self.loaded = False              # 是否已加载到内存
        self.use_count = 0               # 使用次数
        self.last_used: Optional[float] = None

    def to_dict(self) -> Dict:
        return {
            "node_id": self.node_id,
            "name": self.name,
            "domain": self.domain,
            "parent_id": self.parent_id,
            "is_leaf": self.is_leaf,
            "model_id": self.model_id,
            "children": self.children,
            "use_count": self.use_count,
            "loaded": self.loaded,
        }

# ============================================================
# 任务模型树核心
# ============================================================


TaskTree

类 TaskTree 在 deploy/windows/swarm/core/task_tree.py: 任务模型树 — 按需加载的知识树

    类比课程体系:
    - 根节点 = 用户的全部知识领域
    - 分支节点 = 领域分类（编程/物理/写作/日常...）
    - 叶子节点 = 具体任务模型（python基础/力学/邮件写作...）

    核心操作:
    1. execute(): 按TaskAnalysis路由到对应叶子节点执行
    2. reco | 方法: __init__, _init_default_tree, execute, record_usage, _ensure_loaded, _evict_one, unload_all, add_node, remove_node, get_tree, _load, save, get_status

class TaskTree:
    """
    任务模型树 — 按需加载的知识树

    类比课程体系:
    - 根节点 = 用户的全部知识领域
    - 分支节点 = 领域分类（编程/物理/写作/日常...）
    - 叶子节点 = 具体任务模型（python基础/力学/邮件写作...）

    核心操作:
    1. execute(): 按TaskAnalysis路由到对应叶子节点执行
    2. record_usage(): 记录使用情况，用于后续优化
    3. load/unload: 按需加载/卸载模型（内存管理）
    """

    DATA_DIR = "/home/admin/swarm/data/task_tree"
    MAX_LOADED = 3  # 同时最多加载的模型数

    def __init__(self, user_id: str = "default"):
        self.user_id = user_id
        self._nodes: Dict[str, TaskNode] = {}
        self._root_id = "root"
        self._loaded_models: Dict[str, float] = {}  # model_id -> load_time

        # 统计
        self._execute_count = 0
        self._hit_count = 0
        self._load_count = 0
        self._unload_count = 0

        # 初始化默认知识树
        self._init_default_tree()

        # 加载用户自定义树
        self._load()

    # ============================================================
    # 默认知识树
    # ============================================================

    def _init_default_tree(self):
        """初始化默认的任务模型知识树"""
        # 根节点
        root = TaskNode("root", "全部领域")
        self._nodes["root"] = root

        # 一级领域
        domains = {
            "coding": ("编程", ["python", "web", "algorithm", "database"]),
            "science": ("科学", ["physics", "math", "chemistry"]),
            "writing": ("写作", ["email", "report", "creative"]),
            "daily": ("日常", ["chat", "translate", "search"]),
            "work": ("工作", ["office", "project", "meeting"]),
        }

        for domain_id, (domain_name, leaf_names) in domains.items():
            # 创建领域分支
            domain_node = TaskNode(
                domain_id, domain_name,
                domain=domain_name, parent_id="root"
            )
            self._nodes[domain_id] = domain_node
            root.children.append(domain_id)

            # 创建叶子节点
            for leaf_name in leaf_names:
                leaf_id = f"{domain_id}


方法 TaskTree.record_usage():
        """记录使用情况，用于知识树优化"""
        intent = getattr(analysis, 'intent', 'chat')
        domains =

def record_usage(self):
        """记录使用情况，用于知识树优化"""
        intent = getattr(analysis, 'intent', 'chat')
        domains = getattr(analysis, 'knowledge_domains', [])
        route = getattr(analysis, 'route', '')

        # 记录到对应节点
        for domain in domains:
            domain_name_map = {
                "物理": "science", "编程": "coding", "数学": "science",
                "写作": "writing", "日常": "daily",
            }
            domain_id = domain_name_map.get(domain)
            if domain_id and domain_id in self._nodes:
                self._nodes[domain_id].use_count += 1
                self._nodes[domain_id].last_used = time.time()

    # ============================================================
    # 动态加载管理
    # ============================================================


方法 TaskTree.unload_all():
        """卸载所有模型"""
        self._loaded_models.clear()
        for node in self._nodes.values():


save

方法 TaskTree.save():
        """保存知识树"""
        os.makedirs(self.DATA_DIR, exist_ok=True)
        filepath = os.path.jo

def save(self):
        """保存知识树"""
        os.makedirs(self.DATA_DIR, exist_ok=True)
        filepath = os.path.join(self.DATA_DIR, f"{self.user_id}.json")

        custom_nodes = []
        for node in self._nodes.values():
            if node.node_id == "root" or "." not in node.node_id:
                continue  # 跳过默认节点
            custom_nodes.append(node.to_dict())

        try:
            with open(filepath, "w", encoding="utf-8") as f:
                json.dump({"custom_nodes": custom_nodes}, f, ensure_ascii=False, indent=2)
        except Exception as e:
            logger.warning(f"任务树保存失败: {e}")

    # ============================================================
    # 状态查询
    # ============================================================


文件 deploy/windows/swarm/core/local_inference.py: 虫群本地推理后端
- 加载训练好的SwarmModel模型
- 提供统一的推理接口
- 支持多模型管理和切换
- 与MOA引擎集成 | 定义: class LocalModelBackend, def __init__, def _scan_models, def list_available, def get_model_info, def load, def unload, def infer, def get_status, def get_local_backend

os sys time json torch threading typing training.model training.tokenizer

#!/usr/bin/env python3
"""
虫群本地推理后端
- 加载训练好的SwarmModel模型
- 提供统一的推理接口
- 支持多模型管理和切换
- 与MOA引擎集成
"""

import os
import sys
import time
import json
import torch
import threading
from typing import Dict, List, Optional, Tuple

sys.path.insert(0, "/home/admin/swarm")

from training.model import SwarmModel
from training.tokenizer import SwarmTokenizer

class LocalModelBackend:
    """
    本地模型推理后端

    管理多个本地小模型的加载、推理和卸载。
    按需加载模型到内存，支持LRU淘汰。
    """

    def __init__(self, models_dir: str = "/ho


LocalModelBackend

类 LocalModelBackend 在 deploy/windows/swarm/core/local_inference.py: 本地模型推理后端

    管理多个本地小模型的加载、推理和卸载。
    按需加载模型到内存，支持LRU淘汰。 | 方法: __init__, _scan_models, list_available, get_model_info, load, unload, infer, get_status

class LocalModelBackend:
    """
    本地模型推理后端

    管理多个本地小模型的加载、推理和卸载。
    按需加载模型到内存，支持LRU淘汰。
    """

    def __init__(self, models_dir: str = "/home/admin/swarm/training/models", max_loaded: int = 3):
        self.models_dir = models_dir
        self.max_loaded = max_loaded

        # 已加载的模型: model_id -> (model, tokenizer)
        self._loaded: Dict[str, Tuple[SwarmModel, SwarmTokenizer]] = {}
        self._load_times: Dict[str, float] = {}  # LRU时间戳
        self._lock = threading.Lock()

        # 可用模型列表
        self._available = self._scan_models()

        # 设备
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    def _scan_models(self) -> Dict[str, dict]:
        """扫描可用模型"""
        available = {}
        if not os.path.exists(self.models_dir):
            return available

        # 共享分词器路径
        shared_tok = os.path.join(self.models_dir, "shared_tokenizer.json")
        # v2分词器
        v2_tok = os.path.join(self.models_dir, "tokenizer_v2.json")

        for name in os.listdir(self.models_dir):
            model_dir = os.path.join(self.models_dir, name)
            if not os.path.isdir(model_dir):
                continue
            model_path = os.path.join(model_dir, "model.pt")
            meta_path = os.path.join(model_dir, "meta.json")

            if os.path.exists(model_path):
                meta = {}
                if os.path.exists(meta_path):
                    with open(meta_path, "r") as f:
                        meta = json.load(f)
                # 优先用模型目录下的分词器，否则用共享分词器或v2分词器
                tok_path = os.path.join(model_dir, "tokenizer.json")
                if not os.path.exists(tok_path) and os.path.exists(shared_tok):
                    tok_path = shared_tok
                if not os.path.exists(tok_path) and os.path.exists(v2_tok):
                    tok_path = v2_tok
                # 检测量化模型
                quantized = os.path.exists(os.path.join(model_dir,


文件 deploy/windows/swarm/core/royal_agent.py: 虫群智能体系统 — 虫皇智能体
顶层协调器：接收用户输入 → MOA引擎处理 → 返回结果 | 定义: class RoyalAgent, def __init__, def chat, def chat_detailed, def get_status, def new_conversation, def create_royal_agent

#!/usr/bin/env python3
"""
虫群智能体系统 — 虫皇智能体
顶层协调器：接收用户输入 → MOA引擎处理 → 返回结果
"""

import logging
from datetime import datetime
from typing import Dict, Optional

from core.types import AggregationResult, AggregationMethod
from core.moa_engine import MOAEngine
from core.model_registry import get_registry, init_default_models
from core.memory_core import MemoryCore

logger = logging.getLogger(__name__)

class RoyalAgent:
    """虫皇智能体 — 系统的顶层入口"""

    def __init__(self):
        # 初始化模型注册表
        se


RoyalAgent

虫皇智能体 — 系统的顶层入口

类 RoyalAgent 在 deploy/windows/swarm/core/royal_agent.py: 虫皇智能体 — 系统的顶层入口 | 方法: __init__, chat, chat_detailed, get_status, new_conversation

class RoyalAgent:
    """虫皇智能体 — 系统的顶层入口"""

    def __init__(self):
        # 初始化模型注册表
        self.registry = get_registry()
        init_default_models()

        # 初始化MOA引擎
        self.moa = MOAEngine(self.registry)

        # 会话状态
        self.conversation_id = datetime.now().strftime("%Y%m%d_%H%M%S")
        self.user_id = "default"

        logger.info("虫皇智能体初始化完成")

    def chat(self, message: str, user_id: str = None,
             method: AggregationMethod = None) -> str:
        """
        与虫皇对话
        Args:
            message: 用户消息
            user_id: 用户ID
            method: 聚合策略（默认自动选择）
        Returns:
            最终响应文本
        """
        if user_id:
            self.user_id = user_id

        try:
            result = self.moa.process(
                query=message,
                user_id=self.user_id,
                conversation_id=self.conversation_id,
                method=method,
            )
            return result.final_response
        except Exception as e:
            logger.error(f"虫皇处理异常: {e}")
            return f"处理出错: {str(e)}"

    def chat_detailed(self, message: str, user_id: str = None,
                      method: AggregationMethod = None) -> AggregationResult:
        """与虫皇对话（返回详细结果）"""
        if user_id:
            self.user_id = user_id
        try:
            return self.moa.process(
                query=message,
                user_id=self.user_id,
                conversation_id=self.conversation_id,
                method=method,
            )
        except Exception as e:
            logger.error(f"虫皇处理异常: {e}")
            return AggregationResult(
                query=message,
                final_response=f"处理出错: {str(e)}",
                primary_model="error",
            )

    # ============================================================
    # 状态查询
    # ============================================================

    def get_status(self) -> Dict:
        """获取系统状态"""
        registry_report = self.registry.ge


文件 deploy/windows/swarm/core/__init__.py: 虫群智能体系统 v6 — 虫族生态体系

架构层级：
  虫皇(Overmind)  — 最高控制中心，管理整个虫群生态
  虫巢(Hive)      — 中央大模型集群，云端推理节点
  脑虫(Cerebrate) — 区域路由节点，协调虫后间的通信
  虫后(Queen)     — 个人模型系统，每个用户一套
  子虫(Drone)     — 功能型小模型，按需加载/卸载

通信流：
  | 定义:

#!/usr/bin/env python3
"""
虫群智能体系统 v6 — 虫族生态体系

架构层级：
  虫皇(Overmind)  — 最高控制中心，管理整个虫群生态
  虫巢(Hive)      — 中央大模型集群，云端推理节点
  脑虫(Cerebrate) — 区域路由节点，协调虫后间的通信
  虫后(Queen)     — 个人模型系统，每个用户一套
  子虫(Drone)     — 功能型小模型，按需加载/卸载

通信流：
  用户 → 虫后(元模型) → 脑虫(路由) → 子虫(执行) / 虫巢(大模型)
                                          ↓
                             其他虫后的子虫(跨用户协作)

命名灵感：星际争霸虫族(Zerg)生态体系
"""

from core.swarm_types import *

__version__ = "6.0.0"
__codename__ = "虫族生态"


aggregation.py

文件 deploy/windows/swarm/core/aggregation.py: 虫群智能体系统 — 聚合引擎
将多个模型的结果智能合并为最终响应 | 定义: class AggregationEngine, def __init__, def aggregate, def _by_confidence, def _by_weight, def _by_vote, def _by_sequential

#!/usr/bin/env python3
"""
虫群智能体系统 — 聚合引擎
将多个模型的结果智能合并为最终响应
"""

import logging
from typing import Dict, List
from datetime import datetime

from core.types import (
    AggregationMethod, AggregationResult, ModelResult, PerformanceStats
)

logger = logging.getLogger(__name__)

class AggregationEngine:
    """聚合引擎 — 合并多模型结果"""

    def __init__(self):
        self.method = AggregationMethod.CONFIDENCE

    def aggregate(self, query: str, results: List[ModelResult],
                  method: Agg


AggregationEngine

聚合引擎 — 合并多模型结果

类 AggregationEngine 在 deploy/windows/swarm/core/aggregation.py: 聚合引擎 — 合并多模型结果 | 方法: __init__, aggregate, _by_confidence, _by_weight, _by_vote, _by_sequential

class AggregationEngine:
    """聚合引擎 — 合并多模型结果"""

    def __init__(self):
        self.method = AggregationMethod.CONFIDENCE

    def aggregate(self, query: str, results: List[ModelResult],
                  method: AggregationMethod = None) -> AggregationResult:
        """
        聚合多个模型的结果
        Args:
            query: 原始查询
            results: 各模型的处理结果列表
            method: 聚合策略（默认置信度优先）
        Returns:
            AggregationResult
        """
        method = method or self.method
        start = datetime.now()

        # 过滤失败结果
        successful = [r for r in results if r.success and r.response]
        if not successful:
            # 全部失败，收集错误并给出友好提示
            errors = [r.error for r in results if r.error]
            err_msg = "; ".join(errors[:2]) if errors else "所有模型均未返回有效结果"
            return AggregationResult(
                query=query,
                final_response=f"抱歉，暂时无法处理您的请求。原因: {err_msg}",
                method=method,
                model_results=results,
            )

        # 按策略聚合
        if method == AggregationMethod.CONFIDENCE:
            resp, primary, primary_conf = self._by_confidence(successful)
        elif method == AggregationMethod.WEIGHTED:
            resp, primary, primary_conf = self._by_weight(successful)
        elif method == AggregationMethod.VOTE:
            resp, primary, primary_conf = self._by_vote(successful)
        else:  # SEQUENTIAL
            resp, primary, primary_conf = self._by_sequential(successful)

        total_ms = sum(r.latency_ms for r in successful)

        return AggregationResult(
            query=query,
            final_response=resp,
            method=method,
            primary_model=primary,
            primary_confidence=primary_conf,
            model_results=results,
            total_latency_ms=total_ms,
        )

    # ============================================================
    # 聚合策略
    # ============================================================

    def _by_confidence(self, resul


文件 deploy/windows/swarm/core/moa_engine.py: 虫群智能体系统 — MOA多模型聚合引擎
Mixtures of Agents: 路由 → 并行执行 → 聚合 | 定义: class MOAEngine, def __init__, def pipeline, def process, def _execute_models, def _exec_local, def _exec_local_inference, def _exec_api, def process_stream, def _stream_api

#!/usr/bin/env python3
"""
虫群智能体系统 — MOA多模型聚合引擎
Mixtures of Agents: 路由 → 并行执行 → 聚合
"""

import logging
import os
import time
import json
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Dict, List, Optional

import requests

from core.types import (
    ModelResult, AggregationResult, AggregationMethod,
    TaskContext, ComplexityLevel, ModelType
)
from core.model_registry import ModelRegistry, get_registry
from core.router import SwarmRouter
from core.aggregati


MOAEngine

MOA多模型聚合引擎 — 核心处理流水线

类 MOAEngine 在 deploy/windows/swarm/core/moa_engine.py: MOA多模型聚合引擎 — 核心处理流水线 | 方法: __init__, pipeline, process, _execute_models, _exec_local, _exec_local_inference, _exec_api, process_stream, _stream_api, _load_api_keys, _get_api_model_name, _quick_match, _run_skill_pipeline

class MOAEngine:
    """MOA多模型聚合引擎 — 核心处理流水线"""

    def __init__(self, registry: ModelRegistry = None):
        self.registry = registry or get_registry()
        self.router = SwarmRouter(self.registry)
        self.aggregator = AggregationEngine()
        self.memory = MemoryCore()
        # 配置中心
        self._config = get_config()
        # 加载API密钥（优先从配置中心读取）
        self._api_keys = self._load_api_keys()
        # 技能管线（延迟初始化）
        self._pipeline = None
        # 性能监控
        self._monitor = get_monitor()
        # 对话上下文管理
        self._conv_mgr = get_conversation_manager()
        # 健康检查
        self._health = get_health_checker()
        # 智能缓存
        self._cache = get_cache()

        logger.info("MOA引擎初始化完成(含配置中心+日志系统)")

    @property
    def pipeline(self):
        """延迟加载技能管线"""
        if self._pipeline is None:
            try:
                from skills import create_default_pipeline
                self._pipeline = create_default_pipeline()
                logger.info("技能管线初始化完成")
            except Exception as e:
                logger.warning(f"技能管线初始化失败: {e}")
        return self._pipeline

    # ============================================================
    # 主入口
    # ============================================================

    def process(self, query: str, user_id: str = "default",
                conversation_id: str = "",
                method: AggregationMethod = None) -> AggregationResult:
        """
        处理用户查询的完整流水线：
        0. 技能管线预处理（安全检查 + 文本分析 + 任务分类）
        1. 路由分析（复杂度 + 模型链推荐）
        2. 并行执行模型
        3. 聚合结果
        4. 存储记忆
        """
        start_time = time.time()

        # -1. 缓存查询
        cached = self._cache.get(query)
        if cached:
            logger.info(f"缓存命中: {query[:30]} (命中{cached.hit_count}次)")
            return AggregationResult(
                query=query,
                final_response=cached.response,
                primary_model=f"{cached.model_id}(cached)",
            )

        # 0. 技能管线预处理


pipeline

方法 MOAEngine.pipeline():
        """延迟加载技能管线"""
        if self._pipeline is None:
            try:
                from ski

def pipeline(self):
        """延迟加载技能管线"""
        if self._pipeline is None:
            try:
                from skills import create_default_pipeline
                self._pipeline = create_default_pipeline()
                logger.info("技能管线初始化完成")
            except Exception as e:
                logger.warning(f"技能管线初始化失败: {e}")
        return self._pipeline

    # ============================================================
    # 主入口
    # ============================================================


方法 MOAEngine.process_stream():
        """
        流式处理用户查询，逐字返回结果。
        生成器模式：yield (chunk_text, metadata_dict)
        """

def process_stream(self):
        """
        流式处理用户查询，逐字返回结果。
        生成器模式：yield (chunk_text, metadata_dict)
        """
        # 0. 技能管线预处理
        skill_analysis = self._run_skill_pipeline(query, user_id, conversation_id)

        if skill_analysis and not skill_analysis.get("is_safe", True):
            yield ("抱歉，您的请求包含不安全内容，无法处理。",
                   {"model": "safety_filter", "done": True})
            return

        # 1. 快速规则匹配
        quick = self._quick_match(query)
        if quick:
            yield (quick, {"model": "local_memory", "done": True})
            return

        # 2. 路由分析
        ctx = self.router.analyze(query, user_id, conversation_id)

        # 技能分析调整
        if skill_analysis and ctx.metadata is not None:
            ctx.metadata["skill_analysis"] = skill_analysis
            task_cat = skill_analysis.get("task_category", "")
            if task_cat in ("code", "analysis"):
                if ctx.complexity_score < 0.50:
                    ctx.complexity_score = min(ctx.comple


文件 deploy/windows/swarm/core/meta_model.py: 虫群v7 — 元模型(Meta Model)
虫后的核心调度器：意图识别 → 任务拆分 → 路由决策

设计思路：
- 元模型是虫后的"大脑"，负责分析用户输入并决定如何响应
- 当前基于规则+关键词实现，后续可替换为1B以下的小模型
- 输出TaskAnalysis，包含意图、复杂度、路由、子任务 | 定义: class MetaModel, def __init__, def analyze, def _detect_intent, def _assess_complexity, def _decide_route, def _decompose, def _detect_domains, def _intent_to_drone, def _calc_confidence

logging re uuid typing datetime core.types

#!/usr/bin/env python3
"""
虫群v7 — 元模型(Meta Model)
虫后的核心调度器：意图识别 → 任务拆分 → 路由决策

设计思路：
- 元模型是虫后的"大脑"，负责分析用户输入并决定如何响应
- 当前基于规则+关键词实现，后续可替换为1B以下的小模型
- 输出TaskAnalysis，包含意图、复杂度、路由、子任务
"""

import logging
import re
import uuid
from typing import Dict, List, Optional
from datetime import datetime

from core.types import (
    TaskAnalysis, SubTask, DroneType, TaskPriority,
)

logger = logging.getLogger(__name__)

# ============================================================
# 意图识别规则
# ================


MetaModel

类 MetaModel 在 deploy/windows/swarm/core/meta_model.py: 元模型 — 虫后的核心调度器

    三步走：
    1. analyze(): 意图识别 + 复杂度评估
    2. decompose(): 任务拆分（复杂任务才需要）
    3. route(): 路由决策（选模型/虫巢/其他虫后） | 方法: __init__, analyze, _detect_intent, _assess_complexity, _decide_route, _decompose, _detect_domains, _intent_to_drone, _calc_confidence, get_status

class MetaModel:
    """
    元模型 — 虫后的核心调度器

    三步走：
    1. analyze(): 意图识别 + 复杂度评估
    2. decompose(): 任务拆分（复杂任务才需要）
    3. route(): 路由决策（选模型/虫巢/其他虫后）
    """

    def __init__(self, user_id: str = "default"):
        self.user_id = user_id
        self._analyze_count = 0
        self._last_analysis: Optional[TaskAnalysis] = None

    # ============================================================
    # 核心方法: analyze — 三步合一
    # ============================================================

    def analyze(self, message: str, context: str = "") -> TaskAnalysis:
        """
        分析用户输入 → 返回TaskAnalysis

        Args:
            message: 用户消息
            context: 记忆上下文（来自MemoryModel）
        Returns:
            TaskAnalysis: 意图+复杂度+路由+子任务
        """
        self._analyze_count += 1

        # Step 1: 意图识别
        intent = self._detect_intent(message)

        # Step 2: 复杂度评估
        complexity = self._assess_complexity(message, intent)

        # Step 3: 路由决策
        route, assigned_model = self._decide_route(intent, complexity, context)

        # Step 4: 子任务拆分（复杂任务才拆）
        subtasks = []
        if complexity > 0.6 or intent == "multi":
            subtasks = self._decompose(message, intent)

        # Step 5: 知识领域识别
        domains = self._detect_domains(message)

        # 组装结果
        analysis = TaskAnalysis(
            query=message,
            intent=intent,
            complexity=complexity,
            route=route,
            assigned_model=assigned_model,
            subtasks=subtasks,
            confidence=self._calc_confidence(intent, complexity),
            requires_memory=bool(context),
            knowledge_domains=domains,
            reasoning_chain=[
                f"意图={intent}",
                f"复杂度={complexity:.2f}",
                f"路由={route}",
                f"子任务数={len(subtasks)}",
            ],
        )

        self._last_analysis = analysis
        logger.debug(f"元模型分析: intent=


文件 deploy/windows/swarm/core/smart_cache.py: 虫群智能体系统 — 智能缓存层
缓存重复查询结果，减少API调用
LRU + TTL + 语义相似度匹配 | 定义: class CacheEntry, def __init__, def is_expired, def age_seconds, def hit, def to_dict, def from_dict, class SmartCache, def __new__, def initialize

hashlib json logging os threading time collections typing

#!/usr/bin/env python3
"""
虫群智能体系统 — 智能缓存层
缓存重复查询结果，减少API调用
LRU + TTL + 语义相似度匹配
"""

import hashlib
import json
import logging
import os
import threading
import time
from collections import OrderedDict
from typing import Dict, List, Optional, Tuple

logger = logging.getLogger(__name__)

DEFAULT_CACHE_DIR = "/home/admin/swarm/data/cache"

class CacheEntry:
    """缓存条目"""

    def __init__(self, query: str, response: str, model_id: str,
                 confidence: float, ttl: int = 3600):


CacheEntry

类 CacheEntry 在 deploy/windows/swarm/core/smart_cache.py: 缓存条目 | 方法: __init__, is_expired, age_seconds, hit, to_dict, from_dict

class CacheEntry:
    """缓存条目"""

    def __init__(self, query: str, response: str, model_id: str,
                 confidence: float, ttl: int = 3600):
        self.query = query
        self.response = response
        self.model_id = model_id
        self.confidence = confidence
        self.created_at = time.time()
        self.ttl = ttl  # 秒
        self.hit_count = 0
        self.last_hit_at = None

    @property
    def is_expired(self) -> bool:
        return time.time() - self.created_at > self.ttl

    @property
    def age_seconds(self) -> float:
        return time.time() - self.created_at

    def hit(self):
        """记录一次命中"""
        self.hit_count += 1
        self.last_hit_at = time.time()

    def to_dict(self) -> Dict:
        return {
            "query": self.query,
            "response": self.response,
            "model_id": self.model_id,
            "confidence": self.confidence,
            "created_at": self.created_at,
            "ttl": self.ttl,
            "hit_count": self.hit_count,
            "last_hit_at": self.last_hit_at,
        }

    @classmethod
    def from_dict(cls, d: Dict) -> "CacheEntry":
        entry = cls(d["query"], d["response"], d["model_id"],
                    d["confidence"], d.get("ttl", 3600))
        entry.created_at = d.get("created_at", time.time())
        entry.hit_count = d.get("hit_count", 0)
        entry.last_hit_at = d.get("last_hit_at")
        return entry


hit

方法 CacheEntry.hit():
        """记录一次命中"""
        self.hit_count += 1
        self.last_hit_at = time.time()

def hit(self):
        """记录一次命中"""
        self.hit_count += 1
        self.last_hit_at = time.time()


SmartCache

类 SmartCache 在 deploy/windows/swarm/core/smart_cache.py: 智能缓存 — 单例
    特性：
    - LRU淘汰（容量上限）
    - TTL过期（时间上限）
    - 语义相似度匹配（相似问题命中缓存）
    - 关键词去重（核心词相同视为同一查询） | 方法: __new__, initialize, get, put, invalidate, clear, _find_similar, _extract_keywords, _update_keyword_index, _make_key, _should_skip, get_stats, get_top_entries, _save, _load

class SmartCache:
    """
    智能缓存 — 单例
    特性：
    - LRU淘汰（容量上限）
    - TTL过期（时间上限）
    - 语义相似度匹配（相似问题命中缓存）
    - 关键词去重（核心词相同视为同一查询）
    """

    _instance = None
    _lock = threading.Lock()

    # 缓存配置
    MAX_ENTRIES = 500        # 最大条目数
    DEFAULT_TTL = 3600       # 默认1小时过期
    SIMILARITY_THRESHOLD = 0.8  # 相似度阈值

    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)
                cls._instance._cache = OrderedDict()  # key -> CacheEntry
                cls._instance._keyword_index = {}     # 关键词集合 -> cache_key
                cls._instance._stats = {
                    "hits": 0, "misses": 0, "evictions": 0, "expirations": 0
                }
                cls._instance._initialized = False
            return cls._instance

    def initialize(self):
        """初始化缓存"""
        # 尝试加载持久化缓存
        self._load()
        self._initialized = True
        logger.info(f"智能缓存初始化: {len(self._cache)}条缓存")

    # ----------------------------------------------------------
    # 核心：查询/存储
    # ----------------------------------------------------------

    def get(self, query: str) -> Optional[CacheEntry]:
        """
        查询缓存
        策略：精确匹配 → 关键词匹配 → 无命中
        """
        # 1. 精确匹配
        key = self._make_key(query)
        entry = self._cache.get(key)
        if entry and not entry.is_expired:
            entry.hit()
            self._stats["hits"] += 1
            # LRU：移到末尾
            self._cache.move_to_end(key)
            logger.debug(f"缓存命中(精确): {query[:30]}")
            return entry
        elif entry and entry.is_expired:
            # 过期，删除
            del self._cache[key]
            self._stats["expirations"] += 1

        # 2. 关键词相似度匹配
        similar = self._find_similar(query)
        if similar:
            similar.hit()
            self._stats["hits"] += 1
            logger.debug(f"缓存命中(相似): {query[:30]} → {similar.query[:30]}")
            return similar

        self._stat


initialize

方法 SmartCache.initialize():
        """初始化缓存"""
        # 尝试加载持久化缓存
        self._load()
        self._initialized = True


put

方法 SmartCache.put():
        """
        存储到缓存
        仅缓存有意义的查询（太短/太常见的跳过）
        """
        # 过滤不需要缓存的查询
        if

def put(self):
        """
        存储到缓存
        仅缓存有意义的查询（太短/太常见的跳过）
        """
        # 过滤不需要缓存的查询
        if self._should_skip(query):
            return

        key = self._make_key(query)
        entry = CacheEntry(query, response, model_id, confidence,
                           ttl or self.DEFAULT_TTL)

        # 容量检查：LRU淘汰
        while len(self._cache) >= self.MAX_ENTRIES:
            oldest_key = next(iter(self._cache))
            del self._cache[oldest_key]
            self._stats["evictions"] += 1

        self._cache[key] = entry
        # 更新关键词索引
        self._update_keyword_index(key, query)

        # 持久化（节流：每10次写入持久化一次）
        if self._stats["misses"] % 10 == 0:
            self._save()


invalidate

方法 SmartCache.invalidate():
        """使指定查询的缓存失效"""
        key = self._make_key(query)
        if key in self._cache:

def invalidate(self):
        """使指定查询的缓存失效"""
        key = self._make_key(query)
        if key in self._cache:
            del self._cache[key]


clear

方法 SmartCache.clear():
        """清空缓存"""
        self._cache.clear()
        self._keyword_index.clear()
        self._sa


文件 deploy/windows/swarm/core/modal_glm.py: 虫群云端推理后端 — Modal GLM-5.1
- 调用Modal平台托管的GLM-5.1-FP8推理端点
- OpenAI兼容API格式
- 支持流式和非流式推理
- 带思维链(reasoning)输出 | 定义: class ModalGLMBackend, def __init__, def chat, def simple_ask, def get_status, def health_check, def get_glm_backend

#!/usr/bin/env python3
"""
虫群云端推理后端 — Modal GLM-5.1
- 调用Modal平台托管的GLM-5.1-FP8推理端点
- OpenAI兼容API格式
- 支持流式和非流式推理
- 带思维链(reasoning)输出
"""

import os
import time
import json
import httpx
from typing import Dict, Optional

class ModalGLMBackend:
    """
    Modal平台GLM-5.1云端推理后端

    端点: https://api.us-west-2.modal.direct/v1/chat/completions
    模型: zai-org/GLM-5.1-FP8 (FP8量化, 带推理能力)
    """

    # Modal GLM-5.1端点配置
    DEFAULT_BASE_URL = "https://api.us-west-2.modal.direct/v1"
    DEFAULT_MO


ModalGLMBackend

类 ModalGLMBackend 在 deploy/windows/swarm/core/modal_glm.py: Modal平台GLM-5.1云端推理后端

    端点: https://api.us-west-2.modal.direct/v1/chat/completions
    模型: zai-org/GLM-5.1-FP8 (FP8量化, 带推理能力) | 方法: __init__, chat, simple_ask, get_status, health_check

class ModalGLMBackend:
    """
    Modal平台GLM-5.1云端推理后端

    端点: https://api.us-west-2.modal.direct/v1/chat/completions
    模型: zai-org/GLM-5.1-FP8 (FP8量化, 带推理能力)
    """

    # Modal GLM-5.1端点配置
    DEFAULT_BASE_URL = "https://api.us-west-2.modal.direct/v1"
    DEFAULT_MODEL = "zai-org/GLM-5.1-FP8"
    DEFAULT_API_KEY = "modalresearch_m7wFgRkq4LQ1vxVd2FZ0r3o2Ixz66SISJoAvwuUTkCc"

    def __init__(
        self,
        base_url: str = None,
        api_key: str = None,
        model: str = None,
        timeout: float = 120.0,
    ):
        self.base_url = base_url or os.environ.get(
            "MODAL_GLM_BASE_URL", self.DEFAULT_BASE_URL
        )
        self.api_key = api_key or os.environ.get(
            "MODAL_GLM_API_KEY", self.DEFAULT_API_KEY
        )
        self.model = model or os.environ.get(
            "MODAL_GLM_MODEL", self.DEFAULT_MODEL
        )
        self.timeout = timeout

        # 统计
        self._total_calls = 0
        self._total_errors = 0
        self._total_latency_ms = 0

    def chat(
        self,
        messages: list,
        max_tokens: int = 2048,
        temperature: float = 0.7,
        top_p: float = 0.9,
    ) -> Dict:
        """
        聊天推理接口

        参数:
            messages: OpenAI格式消息列表 [{"role": "user", "content": "..."}]
            max_tokens: 最大生成token数
            temperature: 采样温度
            top_p: 核采样概率

        返回:
            {
                "response": str,           # 生成内容
                "reasoning": str,          # 思维链内容(GLM-5.1特有)
                "model": str,              # 模型名
                "usage": dict,             # token用量
                "latency_ms": float,       # 延迟
                "success": bool,
            }
        """
        start_time = time.perf_counter()
        self._total_calls += 1

        payload = {
            "model": self.model,
            "messages": messages,
            "max_tokens": max_tokens,
            "temperature": temperature,


文件 deploy/windows/swarm/core/model_registry.py: 虫群智能体系统 — 统一模型注册表
管理所有可用模型的生命周期：注册、查询、性能跟踪 | 定义: class ModelRegistry, def __new__, def register, def unregister, def get, def list_models, def list_model_ids, def get_local_models, def get_api_models, def get_active_models

#!/usr/bin/env python3
"""
虫群智能体系统 — 统一模型注册表
管理所有可用模型的生命周期：注册、查询、性能跟踪
"""

import logging
import threading
from typing import Dict, List, Optional
from core.types import ModelInfo, ModelType, ModelStatus, PerformanceStats

logger = logging.getLogger(__name__)

class ModelRegistry:
    """统一模型注册表 — 单例模式"""

    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)


ModelRegistry

统一模型注册表 — 单例模式

类 ModelRegistry 在 deploy/windows/swarm/core/model_registry.py: 统一模型注册表 — 单例模式 | 方法: __new__, register, unregister, get, list_models, list_model_ids, get_local_models, get_api_models, get_active_models, record_performance, get_stats, get_ranking, set_status, get_status_report

class ModelRegistry:
    """统一模型注册表 — 单例模式"""

    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)
                cls._instance._models = {}
                cls._instance._stats = {}
                cls._instance._initialized = False
            return cls._instance

    # ----------------------------------------------------------
    # 注册 / 注销
    # ----------------------------------------------------------

    def register(self, model: ModelInfo) -> bool:
        """注册一个模型"""
        if model.model_id in self._models:
            logger.warning(f"模型 {model.model_id} 已存在，将覆盖")
        self._models[model.model_id] = model
        self._stats[model.model_id] = PerformanceStats(model_id=model.model_id)
        logger.info(f"注册模型: {model.model_id} ({model.model_type.value})")
        return True

    def unregister(self, model_id: str) -> bool:
        """注销一个模型"""
        if model_id in self._models:
            del self._models[model_id]
            self._stats.pop(model_id, None)
            logger.info(f"注销模型: {model_id}")
            return True
        return False

    # ----------------------------------------------------------
    # 查询
    # ----------------------------------------------------------

    def get(self, model_id: str) -> Optional[ModelInfo]:
        """获取模型信息"""
        return self._models.get(model_id)

    def list_models(self, model_type: ModelType = None,
                    status: ModelStatus = None) -> List[ModelInfo]:
        """列出模型，支持按类型和状态过滤"""
        models = list(self._models.values())
        if model_type:
            models = [m for m in models if m.model_type == model_type]
        if status:
            models = [m for m in models if m.status == status]
        return models

    def list_model_ids(self, model_type: ModelType = None) -> List[str]:
        """列出模型ID"""
        return [m.model_id for m in self.li


方法 ModelRegistry.record_performance():
        """记录模型性能数据"""
        if model_id in self._stats:
            self._stats[model_id].record

def record_performance(self):
        """记录模型性能数据"""
        if model_id in self._stats:
            self._stats[model_id].record(latency_ms, confidence, success)
        else:
            logger.warning(f"记录性能时模型 {model_id} 不在注册表中")


方法 ModelRegistry.set_status():
        """设置模型状态"""
        if model_id in self._models:
            self._models[model_id].status

def set_status(self):
        """设置模型状态"""
        if model_id in self._models:
            self._models[model_id].status = status


初始化默认模型（本地推理群 + 本地记忆 + GLM）

函数 init_default_models() 在 deploy/windows/swarm/core/model_registry.py: 初始化默认模型（本地推理群 + 本地记忆 + GLM）

def init_default_models():
    """初始化默认模型（本地推理群 + 本地记忆 + GLM）"""
    registry = get_registry()

    # 本地推理模型群（训练好的SwarmModel）
    # 检查可用模型
    try:
        from core.local_inference import LocalModelBackend
        backend = LocalModelBackend()
        for name in backend.list_available():
            meta = backend.get_model_info(name)
            params_m = meta.get("params", {}).get("params_M", 0) if meta else 0
            desc_map = {
                "tiny": "轻量级模型(5M)，快速响应问候和简单问答",
                "small": "通用模型(15M)，处理日常对话和知识问答",
                "medium": "推理模型(50M)，处理复杂推理和深度分析",
            }
            priority_map = {"tiny": 1, "small": 2, "medium": 3}
            conf_map = {"tiny": 0.5, "small": 0.65, "medium": 0.75}

            registry.register(ModelInfo(
                model_id=f"swarm_{name}",
                name=f"虫群{name.capitalize()}",
                model_type=ModelType.LOCAL,
                description=desc_map.get(name, f"本地{name}模型"),
                default_confidence=conf_map.get(name, 0.5),
                priority=priority_map.get(name, 5),
                tags=["local", "inference", name],
            ))
    except Exception:
        pass  # 训练模型不存在时跳过

    # 本地记忆模型（兜底）
    registry.register(ModelInfo(
        model_id="local_memory",
        name="本地记忆模型",
        model_type=ModelType.LOCAL,
        description="基于记忆检索的本地响应模型",
        default_confidence=0.3,
        priority=10,
        tags=["memory", "local"],
    ))

    # GLM API
    registry.register(ModelInfo(
        model_id="glm_api",
        name="智谱GLM-4-Flash",
        model_type=ModelType.API,
        endpoint="https://open.bigmodel.cn/api/paas/v4/chat/completions",
        default_confidence=0.8,
        max_tokens=1024,
        priority=5,
        tags=["api", "glm"],
    ))

    logger.info("默认模型初始化完成（本地记忆 + GLM）")
    return registry


文件 deploy/windows/swarm/core/seed_model.py: 虫群v7 — 种子模型(Seed Model)
统一基座: 同一个种子，喂不同的数据长成不同的模型

设计思路:
- 虫皇模型是种子，只要喂养不同的素材，就可以长成不同的模型
- 体量大了就是虫巢/脑虫，体量小了就是个人端使用的虫后
- 功能模块是每层系统都有的
- 核心方法 grow(): 从种子生长为特定领域的模型 | 定义: class SeedModel, def __init__, def grow, def _train, def _simulated_train, def _validate_data, def _save_state, def _load_state, def get_info, def get_growth_log

#!/usr/bin/env python3
"""
虫群v7 — 种子模型(Seed Model)
统一基座: 同一个种子，喂不同的数据长成不同的模型

设计思路:
- 虫皇模型是种子，只要喂养不同的素材，就可以长成不同的模型
- 体量大了就是虫巢/脑虫，体量小了就是个人端使用的虫后
- 功能模块是每层系统都有的
- 核心方法 grow(): 从种子生长为特定领域的模型
"""

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

logger = logging.getLogger(__name__)

# ============================================================
# 种子模型配置
# ============================================================

SEED_CONFIGS


SeedModel

类 SeedModel 在 deploy/windows/swarm/core/seed_model.py: 种子模型 — 虫群统一基座

    核心概念:
    1. 种子 = 初始化参数 + 训练框架
    2. grow(数据) = 训练 → 输出特定领域的模型
    3. 同一粒种子，喂物理数据长成物理老师，喂代码数据长成编程助手
    4. 体量由配置决定: drone < queen < cerebrate < hive

    当前实现: 元数据管理 + 训练调度 | 方法: __init__, grow, _train, _simulated_train, _validate_data, _save_state, _load_state, get_info, get_growth_log, list_seeds

class SeedModel:
    """
    种子模型 — 虫群统一基座

    核心概念:
    1. 种子 = 初始化参数 + 训练框架
    2. grow(数据) = 训练 → 输出特定领域的模型
    3. 同一粒种子，喂物理数据长成物理老师，喂代码数据长成编程助手
    4. 体量由配置决定: drone < queen < cerebrate < hive

    当前实现: 元数据管理 + 训练调度
    未来: 接入实际训练管线
    """

    SEEDS_DIR = "/home/admin/swarm/training/seeds"

    def __init__(self, seed_name: str = "default", role: str = "queen"):
        self.seed_name = seed_name
        self.role = role  # drone/queen/cerebrate/hive
        self.config = SEED_CONFIGS.get(role, SEED_CONFIGS["queen"])

        # 种子状态
        self.created_at = datetime.now().isoformat()
        self.growth_history: List[Dict] = []
        self.current_gen = 0  # 当前代数
        self.total_data_fed = 0  # 已喂养数据量(条)

        # 模型路径
        self.seed_dir = os.path.join(self.SEEDS_DIR, seed_name)
        self.model_path = ""
        self.is_grown = False

    # ============================================================
    # 核心方法: grow — 从种子生长为模型
    # ============================================================

    def grow(self, data_path: str, epochs: int = 2,
             learning_rate: float = 3e-4,
             description: str = "") -> Dict:
        """
        喂养数据让种子生长

        Args:
            data_path: 训练数据路径(JSON)
            epochs: 训练轮数
            learning_rate: 学习率
            description: 本次生长描述
        Returns:
            生长结果dict
        """
        start_time = time.time()

        # 验证数据
        data_info = self._validate_data(data_path)
        if not data_info["valid"]:
            return {"success": False, "error": data_info["error"]}

        # 记录生长事件
        self.current_gen += 1
        self.total_data_fed += data_info["count"]

        growth_event = {
            "gen": self.current_gen,
            "timestamp": datetime.now().isoformat(),
            "data_path": data_path,
            "data_count": data_info["count"],
            "epochs": epochs,
            "learning_rate":


文件 deploy/windows/swarm/core/data_collector.py: 虫群v7.1 — 数据采集器
自动化收集、清洗、整理训练数据

数据来源:
  1. 对话数据: 用户日常交互产生的高质量对话
  2. 公开数据集: HuggingFace/GitHub上的中文训练数据
  3. 网络爬取: 按需爬取特定领域数据(需合规)
  4. 项目过程: 开发过程数据(日志、文档)作为验证

设计原则:
  - 质量优先: 低质量数据宁可不要
  - 自动去重: 相似内容 | 定义: class DataCollector, def __init__, def _load_data, def _load_hashes, def _save, def collect_from_chat, def collect_from_conversation, def collect_from_file, def list_public_datasets, def download_dataset

hashlib json logging os time datetime typing

#!/usr/bin/env python3
"""
虫群v7.1 — 数据采集器
自动化收集、清洗、整理训练数据

数据来源:
  1. 对话数据: 用户日常交互产生的高质量对话
  2. 公开数据集: HuggingFace/GitHub上的中文训练数据
  3. 网络爬取: 按需爬取特定领域数据(需合规)
  4. 项目过程: 开发过程数据(日志、文档)作为验证

设计原则:
  - 质量优先: 低质量数据宁可不要
  - 自动去重: 相似内容自动合并
  - 格式统一: 输出标准训练格式
  - 持续积累: 数据库式管理，不丢失
"""

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

logger = logging.getLogger(__name__)

# 数据质量评分阈值
QUALITY_CONFIG = {
    "min_leng


DataCollector

类 DataCollector 在 deploy/windows/swarm/core/data_collector.py: 数据采集器 — 训练数据的自动积累

    使用方式:
      dc = DataCollector("my_queen")
      dc.collect_from_chat("你好", "你好！有什么可以帮你？")
      dc.collect_from_file("data.json") | 方法: __init__, _load_data, _load_hashes, _save, collect_from_chat, collect_from_conversation, collect_from_file, list_public_datasets, download_dataset, _quality_score, quality_filter, _hash_content, get_stats, export_training_data

class DataCollector:
    """
    数据采集器 — 训练数据的自动积累

    使用方式:
      dc = DataCollector("my_queen")
      dc.collect_from_chat("你好", "你好！有什么可以帮你？")
      dc.collect_from_file("data.json")
    """

    def __init__(self, model_name: str,
                 base_dir: str = "/home/admin/swarm/training/seeds"):
        self.model_name = model_name
        self.data_dir = os.path.join(base_dir, model_name, "data")
        self._data_file = os.path.join(self.data_dir, "collected_data.json")
        self._dedup_file = os.path.join(self.data_dir, "dedup_hashes.json")

        # 加载已有数据
        self._data: List[Dict] = self._load_data()
        self._hashes: set = self._load_hashes()

    def _load_data(self) -> List[Dict]:
        """加载已收集数据"""
        if os.path.exists(self._data_file):
            with open(self._data_file, "r") as f:
                return json.load(f)
        return []

    def _load_hashes(self) -> set:
        """加载去重哈希集"""
        if os.path.exists(self._dedup_file):
            with open(self._dedup_file, "r") as f:
                return set(json.load(f))
        return set()

    def _save(self):
        """保存数据"""
        os.makedirs(self.data_dir, exist_ok=True)
        with open(self._data_file, "w") as f:
            json.dump(self._data, f, indent=2, ensure_ascii=False)
        with open(self._dedup_file, "w") as f:
            json.dump(list(self._hashes), f)

    # ============================================================
    # 对话采集
    # ============================================================

    def collect_from_chat(self, user_msg: str, ai_msg: str,
                          metadata: Dict = None) -> bool:
        """
        从对话中采集一条训练数据

        Args:
            user_msg: 用户消息
            ai_msg: AI回复
            metadata: 附加信息(模型、延迟等)
        Returns:
            是否成功采集(通过质量过滤)
        """
        # 质量检查
        score = self._quality_score(user_msg, ai_msg)
        if score < QUALITY_CONFIG["min_quality_score"]:
            logger.debug


文件 deploy/windows/swarm/core/queen_agent.py: 虫群v7 — 虫后(Queen)个人端智能体
个人模型系统核心：元模型调度 + 记忆模型 + 任务模型树

架构:
  用户输入 → 元模型(分析/拆分/路由) → 任务模型/记忆模型/虫巢大模型 → 聚合 → 返回

虫后是每个用户的专属AI系统，所有交互的统一入口。 | 定义: class QueenAgent, def __init__, def chat, def chat_detailed, def _execute_route, def _execute_local_drone, def _execute_memory, def _execute_cloud, def _execute_moa, def _call_cloud

#!/usr/bin/env python3
"""
虫群v7 — 虫后(Queen)个人端智能体
个人模型系统核心：元模型调度 + 记忆模型 + 任务模型树

架构:
  用户输入 → 元模型(分析/拆分/路由) → 任务模型/记忆模型/虫巢大模型 → 聚合 → 返回

虫后是每个用户的专属AI系统，所有交互的统一入口。
"""

import logging
import time
import uuid
from datetime import datetime
from typing import Dict, List, Optional, Any

from core.types import (
    SwarmRole, DroneType, ModelLocation, TaskPriority,
    DroneInfo, QueenInfo, SwarmTask, SwarmStatus,
)
from core.meta_model import MetaModel
from core.memory_model import MemoryModel, Memo


QueenAgent

类 QueenAgent 在 deploy/windows/swarm/core/queen_agent.py: 虫后智能体 — 个人端核心

    三大组件:
    1. 元模型(MetaModel): 意图分析 → 任务拆分 → 路由决策
    2. 记忆模型(MemoryModel): 参数化个人记忆，模型即数据库
    3. 任务模型树(TaskTree): 知识树结构的按需加载任务模型群 | 方法: __init__, chat, chat_detailed, _execute_route, _execute_local_drone, _execute_memory, _execute_cloud, _execute_moa, _call_cloud, new_conversation, get_history, get_status, get_info

class QueenAgent:
    """
    虫后智能体 — 个人端核心

    三大组件:
    1. 元模型(MetaModel): 意图分析 → 任务拆分 → 路由决策
    2. 记忆模型(MemoryModel): 参数化个人记忆，模型即数据库
    3. 任务模型树(TaskTree): 知识树结构的按需加载任务模型群
    """

    def __init__(self, user_id: str = "default", queen_name: str = ""):
        # 虫后身份
        self.queen_id = f"queen_{user_id}_{uuid.uuid4().hex[:6]}"
        self.user_id = user_id
        self.queen_name = queen_name or f"虫后-{user_id}"

        # 会话状态
        self.conversation_id = datetime.now().strftime("%Y%m%d_%H%M%S")
        self._session_history: List[Dict] = []

        # 模型注册表（兼容v6）
        self.registry = get_registry()
        init_default_models()

        # === 三大核心组件 ===
        # 1. 元模型 — 任务分析与路由
        self.meta = MetaModel(user_id=user_id)

        # 2. 记忆矩阵 — 参数化个人记忆(含任务分叉)
        self.memory_matrix = MemoryMatrix(user_id)
        self.memory = self.memory_matrix.current  # 当前活跃记忆

        # 3. 任务模型树 — 按需加载的任务模型群
        self.task_tree = TaskTree(user_id=user_id)

        # === 自动训练 + 数据采集 ===
        self.trainer = AutoTrainer(user_id, role="queen")
        self.collector = DataCollector(user_id)

        # === 推理后端 ===
        self.local_backend = get_local_backend()
        self.cloud_backend = get_glm_backend()

        # === MOA引擎（兼容v6，用于多模型聚合） ===
        self.moa = MOAEngine(self.registry)

        # 虫后信息
        self.info = QueenInfo(
            queen_id=self.queen_id,
            name=self.queen_name,
            status=SwarmStatus.ACTIVE,
            last_active=datetime.now(),
        )

        logger.info(f"虫后初始化完成: {self.queen_id} (用户: {user_id})")

    # ============================================================
    # 核心交互 — 统一入口
    # ============================================================

    def chat(self, message: str, method: str = None) -> str:
        """
        与虫后对话 — 所有交互的统一入口

        流程(v7.1增强):
        1. 记忆检索: 通过记忆矩阵获取相关上下文(超长对话)
        2. 元模型分析:


RoyalAgent

虫皇智能体 — v7兼容层，内部使用QueenAgent

类 RoyalAgent 在 deploy/windows/swarm/core/queen_agent.py: 虫皇智能体 — v7兼容层，内部使用QueenAgent | 方法: __init__

class RoyalAgent:
    """虫皇智能体 — v7兼容层，内部使用QueenAgent"""

    def __init__(self):
        super().__init__(user_id="default", queen_name="虫皇")


文件 deploy/windows/swarm/core/performance_monitor.py: 虫群智能体系统 — 性能监控模块
请求统计、模型延迟、成功率追踪、告警规则 | 定义: class
class, class PerformanceMonitor, def __new__, def __init__, def record, def get_model_summary, def get_all_summaries, def get_recent_metrics, def get_hourly_stats, def get_daily_stats

json logging os threading time collections dataclasses datetime typing

#!/usr/bin/env python3
"""
虫群智能体系统 — 性能监控模块
请求统计、模型延迟、成功率追踪、告警规则
"""

import json
import logging
import os
import threading
import time
from collections import defaultdict, deque
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Dict, List, Optional

logger = logging.getLogger(__name__)

# 默认存储路径
DEFAULT_METRICS_PATH = "/home/admin/swarm/data/metrics.json"

@dataclass
class RequestMetric:
    """单次请求指标"""
    request_id: str
    query: str


RequestMetric

类 RequestMetric 在 deploy/windows/swarm/core/performance_monitor.py: 单次请求指标 | 方法:

class RequestMetric:
    """单次请求指标"""
    request_id: str
    query: str
    model_id: str
    latency_ms: float
    confidence: float
    success: bool
    timestamp: float = field(default_factory=time.time)
    error: str = ""


PerformanceMonitor

性能监控器 — 线程安全的请求指标收集和分析

类 PerformanceMonitor 在 deploy/windows/swarm/core/performance_monitor.py: 性能监控器 — 线程安全的请求指标收集和分析 | 方法: __new__, __init__, record, get_model_summary, get_all_summaries, get_recent_metrics, get_hourly_stats, get_daily_stats, _window_stats, add_alert_rule, on_alert, _check_alerts, save, load, get_report

class PerformanceMonitor:
    """性能监控器 — 线程安全的请求指标收集和分析"""

    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)
                cls._instance._initialized = False
            return cls._instance

    def __init__(self):
        if self._initialized:
            return
        self._initialized = True

        # 指标存储（最近N条）
        self._max_history = 1000
        self._metrics: deque = deque(maxlen=self._max_history)

        # 按模型汇总
        self._model_stats: Dict[str, dict] = defaultdict(lambda: {
            "total": 0, "success": 0, "fail": 0,
            "total_latency_ms": 0.0, "total_confidence": 0.0,
            "min_latency_ms": float("inf"), "max_latency_ms": 0.0,
        })

        # 时间窗口统计（最近1小时/24小时）
        self._hourly: Dict[str, deque] = defaultdict(lambda: deque(maxlen=3600))
        self._daily: Dict[str, deque] = defaultdict(lambda: deque(maxlen=86400))

        # 告警规则
        self._alerts: List[dict] = []
        self._alert_callbacks = []

        # 持久化路径
        self._metrics_path = DEFAULT_METRICS_PATH

        # 请求计数器
        self._request_counter = 0

    # ============================================================
    # 记录
    # ============================================================

    def record(self, model_id: str, latency_ms: float,
               confidence: float, success: bool,
               query: str = "", error: str = "") -> str:
        """
        记录一次请求指标，返回request_id
        """
        self._request_counter += 1
        request_id = f"req_{self._request_counter:06d}"

        metric = RequestMetric(
            request_id=request_id,
            query=query[:100],  # 只存前100字
            model_id=model_id,
            latency_ms=latency_ms,
            confidence=confidence,
            success=success,
            error=error[:200],
        )

        with self._lock:
            self._metrics.append(metri


方法 PerformanceMonitor.add_alert_rule():
        """添加告警规则"""
        self._alerts.append({
            "name": name,
            "model_id"

def add_alert_rule(self):
        """添加告警规则"""
        self._alerts.append({
            "name": name,
            "model_id": model_id,
            "min_latency_ms": min_latency_ms,
            "max_success_rate": max_success_rate,
            "min_confidence": min_confidence,
        })


方法 PerformanceMonitor.on_alert():
        """注册告警回调"""
        self._alert_callbacks.append(callback)

def on_alert(self):
        """注册告警回调"""
        self._alert_callbacks.append(callback)


save

方法 PerformanceMonitor.save():
        """保存指标到文件"""
        path = path or self._metrics_path
        os.makedirs(os.path.dirname

def save(self):
        """保存指标到文件"""
        path = path or self._metrics_path
        os.makedirs(os.path.dirname(path), exist_ok=True)
        data = {
            "request_counter": self._request_counter,
            "model_stats": dict(self._model_stats),
            "saved_at": datetime.now().isoformat(),
        }
        with open(path, "w") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)


load

方法 PerformanceMonitor.load():
        """从文件加载指标"""
        path = path or self._metrics_path
        if not os.path.exists(path)

def load(self):
        """从文件加载指标"""
        path = path or self._metrics_path
        if not os.path.exists(path):
            return
        try:
            with open(path) as f:
                data = json.load(f)
            self._request_counter = data.get("request_counter", 0)
            for mid, stats in data.get("model_stats", {}).items():
                self._model_stats[mid] = stats
            logger.info(f"性能指标已加载: {path}")
        except Exception as e:
            logger.warning(f"加载性能指标失败: {e}")

    # ============================================================
    # 报告
    # ============================================================


文件 deploy/windows/swarm/core/logging_config.py: 虫群智能体系统 — 结构化日志配置
统一日志格式、分级、轮转 | 定义: class ColoredFormatter, def format, def setup_logging, def get_logger

logging logging.handlers os sys datetime

#!/usr/bin/env python3
"""
虫群智能体系统 — 结构化日志配置
统一日志格式、分级、轮转
"""

import logging
import logging.handlers
import os
import sys
from datetime import datetime

LOG_DIR = "/home/admin/swarm/logs"
LOG_FORMAT = "%(asctime)s | %(levelname)-5s | %(name)-20s | %(message)s"
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"

class ColoredFormatter(logging.Formatter):
    """终端彩色日志格式器"""

    COLORS = {
        logging.DEBUG: "\033[36m",     # 青色
        logging.INFO: "\033[32m",      # 绿色
        logging.WARNING: "\033[33m


ColoredFormatter

类 ColoredFormatter 在 deploy/windows/swarm/core/logging_config.py: 终端彩色日志格式器 | 方法: format

class ColoredFormatter:
    """终端彩色日志格式器"""

    COLORS = {
        logging.DEBUG: "\033[36m",     # 青色
        logging.INFO: "\033[32m",      # 绿色
        logging.WARNING: "\033[33m",   # 黄色
        logging.ERROR: "\033[31m",     # 红色
        logging.CRITICAL: "\033[35m",  # 紫色
    }
    RESET = "\033[0m"

    def format(self, record):
        color = self.COLORS.get(record.levelno, "")
        record.levelname = f"{color}{record.levelname}{self.RESET}"
        return super().format(record)


format

方法 ColoredFormatter.format():
        color = self.COLORS.get(record.levelno, "")
        record.levelname = f"{color}{record.lev

def format(self):
        color = self.COLORS.get(record.levelno, "")
        record.levelname = f"{color}{record.levelname}{self.RESET}"
        return super().format(record)


函数 format(self, record) 在 deploy/windows/swarm/core/logging_config.py:

def format(self, record):
        color = self.COLORS.get(record.levelno, "")
        record.levelname = f"{color}{record.levelname}{self.RESET}"
        return super().format(record)


函数 setup_logging(level: str = "INFO", log_file: str = None) 在 deploy/windows/swarm/core/logging_config.py: 配置虫群智能体日志系统

    参数:
        level: 日志级别 (DEBUG/INFO/WARNING/ERROR)
        log_file: 日志文件名（可选）

def setup_logging(level: str = "INFO", log_file: str = None):
    """
    配置虫群智能体日志系统

    参数:
        level: 日志级别 (DEBUG/INFO/WARNING/ERROR)
        log_file: 日志文件名（可选）
    """
    log_level = getattr(logging, level.upper(), logging.INFO)

    # 创建日志目录
    os.makedirs(LOG_DIR, exist_ok=True)

    # 根日志器
    root_logger = logging.getLogger("swarm")
    root_logger.setLevel(log_level)

    # 清除已有处理器
    root_logger.handlers.clear()

    # 1. 终端输出（彩色）
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(log_level)
    console_formatter = ColoredFormatter(LOG_FORMAT, datefmt=DATE_FORMAT)
    console_handler.setFormatter(console_formatter)
    root_logger.addHandler(console_handler)

    # 2. 文件输出（按天轮转）
    if log_file is None:
        log_file = f"swarm_{datetime.now().strftime('%Y%m%d')}.log"
    file_path = os.path.join(LOG_DIR, log_file)

    file_handler = logging.handlers.TimedRotatingFileHandler(
        file_path,
        when="midnight",     # 每天轮转
        interval=1,
        backupCount=7,       # 保留7天
        encoding="utf-8",
    )
    file_handler.setLevel(log_level)
    file_formatter = logging.Formatter(LOG_FORMAT, datefmt=DATE_FORMAT)
    file_handler.setFormatter(file_formatter)
    root_logger.addHandler(file_handler)

    # 3. 错误日志单独文件
    error_path = os.path.join(LOG_DIR, "swarm_error.log")
    error_handler = logging.handlers.RotatingFileHandler(
        error_path,
        maxBytes=5*1024*1024,  # 5MB
        backupCount=3,
        encoding="utf-8",
    )
    error_handler.setLevel(logging.ERROR)
    error_handler.setFormatter(file_formatter)
    root_logger.addHandler(error_handler)

    # 降低第三方库日志级别
    logging.getLogger("urllib3").setLevel(logging.WARNING)
    logging.getLogger("requests").setLevel(logging.WARNING)
    logging.getLogger("flask").setLevel(logging.WARNING)
    logging.getLogger("werkzeug").setLevel(logging.WARNING)

    root_logger.info(f"日志系统初始化: 级别={level}, 文件={file_path}")
    return root_logger


types.py

文件 deploy/windows/swarm/core/types.py: 虫群v6 — 统一类型定义

虫族生态体系：
  虫皇(Overmind)  — 最高控制中心，全局调度
  虫巢(Hive)      — 中央大模型集群，云端推理
  脑虫(Cerebrate) — 区域路由节点，任务分发
  虫后(Queen)     — 个人模型系统，用户专属
  子虫(Drone)     — 功能模型，按需启动 | 定义: class SwarmRole, class DroneType, class ModelLocation, class TaskPriority, class SwarmStatus, class
class, def to_dict, class
class, def to_dict, class
class

#!/usr/bin/env python3
"""
虫群v6 — 统一类型定义

虫族生态体系：
  虫皇(Overmind)  — 最高控制中心，全局调度
  虫巢(Hive)      — 中央大模型集群，云端推理
  脑虫(Cerebrate) — 区域路由节点，任务分发
  虫后(Queen)     — 个人模型系统，用户专属
  子虫(Drone)     — 功能模型，按需启动
"""

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

# ============================================================
# 虫族角色枚举
# ============================================================

class SwarmRole(Enum


SwarmRole

类 SwarmRole 在 deploy/windows/swarm/core/types.py: 虫族角色层级 | 方法:

class SwarmRole:
    """虫族角色层级"""
    OVERMIND = "overmind"     # 虫皇 — 最高决策
    HIVE = "hive"             # 虫巢 — 中央模型集群
    CEREBRATE = "cerebrate"   # 脑虫 — 区域路由
    QUEEN = "queen"           # 虫后 — 个人模型系统
    DRONE = "drone"           # 子虫 — 功能模型


DroneType

类 DroneType 在 deploy/windows/swarm/core/types.py: 子虫类型 — 功能分类 | 方法:

class DroneType:
    """子虫类型 — 功能分类"""
    INTENT = "intent"           # 意图识别
    MEMORY = "memory"           # 记忆模型
    CHAT = "chat"               # 对话模型
    REASONING = "reasoning"     # 推理模型
    TRANSLATION = "translation" # 翻译模型
    CODING = "coding"           # 编程模型
    KNOWLEDGE = "knowledge"     # 知识模型
    CREATIVE = "creative"       # 创意模型
    CUSTOM = "custom"           # 自定义模型


ModelLocation

类 ModelLocation 在 deploy/windows/swarm/core/types.py: 模型部署位置 | 方法:

class ModelLocation:
    """模型部署位置"""
    LOCAL = "local"       # 本地CPU/GPU
    CLOUD = "cloud"       # 云端API
    REMOTE = "remote"     # 远程虫后（其他用户）


TaskPriority

类 TaskPriority 在 deploy/windows/swarm/core/types.py: 任务优先级 | 方法:

class TaskPriority:
    """任务优先级"""
    CRITICAL = 0   # 虫皇指令
    HIGH = 1       # 复杂推理
    NORMAL = 2     # 日常任务
    LOW = 3        # 后台学习


SwarmStatus

类 SwarmStatus 在 deploy/windows/swarm/core/types.py: 虫群节点状态 | 方法:


DroneInfo

子虫信息 — 最小功能单元

类 DroneInfo 在 deploy/windows/swarm/core/types.py: 子虫信息 — 最小功能单元 | 方法: to_dict

class DroneInfo:
    """子虫信息 — 最小功能单元"""
    drone_id: str                    # 唯一标识: queen_id.domain.name
    name: str                        # 显示名称
    drone_type: DroneType            # 功能类型
    location: ModelLocation          # 部署位置
    params_M: float = 0.0            # 参数量(M)
    status: SwarmStatus = SwarmStatus.IDLE
    confidence: float = 0.5          # 默认置信度
    avg_latency_ms: float = 0.0      # 平均延迟
    parent_queen: str = ""           # 所属虫后ID
    knowledge_domain: str = ""       # 知识领域（如"力学"、"编程"）
    tags: List[str] = field(default_factory=list)
    endpoint: str = ""               # API端点（远程子虫）
    last_active: Optional[datetime] = None

    def to_dict(self) -> Dict:
        return {
            "drone_id": self.drone_id,
            "name": self.name,
            "drone_type": self.drone_type.value,
            "location": self.location.value,
            "params_M": self.params_M,
            "status": self.status.value,
            "confidence": self.confidence,
            "avg_latency_ms": self.avg_latency_ms,
            "parent_queen": self.parent_queen,
            "knowledge_domain": self.knowledge_domain,
            "tags": self.tags,
        }

@dataclass


QueenInfo

虫后信息 — 个人模型系统

类 QueenInfo 在 deploy/windows/swarm/core/types.py: 虫后信息 — 个人模型系统 | 方法: to_dict

class QueenInfo:
    """虫后信息 — 个人模型系统"""
    queen_id: str                    # 用户唯一标识
    name: str                        # 用户名
    status: SwarmStatus = SwarmStatus.IDLE
    drones: List[str] = field(default_factory=list)  # 子虫ID列表
    memory_drone: str = ""           # 记忆子虫ID
    meta_model: str = ""             # 元模型（意图识别）子虫ID
    knowledge_tree: Dict = field(default_factory=dict)  # 知识树结构
    total_params_M: float = 0.0      # 总参数量
    created_at: datetime = field(default_factory=datetime.now)
    last_active: Optional[datetime] = None

    def to_dict(self) -> Dict:
        return {
            "queen_id": self.queen_id,
            "name": self.name,
            "status": self.status.value,
            "drone_count": len(self.drones),
            "memory_drone": self.memory_drone,
            "meta_model": self.meta_model,
            "total_params_M": self.total_params_M,
        }

@dataclass


CerebrateInfo

脑虫信息 — 区域路由节点

类 CerebrateInfo 在 deploy/windows/swarm/core/types.py: 脑虫信息 — 区域路由节点 | 方法: to_dict

class CerebrateInfo:
    """脑虫信息 — 区域路由节点"""
    cerebrate_id: str                # 节点ID
    name: str                        # 区域名称
    domain: str = ""                 # 负责领域
    status: SwarmStatus = SwarmStatus.ACTIVE
    queens: List[str] = field(default_factory=list)  # 管辖虫后列表
    hive_endpoint: str = ""          # 上连虫巢端点
    routing_table: Dict = field(default_factory=dict)  # 路由表
    capacity: int = 100              # 最大并发
    current_load: int = 0            # 当前负载

    def to_dict(self) -> Dict:
        return {
            "cerebrate_id": self.cerebrate_id,
            "name": self.name,
            "domain": self.domain,
            "status": self.status.value,
            "queen_count": len(self.queens),
            "capacity": self.capacity,
            "current_load": self.current_load,
        }

@dataclass


HiveModelInfo

虫巢模型信息 — 中央大模型

类 HiveModelInfo 在 deploy/windows/swarm/core/types.py: 虫巢模型信息 — 中央大模型 | 方法: to_dict

class HiveModelInfo:
    """虫巢模型信息 — 中央大模型"""
    model_id: str                    # 模型标识
    name: str                        # 显示名称
    endpoint: str = ""               # API端点
    api_key: str = ""                # API密钥
    max_tokens: int = 4096
    avg_latency_ms: float = 0.0
    status: SwarmStatus = SwarmStatus.ACTIVE
    capabilities: List[str] = field(default_factory=list)  # 能力标签

    def to_dict(self) -> Dict:
        return {
            "model_id": self.model_id,
            "name": self.name,
            "endpoint": self.endpoint,
            "status": self.status.value,
            "capabilities": self.capabilities,
            "avg_latency_ms": self.avg_latency_ms,
        }

@dataclass


SwarmTask

虫群任务 — 最小调度单元

类 SwarmTask 在 deploy/windows/swarm/core/types.py: 虫群任务 — 最小调度单元 | 方法: to_dict

class SwarmTask:
    """虫群任务 — 最小调度单元"""
    task_id: str
    query: str                             # 原始查询
    user_id: str                           # 用户ID
    priority: TaskPriority = TaskPriority.NORMAL
    complexity: float = 0.0                # 复杂度 0~1
    subtasks: List[str] = field(default_factory=list)  # 子任务ID
    assigned_drones: List[str] = field(default_factory=list)
    results: Dict[str, Any] = field(default_factory=dict)  # drone_id -> result
    status: str = "pending"                # pending/running/done/failed
    created_at: datetime = field(default_factory=datetime.now)
    completed_at: Optional[datetime] = None

    def to_dict(self) -> Dict:
        return {
            "task_id": self.task_id,
            "query": self.query,
            "user_id": self.user_id,
            "priority": self.priority.value,
            "complexity": self.complexity,
            "assigned_drones": self.assigned_drones,
            "status": self.status,
        }

@dataclass


SwarmMessage

虫群通信消息 — 节点间传递

类 SwarmMessage 在 deploy/windows/swarm/core/types.py: 虫群通信消息 — 节点间传递 | 方法: to_dict

class SwarmMessage:
    """虫群通信消息 — 节点间传递"""
    msg_id: str
    sender: str                      # 发送者ID
    receiver: str                    # 接收者ID
    msg_type: str                    # 消息类型: route/result/discover/sync
    payload: Dict = field(default_factory=dict)
    timestamp: datetime = field(default_factory=datetime.now)
    ttl: int = 10                    # 跳数限制（防环路）

    def to_dict(self) -> Dict:
        return {
            "msg_id": self.msg_id,
            "sender": self.sender,
            "receiver": self.receiver,
            "msg_type": self.msg_type,
            "timestamp": self.timestamp.isoformat(),
        }

# ============================================================
# v7新增: 元模型分析结果
# ============================================================

@dataclass


SubTask

子任务 — 任务拆分后的最小执行单元

类 SubTask 在 deploy/windows/swarm/core/types.py: 子任务 — 任务拆分后的最小执行单元 | 方法: to_dict

class SubTask:
    """子任务 — 任务拆分后的最小执行单元"""
    subtask_id: str
    description: str                     # 子任务描述
    drone_type: DroneType = DroneType.CHAT  # 需要的子虫类型
    knowledge_domain: str = ""           # 知识领域
    priority: TaskPriority = TaskPriority.NORMAL
    assigned_model: str = ""             # 分配的模型ID
    status: str = "pending"              # pending/running/done/failed

    def to_dict(self) -> Dict:
        return {
            "subtask_id": self.subtask_id,
            "description": self.description,
            "drone_type": self.drone_type.value,
            "knowledge_domain": self.knowledge_domain,
            "priority": self.priority.value,
            "assigned_model": self.assigned_model,
            "status": self.status,
        }

@dataclass


TaskAnalysis

元模型分析结果 — 意图识别+任务拆分+路由决策

类 TaskAnalysis 在 deploy/windows/swarm/core/types.py: 元模型分析结果 — 意图识别+任务拆分+路由决策 | 方法: to_dict

class TaskAnalysis:
    """元模型分析结果 — 意图识别+任务拆分+路由决策"""
    query: str                            # 原始查询
    intent: str                           # 意图: chat/query/code/reasoning/memory/compute/multi
    complexity: float = 0.0               # 复杂度 0~1
    route: str = "cloud_hive"             # 路由: local_drone/memory/cloud_hive/multi_model/remote_queen
    assigned_model: str = ""              # 主模型ID
    subtasks: List[SubTask] = field(default_factory=list)
    confidence: float = 0.5               # 分析置信度
    requires_memory: bool = False         # 是否需要记忆检索
    knowledge_domains: List[str] = field(default_factory=list)  # 涉及的知识领域
    reasoning_chain: List[str] = field(default_factory=list)    # 推理链（调试用）

    def to_dict(self) -> Dict:
        return {
            "query": self.query,
            "intent": self.intent,
            "complexity": self.complexity,
            "route": self.route,
            "assigned_model": self.assigned_model,
            "subtask_count": len(self.subtasks),
            "confidence": self.confidence,
            "requires_memory": self.requires_memory,
            "knowledge_domains": self.knowledge_domains,
        }

# ============================================================
# v6兼容: 模型管理相关类型
# ============================================================


ModelType

类 ModelType 在 deploy/windows/swarm/core/types.py: 模型类型 | 方法:

class ModelType:
    """模型类型"""
    LOCAL = "local"       # 本地模型
    API = "api"           # API模型
    REMOTE = "remote"     # 远程模型


ModelStatus

类 ModelStatus 在 deploy/windows/swarm/core/types.py: 模型状态 | 方法:

class ModelStatus:
    """模型状态"""
    ACTIVE = "active"
    INACTIVE = "inactive"
    ERROR = "error"
    LOADING = "loading"


AggregationMethod

类 AggregationMethod 在 deploy/windows/swarm/core/types.py: 聚合策略 | 方法:

class AggregationMethod:
    """聚合策略"""
    CONFIDENCE = "confidence"     # 置信度优先
    VOTING = "voting"             # 投票法
    WEIGHTED = "weighted"         # 加权平均
    SEQUENTIAL = "sequential"     # 顺序精炼
    ADAPTIVE = "adaptive"         # 自适应


MemoryCategory

类 MemoryCategory 在 deploy/windows/swarm/core/types.py: 记忆类别 | 方法:

class MemoryCategory:
    """记忆类别"""
    GREETING = "greeting"          # 问候
    PERSONAL = "personal"          # 个人信息
    GENERAL = "general"            # 通用对话
    INFORMATION = "information"    # 信息/事实
    TASK = "task"                  # 任务相关
    CREATION = "creation"          # 创作内容
    CONVERSATION = "conversation"  # 对话记忆
    FACT = "fact"                  # 事实记忆
    PROCEDURE = "procedure"        # 过程记忆
    PREFERENCE = "preference"      # 偏好记忆
    EMOTION = "emotion"            # 情感记忆

@dataclass


ModelInfo

类 ModelInfo 在 deploy/windows/swarm/core/types.py: 模型信息 | 方法: is_local, is_api, to_dict

class ModelInfo:
    """模型信息"""
    model_id: str
    name: str
    model_type: ModelType = ModelType.LOCAL
    description: str = ""
    endpoint: str = ""
    api_key: str = ""
    default_confidence: float = 0.5
    max_tokens: int = 1024
    priority: int = 5
    tags: List[str] = field(default_factory=list)
    status: ModelStatus = ModelStatus.ACTIVE

    @property
    def is_local(self) -> bool:
        return self.model_type == ModelType.LOCAL

    @property
    def is_api(self) -> bool:
        return self.model_type == ModelType.API

    def to_dict(self) -> Dict:
        return {
            "model_id": self.model_id,
            "name": self.name,
            "model_type": self.model_type.value,
            "description": self.description,
            "default_confidence": self.default_confidence,
            "priority": self.priority,
            "tags": self.tags,
            "status": self.status.value,
        }

@dataclass