@ claude- flow/ swarm (英语)
V3 实施ADR-003的统一Swarm协调模块:有蜂窝智能的单一协调引擎
建筑(ADR-003)
本单元提供 完整的多代理协调系统 具有蜂窝照料能力:
关键部件
@claude-flow/swarm
├── UnifiedSwarmCoordinator ⭐ CANONICAL ENGINE
│ ├── Configurable agent count (default 15, max 100+)
│ ├── Domain-based task routing
│ ├── Parallel execution across domains
│ ├── Multiple consensus algorithms
│ ├── 4 topology types (mesh, hierarchical, centralized, hybrid)
│ └── Performance: <100ms coordination
│
├── QueenCoordinator 👑 HIVE-MIND INTELLIGENCE
│ ├── Strategic task analysis & decomposition
│ ├── Agent capability-based delegation
│ ├── Swarm health monitoring & bottleneck detection
│ ├── 5 consensus types (majority, supermajority, unanimous, weighted, queen-override)
│ └── Learning from outcomes
│
├── AttentionCoordinator 🧠 ATTENTION MECHANISMS
│ ├── Flash Attention (2.49x-7.47x speedup)
│ ├── Multi-Head Attention (8 heads)
│ ├── Linear Attention (O(n) complexity)
│ ├── Hyperbolic Attention (Poincaré hierarchies)
│ ├── Mixture of Experts (MoE) routing
│ └── GraphRoPE (topology-aware positioning)
│
├── FederationHub 🌐 CROSS-SWARM COORDINATION
│ ├── Ephemeral agent spawning with TTL
│ ├── Cross-swarm messaging
│ ├── Federation-wide consensus voting
│ └── Auto-cleanup & heartbeat tracking
│
├── ConsensusEngines 🗳️ DISTRIBUTED AGREEMENT
│ ├── Raft (leader election, log replication)
│ ├── Byzantine (fault-tolerant, 2/3 supermajority)
│ └── Gossip (epidemic protocol for large swarms)
│
└── SwarmHub (deprecated) - Thin facade for backward compatibility
* 代理计算:可配置,不有限
默认的15个代理架构是 建议,而不是硬限制:
// Default: 15-agent V3 architecture
const coordinator = createUnifiedSwarmCoordinator({
topology: { type: 'hierarchical', maxAgents: 15 },
});
// Scale up: 50 agents
const largeCoordinator = createUnifiedSwarmCoordinator({
topology: { type: 'mesh', maxAgents: 50 },
});
// Maximum: 100+ agents (DEFAULT_MAX_AGENTS = 100)
const enterpriseCoordinator = createUnifiedSwarmCoordinator({
topology: { type: 'hybrid', maxAgents: 100 },
});
快速启动( 建议)
import { createUnifiedSwarmCoordinator } from '@claude-flow/swarm';
// Create coordinator
const coordinator = createUnifiedSwarmCoordinator({
topology: { type: 'hierarchical', maxAgents: 15 },
consensus: { algorithm: 'raft', threshold: 0.66 },
});
// Initialize
await coordinator.initialize();
// Spawn 15-agent hierarchy
const agents = await coordinator.spawnFullHierarchy();
console.log(`Spawned ${agents.size} agents across 5 domains`);
// Submit tasks to specific domains
const securityTaskId = await coordinator.submitTask({
type: 'review',
name: 'CVE Security Audit',
priority: 'critical',
maxRetries: 3,
});
await coordinator.assignTaskToDomain(securityTaskId, 'security');
// Parallel execution across domains
const results = await coordinator.executeParallel([
{ task: { type: 'coding', name: 'Core Implementation' }, domain: 'core' },
{ task: { type: 'testing', name: 'Security Tests' }, domain: 'security' },
{ task: { type: 'documentation', name: 'API Docs' }, domain: 'integration' },
]);
console.log(`Completed ${results.filter(r => r.success).length} tasks in parallel`);
// Get swarm status
const status = coordinator.getStatus();
console.log('Domain Status:', status.domains);
console.log('Metrics:', status.metrics);
// Shutdown
await coordinator.shutdown();
15 代理域架构
协调员管理5个有具体代理任务的领域:
| 域名 | 探员 | 能力 |
|---|---|---|
| 皇后 | 1个 | 高层协调、共识、规划 |
| 警卫 | 2至4岁 | 安全结构、CVE修复、威胁模型 |
| 核心 | 第5-9页 | DDD 设计,内存统一,类型现代化 |
| 一体化 | 第10-12条 | 活性流动融合、CLI、神经特征 |
| 支助 | 13-15 (中文(简体) ) | TDD 测试、性能、部署 |
基于域的任务运行
// Route tasks to optimal domains
await coordinator.assignTaskToDomain(securityTask, 'security');
await coordinator.assignTaskToDomain(coreTask, 'core');
await coordinator.assignTaskToDomain(integrationTask, 'integration');
// Get agents by domain
const securityAgents = coordinator.getAgentsByDomain('security');
console.log(`Security domain has ${securityAgents.length} agents`);
// Get domain status
const status = coordinator.getStatus();
status.domains.forEach(domain => {
console.log(`${domain.name}: ${domain.availableAgents}/${domain.agentCount} available`);
});
并行执行
为最大吞吐量同时执行多个域的任务 :
const tasks = [
{ task: { type: 'coding', name: 'Implement Auth' }, domain: 'core' },
{ task: { type: 'testing', name: 'Security Tests' }, domain: 'security' },
{ task: { type: 'review', name: 'Code Review' }, domain: 'support' },
];
const results = await coordinator.executeParallel(tasks);
// Check results
results.forEach(result => {
if (result.success) {
console.log(`✅ ${result.domain}: ${result.durationMs}ms`);
} else {
console.error(`❌ ${result.domain}: ${result.error?.message}`);
}
});
地形学支持
选择适合您需要的协调模式 :
| 地形学 | 最佳服务 | 可缩放性 | 延迟 |
|---|---|---|---|
| 等级 | 女王所带领的人群 | O(n),最多100+ | 15-35毫米口径 |
| 网点 | 分配的工作量 | O(n2),最多20个 | 10-40分钟 |
| 集中化 | 简单的协调 | O(n),最多50个 | 10-20毫米口径 |
| 混合 | 大型混合工作量 | O(n),可达200 | 20-50毫米口径 |
等级( 默认)
const coordinator = createUnifiedSwarmCoordinator({
topology: { type: 'hierarchical', maxAgents: 15 },
});
- Queen代理坐标域线索
- 行业领导管理工人代理人
- 最适合域组织的 V3 架构
网点
const coordinator = createUnifiedSwarmCoordinator({
topology: { type: 'mesh', maxAgents: 20 },
});
- 有限的对等连接( 每个节点最大~ 10)
- 无中央协调员
- 20名代理人以下分配工作量的最佳办法
集中化
const coordinator = createUnifiedSwarmCoordinator({
topology: { type: 'centralized', maxAgents: 50 },
});
- 单一协调员中心管理所有代理
- 最简单的道理
- 对中小群而言最好
混合( 规模最佳)
const coordinator = createUnifiedSwarmCoordinator({
topology: { type: 'hybrid', maxAgents: 100 },
});
- 网络工人+等级协调员
- 将两种模式的好处结合起来
- 适用于大型企业部署的最佳方法
共识算法
选择代理商如何达成协议 :
Raft (默认)
const coordinator = createUnifiedSwarmCoordinator({
consensus: { algorithm: 'raft', threshold: 0.66 },
});
- 以领导人为基础的共识
- 强有力的一致性保障
- 目标: < 100ms共识时间
拜占庭断层容忍
const coordinator = createUnifiedSwarmCoordinator({
consensus: { algorithm: 'byzantine', threshold: 0.66 },
});
- 处理恶意代理人
- 拜占庭断层承受能力
- 较高的间接费用,但更安全
八卦天后协议
const coordinator = createUnifiedSwarmCoordinator({
consensus: { algorithm: 'gossip', threshold: 0.66 },
});
- 最终一致性
- 低管理费用
- 对大群人来说最好
绩效目标
协调员根据V3性能要求进行了优化:
| 度量衡 | 目标 | 实际 |
|---|---|---|
| 协调 | < 100 分钟 | 在测试中验证 |
| 协商一致时间 | < 100 分钟 | 在测试中验证 |
| 信件流量 | > 1 000毫秒/秒 | 在测试中验证 |
| 代理使用 | >85% | 通过平行执行实现 |
业绩监测
const report = coordinator.getPerformanceReport();
console.log('Coordination Latency:', {
p50: report.coordinationLatencyP50,
p99: report.coordinationLatencyP99,
});
console.log('Throughput:', {
messagesPerSec: report.messagesPerSecond,
tasksPerSec: report.taskThroughput,
});
console.log('Utilization:', {
agentUtilization: report.agentUtilization,
consensusSuccessRate: report.consensusSuccessRate,
});
后向相容性( SwarmHub)
对于使用的现有代码 SwarmHub,兼容层得到维护:
import { createSwarmHub } from '@claude-flow/swarm';
// ⚠️ DEPRECATED: Use createUnifiedSwarmCoordinator() instead
const hub = createSwarmHub();
await hub.initialize();
// SwarmHub delegates all operations to UnifiedSwarmCoordinator
const coordinator = hub.getCoordinator();
// Use coordinator for advanced features
await coordinator.executeParallel(tasks);
从SwarmHub移徙
// OLD (deprecated)
import { createSwarmHub } from '@claude-flow/swarm';
const hub = createSwarmHub();
await hub.initialize();
await hub.spawnAllAgents();
// NEW (recommended)
import { createUnifiedSwarmCoordinator } from '@claude-flow/swarm';
const coordinator = createUnifiedSwarmCoordinator();
await coordinator.initialize();
await coordinator.spawnFullHierarchy();
蜂窝式情报(女王协调员)
女王协调员提供智能任务协调:
import { createQueenCoordinator } from '@claude-flow/swarm';
const queen = createQueenCoordinator({
swarmCoordinator: coordinator,
// Optional: connect to neural learning system
// neuralSystem: myNeuralSystem,
// memoryService: myMemoryService,
});
// Analyze a complex task
const analysis = await queen.analyzeTask({
id: 'task-1',
type: 'security-audit',
description: 'Comprehensive CVE audit of authentication system',
});
console.log('Task Analysis:', {
complexity: analysis.complexity, // 'low' | 'medium' | 'high' | 'critical'
estimatedDuration: analysis.estimatedDuration,
requiredCapabilities: analysis.requiredCapabilities,
suggestedSubtasks: analysis.subtasks,
});
// Delegate to optimal agents
const plan = await queen.delegateToAgents(task, analysis);
console.log('Delegation Plan:', {
primaryAgent: plan.primaryAgent,
backupAgents: plan.backupAgents,
parallelAssignments: plan.parallelAssignments,
});
// Monitor swarm health
const health = await queen.monitorSwarmHealth();
console.log('Health Report:', {
overallStatus: health.status,
bottlenecks: health.bottlenecks,
alerts: health.alerts,
recommendations: health.recommendations,
});
// Coordinate consensus with 5 types
const decision = await queen.coordinateConsensus({
type: 'deployment',
value: { version: '3.0.0', environment: 'production' },
consensusType: 'supermajority', // 'majority' | 'supermajority' | 'unanimous' | 'weighted' | 'queen-override'
});
注意机制
智能剂协调6个关注机制:
import { createAttentionCoordinator } from '@claude-flow/swarm';
const attention = createAttentionCoordinator({
topology: coordinator.getTopology(),
});
// Flash Attention - 2.49x-7.47x speedup for long sequences
const flashResult = await attention.coordinate(agents, task, { type: 'flash' });
// Multi-Head Attention - 8 parallel attention heads
const multiHeadResult = await attention.coordinate(agents, task, { type: 'multi-head' });
// Linear Attention - O(n) complexity for very long sequences
const linearResult = await attention.coordinate(agents, task, { type: 'linear' });
// Hyperbolic Attention - Poincaré distance for hierarchies
const hyperbolicResult = await attention.coordinate(agents, task, { type: 'hyperbolic' });
// Mixture of Experts - Route to top-k best agents
const moeResult = await attention.coordinate(agents, task, {
type: 'moe',
topK: 3,
loadBalancing: true,
});
// GraphRoPE - Topology-aware position encoding
const graphResult = await attention.coordinate(agents, task, { type: 'graph-rope' });
联合会中心(交叉-流体协调)
用麻黄剂协调多组人:
import { createFederationHub, getDefaultFederationHub } from '@claude-flow/swarm';
// Get singleton hub or create custom
const hub = getDefaultFederationHub();
// or: const hub = createFederationHub({ maxSwarms: 10 });
// Register swarms
await hub.registerSwarm('swarm-security', {
coordinator: securityCoordinator,
capabilities: ['security-audit', 'penetration-testing'],
});
await hub.registerSwarm('swarm-dev', {
coordinator: devCoordinator,
capabilities: ['coding', 'testing', 'review'],
});
// Spawn ephemeral agent (auto-cleanup after TTL)
const { agentId } = await hub.spawnEphemeral({
swarmId: 'swarm-security',
ttlMs: 300000, // 5 minutes
task: { type: 'quick-audit', target: 'auth-module' },
});
// Cross-swarm messaging
await hub.sendMessage({
from: 'swarm-dev',
to: 'swarm-security',
type: 'audit-request',
payload: { module: 'auth', priority: 'high' },
});
// Federation-wide consensus
const vote = await hub.proposeConsensus({
topic: 'release-v3',
options: ['approve', 'reject', 'defer'],
timeout: 30000,
});
// Get federation stats
const stats = hub.getStats();
console.log('Federation:', {
swarms: stats.swarmCount,
ephemeralAgents: stats.ephemeralAgentCount,
messagesSent: stats.messageCount,
});
高级特性
代理池管理
// Get domain-specific pool
const corePool = coordinator.getDomainPool('core');
const stats = corePool?.getPoolStats();
console.log('Core Domain Pool:', {
total: stats?.total,
available: stats?.available,
busy: stats?.busy,
});
// Auto-scaling is built-in
// - Scale up at 80% utilization
// - Scale down at 20% utilization
自定义代理注册
// Register agent with automatic domain assignment
const { agentId, domain } = await coordinator.registerAgentWithDomain(
{
name: 'security-agent-2',
type: 'specialist',
status: 'idle',
capabilities: {
codeReview: true,
securityAudit: true,
},
// ... other agent properties
},
2 // Agent number 2 → security domain
);
console.log(`Registered ${agentId} in ${domain} domain`);
事件监测
coordinator.on('agent.joined', (event) => {
console.log('Agent joined:', event.data.agentId);
});
coordinator.on('task.completed', (event) => {
console.log('Task completed:', event.data.taskId);
});
coordinator.on('consensus.achieved', (event) => {
console.log('Consensus achieved:', event.data.approvalRate);
});
coordinator.on('swarm.initialized', (event) => {
console.log('Swarm initialized:', event.data.swarmId);
});
API 参考
统一星团协调员
生命周期
initialize(): Promise<void>- 启动协调员shutdown(): Promise<void>- 关闭协调员pause(): Promise<void>- 暂停操作resume(): Promise<void>- 恢复作业
代理管理
registerAgent(agent): Promise<string>- 注册代理人registerAgentWithDomain(agent, number): Promise<{agentId, domain}>- 有域名的登记册unregisterAgent(id): Promise<void>- 未注册代理人spawnFullHierarchy(): Promise<Map<number, {agentId, domain}>>- 15个特工getAgent(id): AgentState | undefined-通过身份证明找到特工getAllAgents(): AgentState[]- 找所有探员getAgentsByDomain(domain): AgentState[]- 让特工进入域内
任务管理
submitTask(task): Promise<string>- 提交任务assignTaskToDomain(taskId, domain): Promise<string | undefined>- 指定域executeParallel(tasks): Promise<ParallelExecutionResult[]>- 平行执行cancelTask(taskId): Promise<void>- 取消任务getTask(id): TaskDefinition | undefined-通过身份证获得任务
协调
proposeConsensus(value): Promise<ConsensusResult>- 建议协商一致broadcastMessage(payload, priority): Promise<void>- 广播信息
监测
getState(): CoordinatorState- 获取当前状态getMetrics(): CoordinatorMetrics- 获得度量衡getPerformanceReport(): PerformanceReport- 获取性能数据getStatus(): {swarmId, status, domains, metrics}- 获得全面地位
与代理流合并@ alpha
本模块可与代理- flow@alpha相集,以提高能力:
import { createUnifiedSwarmCoordinator } from '@claude-flow/swarm';
import { AgenticFlowBridge } from '@claude-flow/integration';
// Connect to agentic-flow for enhanced features
const bridge = new AgenticFlowBridge({
agenticFlow: { version: 'alpha' },
});
const coordinator = createUnifiedSwarmCoordinator({
topology: { type: 'hierarchical', maxAgents: 15 },
// Enable agentic-flow features via bridge
extensions: {
transport: bridge.getQuicTransport(), // QUIC 0-RTT
learning: bridge.getSwarmLearningOptimizer(),
},
});
可从代理流获取@ alpha
| 特性 | 状态 | 说明 |
|---|---|---|
| QUIC 运输 | Via 桥 | 0-RTT连接,速度快50-70% |
| Swarm 学习优化器 | Via 桥 | 自动地形学建议 |
| E2B 沙盒代理工具 | Via 桥 | 隔离执行环境 |
| P2P 有枪库/IPFS | Via 桥 | 免费分散协调 |
| WASM 加速 | 计划数 | HNSW 索引、语义路径 |
路线图:未来的加强
基于可集成的代理流@ alpha 能力:
优先事项1(高影响)
- HTTP/2 的原生 QUIC 运输
- 自动地形学的 Swarm 学习优化器
- 免费 P2P 供应商集成( GunDB, IPFS)
优先事项2(中度影响)
- WASM 加速成员索引
- E2B 沙盒剂专门化
- 附有燃料/燃料预算的强化信息类型
优先事项3(拥有愉快)
- 高级八卦变体
- CRDT 同步
- 生产级 Ed25519/X25519 密码学
捐款
本单元沿用了ADR-003:单一协调引擎. 贡献时 :
- 所有协调逻辑 进去
UnifiedSwarmCoordinator - 沼泽 是一个很薄的外表 - 没有新的逻辑
- 基于域的路由 应用于有组织的等级
- 业绩指标 必须保持( < 100ms 协调)
- 新特点 应通过扩展 API 集成
许可证
麻省理工学院
ADR-003 遵守情况: 本模块执行一个单相干协调引擎,具有蜂窝智能,6个关注机制,联邦支持,并通过外观模式实现后向相容.