# @claude-flow/shared 中文文档

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

版本：3\.0\.8
npm 元数据更新时间：2026-11-09T09:38:56.487Z
中文译文更新时间：2026-11-10T00:02:12.496Z
软件包许可：未声明

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

原始 npm 页面：https://www.npmjs.com/package/%40claude-flow/shared
原文对照：https://npmcn.com/package/%40claude-flow/shared/?lang=original
项目主页：https://ruv.io/
源码仓库：https://github.com/ruvnet/ruflo

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

- 包体积（解压后）：1.3 MB，306 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：7 个
- 首次发布：2026-01-06T21:43:55.107Z
- 最新版本发布：2026-11-09T09:38:56.245Z
- 近 30 天下载量：297863（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：12（近 12 个月 12 个）

## 中文简介

共享类型,事件总线,配置图和验证器,MCP运输辅助器和Ruflo(claude-flow)V3软件包使用的回弹功能.

## 安装

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

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

## README

# @ claude- flow/ 分享

![Animated diagram: raw config is validated by Zod schemas into typed config that flows through the EventBus to other packages](https://raw.githubusercontent.com/ruvnet/ruflo/main/v3/@claude-flow/shared/assets/shared-flow.svg)

**@ claude- flow/ 分享** 共享类型、 Zod 配置计划和验证器、 事件总线和复原辅助器 `@claude-flow` 软件包正在扩展.

**支持的环境 :** 节点.js 20+ → 无害环境管理 → Linux, macOS, Windows (纯 JavaScript)

## 快速启动

```bash
npm install @claude-flow/shared
```

```js
import { validateAgentConfig } from '@claude-flow/shared';

const ok = validateAgentConfig({ id: 'coder-1', name: 'Coder', type: 'coder' });
console.log(ok.success, ok.data.maxConcurrentTasks, ok.data.priority);

const bad = validateAgentConfig({ id: 'coder-1', name: 'Coder', type: 'coder', priority: 500 });
console.log(bad.success, bad.errors.map((e) => `${e.path}: ${e.code}`).join(', '));
```

预期产出:

```text
true 5 50
false priority: too_big
```

下一个 : [`@claude-flow/hooks`](https://www.npmjs.com/package/@claude-flow/hooks) 在这些种类上建立了它的生命周期钩.

[![npm version](https://img.shields.io/npm/v/@claude-flow/shared.svg)](https://www.npmjs.com/package/@claude-flow/shared) [![npm downloads](https://img.shields.io/npm/dm/@claude-flow/shared.svg)](https://www.npmjs.com/package/@claude-flow/shared) [![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/) [![Core](https://img.shields.io/badge/Module-Core-blue.svg)](https://github.com/ruvnet/claude-flow)

> Claude Flow V3的共享公用事业、类型和核心基础设施----所有其他@claude-flow包所使用的基础模块.

## 特征

-   **核心类型** - 代理、任务、记忆、MCP和Swarm类型定义
-   **核心接口** - 代理、任务、记忆、事件和协调员接口
-   **配置** - Schema 验证、加载和默认值
-   **事件系统** - 活动总线、协调员和搬运工
-   **钩子系统** - 执行前/执行后可延展性钩子
-   **MCP 基础设施** - 服务器、运输、连接池和工具登记册
-   **卫生监测** - 健康检查和监测公用事业

## 安装

```bash
npm install @claude-flow/shared
```

## 快速启动

```typescript
import {
  AgentState,
  TaskDefinition,
  MemoryEntry,
  EventBus,
  ConfigLoader
} from '@claude-flow/shared';

// Use shared types
const agent: AgentState = {
  id: { id: 'agent-1', swarmId: 'swarm-1', type: 'coder' },
  name: 'Code Agent',
  type: 'coder',
  status: 'idle'
};

// Use configuration
const config = await ConfigLoader.load('./config.json');

// Use event system
const eventBus = new EventBus();
eventBus.on('task.completed', (event) => {
  console.log(`Task ${event.taskId} completed`);
});
```

## 软件包导出

```typescript
// Main entry (recommended - includes all modules)
import { ... } from '@claude-flow/shared';

// Submodule exports (for tree-shaking or specific imports)
import { ... } from '@claude-flow/shared/types';      // Type definitions
import { ... } from '@claude-flow/shared/core';       // Config, interfaces, orchestrator
import { ... } from '@claude-flow/shared/events';     // Event sourcing (ADR-007)
import { ... } from '@claude-flow/shared/hooks';      // Hooks system
import { ... } from '@claude-flow/shared/mcp';        // MCP server infrastructure
import { ... } from '@claude-flow/shared/security';   // Security utilities
import { ... } from '@claude-flow/shared/resilience'; // Retry, circuit breaker, rate limiter
```

## API 参考

### 类型

```typescript
import type {
  // Agent types
  AgentId,
  AgentState,
  AgentType,
  AgentStatus,
  AgentCapabilities,
  AgentMetrics,

  // Task types
  TaskId,
  TaskDefinition,
  TaskType,
  TaskStatus,
  TaskPriority,

  // Memory types
  MemoryEntry,
  MemoryType,
  SearchResult,

  // Swarm types
  SwarmId,
  SwarmStatus,
  SwarmEvent,
  CoordinatorConfig,

  // MCP types
  MCPTool,
  MCPRequest,
  MCPResponse
} from '@claude-flow/shared/types';
```

### 核心接口

```typescript
import type {
  IAgent,
  ITask,
  IMemory,
  ICoordinator,
  IEventHandler
} from '@claude-flow/shared/core';

// Agent interface
interface IAgent {
  getId(): AgentId;
  getState(): AgentState;
  execute(task: TaskDefinition): Promise<TaskResult>;
  handleMessage(message: Message): Promise<void>;
}

// Memory interface
interface IMemory {
  store(entry: MemoryEntry): Promise<string>;
  retrieve(id: string): Promise<MemoryEntry | null>;
  search(query: SearchQuery): Promise<SearchResult[]>;
  delete(id: string): Promise<boolean>;
}

// Coordinator interface
interface ICoordinator {
  initialize(): Promise<void>;
  shutdown(): Promise<void>;
  registerAgent(agent: IAgent): Promise<string>;
  submitTask(task: TaskDefinition): Promise<string>;
}
```

### 配置

```typescript
import {
  ConfigLoader,
  ConfigValidator,
  defaultConfig,
  ConfigSchema
} from '@claude-flow/shared/core';

// Load configuration
const config = await ConfigLoader.load('./config.json');
const config2 = await ConfigLoader.loadFromEnv();

// Validate configuration
const errors = ConfigValidator.validate(config);
if (errors.length > 0) {
  console.error('Invalid config:', errors);
}

// Default configuration
const defaults = defaultConfig();
```

### 事件系统

```typescript
import { EventBus, EventCoordinator } from '@claude-flow/shared/events';

const eventBus = new EventBus();

// Subscribe to events
eventBus.on('agent.joined', (event) => {
  console.log(`Agent ${event.agentId} joined`);
});

eventBus.on('task.*', (event) => {
  console.log(`Task event: ${event.type}`);
});

// Emit events
eventBus.emit({
  type: 'task.completed',
  taskId: 'task-1',
  result: { success: true }
});

// Event coordinator for complex workflows
const coordinator = new EventCoordinator();
coordinator.orchestrate([
  { event: 'step1.done', handler: () => startStep2() },
  { event: 'step2.done', handler: () => startStep3() }
]);
```

### 钩子系统

```typescript
import { HooksManager, Hook } from '@claude-flow/shared/hooks';

const hooks = new HooksManager();

// Register pre-execution hook
hooks.register('pre:task', async (context) => {
  console.log(`Starting task: ${context.taskId}`);
  return { ...context, startTime: Date.now() };
});

// Register post-execution hook
hooks.register('post:task', async (context, result) => {
  const duration = Date.now() - context.startTime;
  console.log(`Task completed in ${duration}ms`);
});

// Execute with hooks
const result = await hooks.execute('task', context, async (ctx) => {
  return await runTask(ctx);
});
```

### MCP 基础设施

```typescript
import {
  createMCPServer,
  createToolRegistry,
  createConnectionPool,
  createSessionManager,
  defineTool,
  quickStart,
} from '@claude-flow/shared/mcp';

// Quick start - simplest way to create an MCP server
const server = await quickStart({
  transport: 'stdio',
  name: 'My MCP Server',
});

// Tool registry
const registry = createToolRegistry();
registry.register(defineTool({
  name: 'swarm_init',
  description: 'Initialize a swarm',
  inputSchema: { type: 'object', properties: { topology: { type: 'string' } } },
  handler: async (params) => ({ result: 'initialized' }),
}));

// Connection pool
const pool = createConnectionPool({
  maxConnections: 10,
  acquireTimeoutMs: 30000,
});

// Session manager
const sessions = createSessionManager({ timeoutMs: 3600000 });
const session = await sessions.create({ clientInfo: { name: 'client' } });
```

### 卫生监测

```typescript
import { HealthMonitor, HealthCheck } from '@claude-flow/shared/core';

const monitor = new HealthMonitor();

// Register health checks
monitor.register('database', async () => {
  const connected = await db.ping();
  return { healthy: connected, latency: pingTime };
});

monitor.register('memory', async () => {
  const usage = process.memoryUsage();
  return { healthy: usage.heapUsed < MAX_HEAP, usage };
});

// Run health checks
const report = await monitor.check();
// { overall: 'healthy', checks: { database: {...}, memory: {...} } }
```

## 类型脚本

所有类型均全部出口并记录在案:

```typescript
// Re-export all types
export * from './types/agent.types';
export * from './types/task.types';
export * from './types/memory.types';
export * from './types/swarm.types';
export * from './types/mcp.types';
```

## 依赖关系

-   `sql.js` - SQLite WASM 用于跨平台持久性

## 用户

此软件包是所有其它 @ claude- flow 模块的依赖 :

-   [@claude-flow/cli (英语)](https://npmcn.com/package/%40claude-flow/cli) - CLI模块
-   [@ claude- flow/ 安全](https://npmcn.com/package/%40claude-flow/security) - 安全和验证
-   [@ claude- flow/ 记忆](https://npmcn.com/package/%40claude-flow/memory) - AgentDB & HNSW 索引
-   [@ claude- flow/ 神经](https://npmcn.com/package/%40claude-flow/neural) - SONA学习和RL算法
-   [@ claude- flow/ 性能](https://npmcn.com/package/%40claude-flow/performance) - 基准和优化
-   [@ claude- flow/ swarm (英语)](https://npmcn.com/package/%40claude-flow/swarm) - 15名代理人的协调
-   [@ claude- flow/ 合并](https://npmcn.com/package/%40claude-flow/integration) - 代理流量@ alpha 桥
-   [@ claude- flow/ 测试](https://npmcn.com/package/%40claude-flow/testing) - TDD框架和固定装置
-   [@ claude- flow/ 部署](https://npmcn.com/package/%40claude-flow/deployment) - 发行管理
-   [@ claude- flow/ 嵌入](https://npmcn.com/package/%40claude-flow/embeddings) - 嵌入服务
-   [@ claude- flow/ hooks](https://npmcn.com/package/%40claude-flow/hooks) - 虎克系统

## 许可证

麻省理工学院

* * *

由 [尔 紫外线](https://ruv.io/) • 妇女 [卢夫.io](https://ruv.io/) • 妇女 [来源](https://github.com/ruvnet/ruflo/tree/main/v3/@claude-flow/shared)

## 常见问题

### @claude-flow/shared 是什么？

共享类型,事件总线,配置图和验证器,MCP运输辅助器和Ruflo\(claude-flow\)V3软件包使用的回弹功能\.

### 如何安装 @claude-flow/shared？

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

### @claude-flow/shared 支持 TypeScript 吗？

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

### @claude-flow/shared 支持 ESM 还是 CommonJS？

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

### @claude-flow/shared 可以商用吗？

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

### @claude-flow/shared 的下载量有多少？

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

### @claude-flow/shared 还在维护吗？

最新版本 3\.0\.8 发布于 2026/11/09（今天）；至今共发布 12 个版本，其中过去 12 个月发布了 12 个；首次发布于 2026/01/07。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

