@claude-flow/swarm

中文文档
3.0.5发布于 2026/11/10TypeScriptES Module零依赖近 30 天下载 3796

独立的群群协调 -- -- 最多100名代理人、4名地形、蜂窝、共识

中文使用文档
文档目录37 节
  1. 建筑(ADR-003)
  2. 关键部件
  3. * 代理计算:可配置,不有限
  4. 快速启动( 建议)
  5. 15 代理域架构
  6. 基于域的任务运行
  7. 并行执行
  8. 地形学支持
  9. 等级( 默认)
  10. 网点
  11. 集中化
  12. 混合( 规模最佳)
  13. 共识算法
  14. Raft (默认)
  15. 拜占庭断层容忍
  16. 八卦天后协议
  17. 绩效目标
  18. 业绩监测
  19. 后向相容性( SwarmHub)
  20. 从SwarmHub移徙
  21. 蜂窝式情报(女王协调员)
  22. 注意机制
  23. 联合会中心(交叉-流体协调)
  24. 高级特性
  25. 代理池管理
  26. 自定义代理注册
  27. 事件监测
  28. API 参考
  29. 统一星团协调员
  30. 与代理流合并@ alpha
  31. 可从代理流获取@ alpha
  32. 路线图:未来的加强
  33. 优先事项1(高影响)
  34. 优先事项2(中度影响)
  35. 优先事项3(拥有愉快)
  36. 捐款
  37. 许可证

@ claude- flow/ swarm (英语)

npm version npm downloads License: MIT TypeScript ADR-003 Agents

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),可达20020-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 有枪库/IPFSVia 桥免费分散协调
WASM 加速计划数HNSW 索引、语义路径

路线图:未来的加强

基于可集成的代理流@ alpha 能力:

优先事项1(高影响)

  • HTTP/2 的原生 QUIC 运输
  • 自动地形学的 Swarm 学习优化器
  • 免费 P2P 供应商集成( GunDB, IPFS)

优先事项2(中度影响)

  • WASM 加速成员索引
  • E2B 沙盒剂专门化
  • 附有燃料/燃料预算的强化信息类型

优先事项3(拥有愉快)

  • 高级八卦变体
  • CRDT 同步
  • 生产级 Ed25519/X25519 密码学

捐款

本单元沿用了ADR-003:单一协调引擎. 贡献时 :

  1. 所有协调逻辑 进去 UnifiedSwarmCoordinator
  2. 沼泽 是一个很薄的外表 - 没有新的逻辑
  3. 基于域的路由 应用于有组织的等级
  4. 业绩指标 必须保持( < 100ms 协调)
  5. 新特点 应通过扩展 API 集成

许可证

麻省理工学院


ADR-003 遵守情况: 本模块执行一个单相干协调引擎,具有蜂窝智能,6个关注机制,联邦支持,并通过外观模式实现后向相容.

版本与发布记录

@claude-flow/swarm 共发布 10 个版本,首次发布于 2026/01/07;过去 12 个月发布了 10 个版本。

版本发布日期距今
3.0.5latest2026/11/10今天
3.0.42026/11/028 天前
3.0.32026/11/028 天前
3.0.2v3alphaalpha2026/10/101 个月前
3.0.12026/10/081 个月前
3.0.02026/09/291 个月前

关于 @claude-flow/swarm 的常见问题

@claude-flow/swarm 是什么?

独立的群群协调 -- -- 最多100名代理人、4名地形、蜂窝、共识

如何安装 @claude-flow/swarm?

在项目目录运行 npm install @claude-flow/swarm,或使用 pnpm add / yarn add / bun add。

@claude-flow/swarm 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@claude-flow/swarm 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@claude-flow/swarm 可以商用吗?

@claude-flow/swarm 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@claude-flow/swarm 的下载量有多少?

根据 npm 官方下载统计,@claude-flow/swarm 在 2026/10/10 – 2026/11/08 这 30 天内被下载 3,796 次,日均约 127 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@claude-flow/swarm 还在维护吗?

最新版本 3.0.5 发布于 2026/11/10(今天);至今共发布 10 个版本,其中过去 12 个月发布了 10 个;首次发布于 2026/01/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。