# @claude-flow/swarm 中文文档

规范地址：https://npmcn.com/package/%40claude-flow/swarm/

版本：3\.0\.5
npm 元数据更新时间：2026-11-09T21:47:10.084Z
中文译文更新时间：2026-11-10T00:11:56.730Z
软件包许可：未声明

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40claude-flow/swarm
原文对照：https://npmcn.com/package/%40claude-flow/swarm/?lang=original

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：1.1 MB，135 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2026-01-06T21:45:10.069Z
- 最新版本发布：2026-11-09T21:47:09.901Z
- 近 30 天下载量：3796（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：10（近 12 个月 10 个）

## 中文简介

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

## 安装

```sh
npm install @claude-flow/swarm
```

也可以使用：`pnpm add @claude-flow/swarm`、`yarn add @claude-flow/swarm`、`bun add @claude-flow/swarm`

## README

# @ claude- flow/ swarm (英语)

[![npm version](https://img.shields.io/npm/v/@claude-flow/swarm.svg)](https://www.npmjs.com/package/@claude-flow/swarm) [![npm downloads](https://img.shields.io/npm/dm/@claude-flow/swarm.svg)](https://www.npmjs.com/package/@claude-flow/swarm) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/) [![ADR-003](https://img.shields.io/badge/ADR--003-Compliant-green.svg)](https://github.com/ruvnet/claude-flow) [![Agents](https://img.shields.io/badge/Agents-Up%20to%20100+-orange.svg)](https://github.com/ruvnet/claude-flow)

> 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个代理架构是 **建议**,而不是硬限制:

```typescript
// 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 },
});
```

## 快速启动( 建议)

```typescript
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 测试、性能、部署 |

### 基于域的任务运行

```typescript
// 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`);
});
```

## 并行执行

为最大吞吐量同时执行多个域的任务 :

```typescript
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毫米口径 |

### 等级( 默认)

```typescript
const coordinator = createUnifiedSwarmCoordinator({
  topology: { type: 'hierarchical', maxAgents: 15 },
});
```

-   Queen代理坐标域线索
-   行业领导管理工人代理人
-   最适合域组织的 V3 架构

### 网点

```typescript
const coordinator = createUnifiedSwarmCoordinator({
  topology: { type: 'mesh', maxAgents: 20 },
});
```

-   有限的对等连接( 每个节点最大~ 10)
-   无中央协调员
-   20名代理人以下分配工作量的最佳办法

### 集中化

```typescript
const coordinator = createUnifiedSwarmCoordinator({
  topology: { type: 'centralized', maxAgents: 50 },
});
```

-   单一协调员中心管理所有代理
-   最简单的道理
-   对中小群而言最好

### 混合( 规模最佳)

```typescript
const coordinator = createUnifiedSwarmCoordinator({
  topology: { type: 'hybrid', maxAgents: 100 },
});
```

-   网络工人+等级协调员
-   将两种模式的好处结合起来
-   适用于大型企业部署的最佳方法

## 共识算法

选择代理商如何达成协议 :

### Raft (默认)

```typescript
const coordinator = createUnifiedSwarmCoordinator({
  consensus: { algorithm: 'raft', threshold: 0.66 },
});
```

-   以领导人为基础的共识
-   强有力的一致性保障
-   目标: < 100ms共识时间

### 拜占庭断层容忍

```typescript
const coordinator = createUnifiedSwarmCoordinator({
  consensus: { algorithm: 'byzantine', threshold: 0.66 },
});
```

-   处理恶意代理人
-   拜占庭断层承受能力
-   较高的间接费用,但更安全

### 八卦天后协议

```typescript
const coordinator = createUnifiedSwarmCoordinator({
  consensus: { algorithm: 'gossip', threshold: 0.66 },
});
```

-   最终一致性
-   低管理费用
-   对大群人来说最好

## 绩效目标

协调员根据V3性能要求进行了优化:

| 度量衡 | 目标 | 实际 |
| --- | --- | --- |
| 协调 | < 100 分钟 | 在测试中验证 |
| 协商一致时间 | < 100 分钟 | 在测试中验证 |
| 信件流量 | \> 1 000毫秒/秒 | 在测试中验证 |
| 代理使用 | \>85% | 通过平行执行实现 |

### 业绩监测

```typescript
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`,兼容层得到维护:

```typescript
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移徙

```typescript
// 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();
```

## 蜂窝式情报(女王协调员)

女王协调员提供智能任务协调:

```typescript
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个关注机制:

```typescript
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' });
```

## 联合会中心(交叉-流体协调)

用麻黄剂协调多组人:

```typescript
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,
});
```

## 高级特性

### 代理池管理

```typescript
// 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
```

### 自定义代理注册

```typescript
// 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`);
```

### 事件监测

```typescript
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相集,以提高能力:

```typescript
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:单一协调引擎. 贡献时 :

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

## 许可证

麻省理工学院

* * *

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

## 常见问题

### @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 和提交记录判断。

