@claude-flow/shared

中文文档
3.0.8发布于 2026/11/09TypeScriptES Module近 30 天下载 29.8万

Shared types, event bus, config schemas and validators, MCP transport helpers and resilience utilities used by the Ruflo (claude-flow) V3 packages.

原始使用文档
文档目录17 节
  1. Quickstart
  2. Features
  3. Installation
  4. Quick Start
  5. Package Exports
  6. API Reference
  7. Types
  8. Core Interfaces
  9. Configuration
  10. Event System
  11. Hooks System
  12. MCP Infrastructure
  13. Health Monitor
  14. TypeScript Types
  15. Dependencies
  16. Used By
  17. License

@claude-flow/shared

Animated diagram: raw config is validated by Zod schemas into typed config that flows through the EventBus to other packages

@claude-flow/shared — Shared types, Zod config schemas and validators, the event bus and resilience helpers that the other @claude-flow packages build on.

Supported environments: Node.js 20+ · ESM · Linux, macOS, Windows (pure JavaScript)

Quickstart

npm install @claude-flow/shared
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(', '));

Expected output:

true 5 50
false priority: too_big

Next: @claude-flow/hooks builds its lifecycle hooks on these types.

npm version npm downloads License: MIT TypeScript Core

Shared utilities, types, and core infrastructure for Claude Flow V3 - the foundation module used by all other @claude-flow packages.

Features

  • Core Types - Agent, Task, Memory, MCP, and Swarm type definitions
  • Core Interfaces - Agent, Task, Memory, Event, and Coordinator interfaces
  • Configuration - Schema validation, loading, and default values
  • Event System - Event bus, coordinator, and handler utilities
  • Hooks System - Pre/post execution hooks for extensibility
  • MCP Infrastructure - Server, transport, connection pool, and tool registry
  • Health Monitoring - Health checks and monitoring utilities

Installation

npm install @claude-flow/shared

Quick Start

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

Package Exports

// 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 Reference

Types

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';

Core Interfaces

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>;
}

Configuration

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();

Event System

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() }
]);

Hooks System

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 Infrastructure

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

Health Monitor

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 Types

All types are fully exported and documented:

// 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';

Dependencies

  • sql.js - SQLite WASM for cross-platform persistence

Used By

This package is a dependency of all other @claude-flow modules:

License

MIT


Built by rUv · ruv.io · Source

版本与发布记录

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

版本发布日期距今
3.0.8latest2026/11/09今天
3.0.72026/11/045 天前
3.0.62026/10/2714 天前
3.0.52026/10/1328 天前
3.0.42026/10/1228 天前
3.0.32026/10/1129 天前

其他发布通道:v3alpha → 3.0.1,alpha → 3.0.1。

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

@claude-flow/shared 是什么?

Shared types, event bus, config schemas and validators, MCP transport helpers and resilience utilities used by the Ruflo (claude-flow) V3 packages.

如何安装 @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 和提交记录判断。