🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
checkpoint: File edit:
rUv7900aea3b701
diff --git a/.claude/settings.json b/.claude/settings.jsonindex cb8195518b..43e1809141 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -73,7 +73,7 @@{"type": "command","timeout": 5000,- "command": ".claude/helpers/guidance-hooks.sh pre-edit \"$TOOL_INPUT_file_path\" 2>/dev/null || true"+ "command": "/workspaces/claude-flow/.claude/helpers/guidance-hooks.sh pre-edit \"$TOOL_INPUT_file_path\" 2>/dev/null || true"}]},diff --git a/v3/.agentic-flow/intelligence.json b/v3/.agentic-flow/intelligence.jsonindex b7600d8748..a99e191298 100644--- a/v3/.agentic-flow/intelligence.json+++ b/v3/.agentic-flow/intelligence.json@@ -1,7 +1,7 @@{"patterns": {"command:": {- "success": 0.5217031000000001,+ "success": 0.7458134171671,"failure": -0.05}},@@ -10,8 +10,8 @@"dirPatterns": {},"errorPatterns": [],"metrics": {- "totalRoutes": 9,- "successfulRoutes": 8,+ "totalRoutes": 15,+ "successfulRoutes": 14,"routingHistory": [{"timestamp": "2026-01-04T17:04:00.672Z",diff --git a/v3/@claude-flow/memory/src/agentdb-backend.ts b/v3/@claude-flow/memory/src/agentdb-backend.tsindex 17166ac6a6..1924f77c20 100644--- a/v3/@claude-flow/memory/src/agentdb-backend.ts+++ b/v3/@claude-flow/memory/src/agentdb-backend.ts@@ -815,8 +815,8 @@ export class AgentDBBackend extends EventEmitter implements IMemoryBackend {for (const entry of this.entries.values()) {if (!entry.embedding) continue;- const distance = this.cosineSimilarity(embedding, entry.embedding);- const score = 1 - distance;+ const score = this.cosineSimilarity(embedding, entry.embedding);+ const distance = 1 - score;if (options.threshold && score < options.threshold) continue;@@ -965,7 +965,7 @@ export class AgentDBBackend extends EventEmitter implements IMemoryBackend {}/**- * Cosine similarity+ * Cosine similarity (returns value in range [0, 1] where 1 = identical)*/private cosineSimilarity(a: Float32Array, b: Float32Array): number {let dotProduct = 0;@@ -978,7 +978,8 @@ export class AgentDBBackend extends EventEmitter implements IMemoryBackend {normB += b[i] * b[i];}- return 1 - dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));+ const magnitude = Math.sqrt(normA) * Math.sqrt(normB);+ return magnitude === 0 ? 0 : dotProduct / magnitude;}/**diff --git a/v3/@claude-flow/plugins/examples/ruvector-plugins/shared/index.ts b/v3/@claude-flow/plugins/examples/ruvector-plugins/shared/index.tsnew file mode 100644index 0000000000..219588eafd--- /dev/null+++ b/v3/@claude-flow/plugins/examples/ruvector-plugins/shared/index.ts@@ -0,0 +1,20 @@+/**+ * Shared utilities for RuVector plugins+ */++export {+ // Interfaces+ IVectorDB,+ ILoRAEngine,+ LoRAAdapter,+ // Fallback implementations+ FallbackVectorDB,+ FallbackLoRAEngine,+ // Factory functions+ createVectorDB,+ createLoRAEngine,+ // Utilities+ cosineSimilarity,+ generateHashEmbedding,+ LazyInitializable,+} from './vector-utils.js';diff --git a/v3/@claude-flow/plugins/examples/ruvector-plugins/shared/vector-utils.ts b/v3/@claude-flow/plugins/examples/ruvector-plugins/shared/vector-utils.tsnew file mode 100644index 0000000000..ef62b43e54--- /dev/null+++ b/v3/@claude-flow/plugins/examples/ruvector-plugins/shared/vector-utils.ts@@ -0,0 +1,257 @@+/**+ * Shared Vector Database Utilities+ *+ * Consolidated implementations for all RuVector plugins.+ */++// ============================================================================+// Interfaces+// ============================================================================++/**+ * Vector database interface for HNSW operations+ */+export interface IVectorDB {+ insert(vector: Float32Array, id: string, metadata?: Record<string, unknown>): string;+ search(query: Float32Array, k: number, filter?: Record<string, unknown>): Array<{+ id: string;+ score: number;+ metadata?: Record<string, unknown>;+ }>;+ get?(id: string): { vector: Float32Array; metadata: Record<string, unknown> } | null;+ delete(id: string): boolean;+ size(): number;+}++/**+ * LoRA engine interface for neural adaptation+ */+export interface ILoRAEngine {+ createAdapter(category: string, rank: number): Promise<LoRAAdapter>;+ updateAdapter(adapterId: string, gradient: Float32Array, learningRate: number): Promise<void>;+ applyEWC?(adapterId: string, lambda: number): Promise<void>;+ computeGradient(input: Float32Array, target: Float32Array): Float32Array;+}++export interface LoRAAdapter {+ id: string;+ category: string;+ rank: number;+ alpha: number;+}++// ============================================================================+// Fallback Implementations+// ============================================================================++/**+ * Fallback vector database when @ruvector/wasm is not available.+ * Uses in-memory Map with brute-force cosine similarity search.+ */+export class FallbackVectorDB implements IVectorDB {+ private vectors = new Map<string, { vector: Float32Array; metadata: Record<string, unknown> }>();++ constructor(private dimensions: number) {}++ insert(vector: Float32Array, id: string, metadata: Record<string, unknown> = {}): string {+ this.vectors.set(id, { vector, metadata });+ return id;+ }++ search(query: Float32Array, k: number): Array<{ id: string; score: number; metadata?: Record<string, unknown> }> {+ const results: Array<{ id: string; score: number; metadata?: Record<string, unknown> }> = [];++ for (const [id, entry] of this.vectors) {+ const score = cosineSimilarity(query, entry.vector);+ results.push({ id, score, metadata: entry.metadata });+ }++ return results.sort((a, b) => b.score - a.score).slice(0, k);+ }++ get(id: string): { vector: Float32Array; metadata: Record<string, unknown> } | null {+ return this.vectors.get(id) ?? null;+ }++ delete(id: string): boolean {+ return this.vectors.delete(id);+ }++ size(): number {+ return this.vectors.size;+ }+}++/**+ * Fallback LoRA engine when @ruvector/learning-wasm is not available.+ * Uses simple gradient descent with in-memory weights.+ */+export class FallbackLoRAEngine implements ILoRAEngine {+ private adapters = new Map<string, LoRAAdapter>();+ private adapterWeights = new Map<string, Float32Array>();+ private nextId = 1;++ async createAdapter(category: string, rank: number): Promise<LoRAAdapter> {+ const adapter: LoRAAdapter = {+ id: `adapter-${this.nextId++}`,+ category,+ rank,+ alpha: 16,+ };+ this.adapters.set(adapter.id, adapter);+ this.adapterWeights.set(adapter.id, new Float32Array(rank * 768));+ return adapter;+ }++ async updateAdapter(adapterId: string, gradient: Float32Array, learningRate: number): Promise<void> {+ const weights = this.adapterWeights.get(adapterId);+ if (weights) {+ const len = Math.min(weights.length, gradient.length);+ for (let i = 0; i < len; i++) {+ weights[i] -= learningRate * gradient[i];+ }+ }+ }++ async applyEWC(adapterId: string, lambda: number): Promise<void> {+ const weights = this.adapterWeights.get(adapterId);+ if (weights) {+ for (let i = 0; i < weights.length; i++) {+ weights[i] *= 1 - lambda * 0.01;+ }+ }+ }++ computeGradient(input: Float32Array, target: Float32Array): Float32Array {+ const gradient = new Float32Array(input.length);+ for (let i = 0; i < input.length; i++) {+ gradient[i] = (input[i] - (target[i] || 0)) * 0.01;+ }+ return gradient;+ }+}++// ============================================================================+// Factory Functions+// ============================================================================++/**+ * Create a vector database - uses @ruvector/wasm in production, fallback otherwise.+ */+export async function createVectorDB(dimensions: number): Promise<IVectorDB> {+ try {+ // @ts-expect-error - @ruvector/wasm types may not be available+ const { VectorDB: RuVectorDB } = await import('@ruvector/wasm');+ const db = new RuVectorDB({+ dimensions,+ indexType: 'hnsw',+ metric: 'cosine',+ efConstruction: 200,+ m: 16,+ });+ await db.initialize?.();+ return db as IVectorDB;+ } catch {+ console.warn('[@claude-flow/plugins] @ruvector/wasm not available, using fallback');+ return new FallbackVectorDB(dimensions);+ }+}++/**+ * Create a LoRA engine - uses @ruvector/learning-wasm in production, fallback otherwise.+ */+export async function createLoRAEngine(): Promise<ILoRAEngine> {+ try {+ // @ts-expect-error - @ruvector/learning-wasm types may not be available+ const { LoRAEngine } = await import('@ruvector/learning-wasm');+ const engine = new LoRAEngine({ defaultRank: 8, defaultAlpha: 16 });+ await engine.initialize?.();+ return engine as ILoRAEngine;+ } catch {+ console.warn('[@claude-flow/plugins] @ruvector/learning-wasm not available, using fallback');+ return new FallbackLoRAEngine();+ }+}++// ============================================================================+// Utility Functions+// ============================================================================++/**+ * Compute cosine similarity between two vectors.+ * Returns value in range [-1, 1] where 1 = identical.+ */+export function cosineSimilarity(a: Float32Array, b: Float32Array): number {+ let dot = 0;+ let normA = 0;+ let normB = 0;+ const len = Math.min(a.length, b.length);++ for (let i = 0; i < len; i++) {+ dot += a[i] * b[i];+ normA += a[i] * a[i];+ normB += b[i] * b[i];+ }++ const magnitude = Math.sqrt(normA) * Math.sqrt(normB);+ return magnitude === 0 ? 0 : dot / magnitude;+}++/**+ * Generate a simple hash-based embedding for text.+ * Use for fallback when no embedding model is available.+ */+export function generateHashEmbedding(text: string, dimensions: number): Float32Array {+ const embedding = new Float32Array(dimensions);+ const normalized = text.toLowerCase();+ let hash = 0;++ for (let i = 0; i < normalized.length; i++) {+ hash = ((hash << 5) - hash) + normalized.charCodeAt(i);+ hash = hash & hash;+ }++ for (let i = 0; i < dimensions; i++) {+ embedding[i] = Math.sin(hash * (i + 1) * 0.001) * 0.5 + 0.5;+ }++ // Normalize+ let norm = 0;+ for (let i = 0; i < dimensions; i++) {+ norm += embedding[i] * embedding[i];+ }+ norm = Math.sqrt(norm);+ if (norm > 0) {+ for (let i = 0; i < dimensions; i++) {+ embedding[i] /= norm;+ }+ }++ return embedding;+}++/**+ * Lazy initialization mixin for async-initialized classes.+ */+export abstract class LazyInitializable {+ protected initPromise: Promise<void> | null = null;+ protected initialized = false;++ abstract doInitialize(): Promise<void>;++ async initialize(): Promise<void> {+ if (this.initialized) return;+ if (this.initPromise) return this.initPromise;++ this.initPromise = (async () => {+ await this.doInitialize();+ this.initialized = true;+ })();++ return this.initPromise;+ }++ protected async ensureInitialized(): Promise<void> {+ await this.initialize();+ }+}diff --git a/v3/implementation/hooks/guidance-system.ts b/v3/implementation/hooks/guidance-system.tsdeleted file mode 100644index 82ce8e1a13..0000000000--- a/v3/implementation/hooks/guidance-system.ts+++ /dev/null@@ -1,668 +0,0 @@-/**- * Claude Flow V3 - Intelligent Guidance System- *- * Provides actionable context to Claude for optimal development decisions.- * Based on Claude Code hooks research - outputs context Claude will follow.- *- * Key mechanisms:- * - Exit 0 + stdout = Context added to Claude's view- * - Exit 2 + stderr = Block with explanation- * - JSON additionalContext = Discrete guidance Claude follows- *- * @module @claude-flow/hooks- */--import { readFileSync, existsSync, writeFileSync, mkdirSync } from 'fs';-import { join, basename, extname } from 'path';-import { execFileSync } from 'child_process';--// =============================================================================-// Types-// =============================================================================--export interface HookInput {- session_id: string;- transcript_path?: string;- cwd: string;- permission_mode: 'default' | 'plan' | 'acceptEdits' | 'dontAsk' | 'bypassPermissions';- hook_event_name: HookEventName;- tool_name?: string;- tool_input?: Record<string, unknown>;- tool_response?: unknown;- prompt?: string;- stop_hook_active?: boolean;-}--export type HookEventName =- | 'PreToolUse'- | 'PostToolUse'- | 'UserPromptSubmit'- | 'SessionStart'- | 'SessionEnd'- | 'Stop'- | 'SubagentStop';--export interface HookOutput {- decision?: 'approve' | 'block' | 'allow' | 'deny';- reason?: string;- continue?: boolean;- stopReason?: string;- systemMessage?: string;- suppressOutput?: boolean;- hookSpecificOutput?: {- hookEventName: HookEventName;- additionalContext?: string;- permissionDecision?: 'allow' | 'deny' | 'ask';- permissionDecisionReason?: string;- updatedInput?: Record<string, unknown>;- };-}--export interface GuidanceContext {- projectState: ProjectState;- recentPatterns: Pattern[];- securityAlerts: SecurityAlert[];- performanceHints: PerformanceHint[];-}--export interface ProjectState {- v3Progress: number;- activeDomain: string;- recentFiles: string[];- uncommittedChanges: number;- testStatus: 'passing' | 'failing' | 'unknown';-}--export interface Pattern {- id: string;- strategy: string;- domain: string;- quality: number;- usageCount: number;-}--export interface SecurityAlert {- severity: 'critical' | 'high' | 'medium' | 'low';- message: string;- file?: string;-}--export interface PerformanceHint {- type: 'optimization' | 'warning' | 'suggestion';- message: string;- target?: string;-}--// =============================================================================-// Configuration-// =============================================================================--const CONFIG = {- projectRoot: process.cwd(),- guidanceDir: '.claude-flow/guidance',- patternsDb: '.claude-flow/learning/patterns.db',- metricsDir: '.claude-flow/metrics',-- // V3 Architecture guidance- domains: [- 'task-management',- 'session-management',- 'health-monitoring',- 'lifecycle-management',- 'event-coordination',- ],-- // Security patterns- securityPatterns: {- blocked: ['.env', '.pem', '.key', 'credentials', 'secret'],- warned: ['prod', 'production', 'live', 'deploy'],- },-- // Performance targets- performanceTargets: {- searchTimeMs: 1,- operationTimeMs: 100,- fileMaxLines: 500,- memoryReduction: 0.5,- },-- // Agent routing- agentMapping: {- security: ['security-architect', 'security-auditor'],- testing: ['test-architect', 'tester'],- performance: ['performance-engineer', 'perf-analyzer'],- architecture: ['core-architect', 'architecture'],- swarm: ['swarm-specialist', 'hierarchical-coordinator'],- memory: ['memory-specialist', 'memory-coordinator'],- code: ['coder', 'backend-dev'],- review: ['reviewer', 'code-analyzer'],- },-};--// =============================================================================-// Guidance Generators-// =============================================================================--/**- * Generate session start context - loaded at beginning of every session- */-export function generateSessionContext(): string {- const lines: string[] = [- '## V3 Development Context',- '',- '**Architecture**: Domain-Driven Design with 15 @claude-flow modules',- '**Priority**: Security-first (CVE-1, CVE-2, CVE-3 remediation)',- '',- '**Performance Targets**:',- '- HNSW search: 150x-12,500x faster (<1ms)',- '- Flash Attention: 2.49x-7.47x speedup',- '- Memory: 50-75% reduction',- '',- '**Active Patterns**:',- '- Use TDD London School (mock-first)',- '- Event sourcing for state changes',- '- agentic-flow@alpha as core foundation',- '- Bounded contexts with clear interfaces',- '',- '**Code Quality Rules**:',- '- Files under 500 lines',- '- No hardcoded secrets',- '- Input validation at boundaries',- '- Typed interfaces for all public APIs',- ];-- // Add git status (using execFileSync to avoid shell injection)- try {- const gitOutput = execFileSync('git', ['status', '--porcelain'], {- encoding: 'utf-8',- stdio: ['pipe', 'pipe', 'pipe'],- });- const uncommitted = gitOutput.split('\n').filter(line => line.trim()).length;- lines.push('', `**Git Status**: ${uncommitted} uncommitted files`);- } catch {- // Ignore git errors- }-- // Add patterns count (using execFileSync to avoid shell injection)- const patternsPath = join(CONFIG.projectRoot, CONFIG.patternsDb);- if (existsSync(patternsPath)) {- try {- const count = execFileSync('sqlite3', [patternsPath, 'SELECT COUNT(*) FROM short_term_patterns'], {- encoding: 'utf-8',- stdio: ['pipe', 'pipe', 'pipe'],- }).trim();- lines.push(`**Learned Patterns**: ${count} available`);- } catch {- // Ignore db errors- }- }-- return lines.join('\n');-}--/**- * Generate context based on user prompt analysis- */-export function generatePromptContext(prompt: string): string {- const guidance: string[] = [];- const lowerPrompt = prompt.toLowerCase();-- // Security-related prompts- if (/auth|security|password|token|secret|cve|vuln/i.test(lowerPrompt)) {- guidance.push(- '**Security Guidance**:',- '- Validate all inputs at system boundaries',- '- Use parameterized queries (no string concatenation)',- '- Store secrets in environment variables only',- '- Apply principle of least privilege',- '- Check OWASP Top 10 patterns',- ''- );- }-- // Performance-related prompts- if (/optim|perf|fast|slow|memory|cache|speed/i.test(lowerPrompt)) {- guidance.push(- '**Performance Guidance**:',- '- Use HNSW for vector search (not brute-force)',- '- Batch database operations',- '- Implement caching at appropriate layers',- '- Profile before optimizing',- `- Target: <${CONFIG.performanceTargets.searchTimeMs}ms searches, <${CONFIG.performanceTargets.operationTimeMs}ms operations`,- ''- );- }-- // Testing-related prompts- if (/test|spec|mock|assert|coverage/i.test(lowerPrompt)) {- guidance.push(- '**Testing Guidance (TDD London School)**:',- '- Write test first, then implementation',- '- Mock external dependencies',- '- Test behavior, not implementation',- '- One assertion per test concept',- '- Use descriptive test names',- ''- );- }-- // Architecture-related prompts- if (/architect|design|struct|refactor|module|domain/i.test(lowerPrompt)) {- guidance.push(- '**Architecture Guidance (DDD)**:',- '- Respect bounded context boundaries',- '- Use domain events for cross-module communication',- '- Keep domain logic in domain layer',- '- Infrastructure adapters for external services',- '- Follow ADR decisions (ADR-001 through ADR-010)',- ''- );- }-- // Error/bug fixing prompts- if (/fix|bug|error|issue|broken|fail/i.test(lowerPrompt)) {- guidance.push(- '**Debugging Guidance**:',- '- Reproduce the issue first',- '- Check recent changes in git log',- '- Add logging before fixing',- '- Write regression test',- '- Verify fix doesn\'t break other tests',- ''- );- }-- // Implementation prompts- if (/implement|create|add|build|develop/i.test(lowerPrompt)) {- guidance.push(- '**Implementation Guidance**:',- '- Check for existing similar implementations',- '- Follow established patterns in codebase',- '- Write tests alongside implementation',- '- Keep functions focused and small',- '- Document public interfaces',- ''- );- }-- return guidance.join('\n');-}--/**- * Generate pre-edit guidance for file modifications- */-export function generatePreEditGuidance(- filePath: string,- toolName: string = 'Edit'-): HookOutput {- const fileName = basename(filePath);- const ext = extname(filePath);-- // Security checks - block sensitive files- for (const pattern of CONFIG.securityPatterns.blocked) {- if (filePath.toLowerCase().includes(pattern)) {- return {- hookSpecificOutput: {- hookEventName: 'PreToolUse',- permissionDecision: 'deny',- permissionDecisionReason: `Security: Cannot edit ${pattern} files directly. Use environment variables instead.`,- },- };- }- }-- // Warn about production files- for (const pattern of CONFIG.securityPatterns.warned) {- if (filePath.toLowerCase().includes(pattern)) {- return {- hookSpecificOutput: {- hookEventName: 'PreToolUse',- permissionDecision: 'ask',- permissionDecisionReason: `This appears to be a ${pattern} file. Confirm this edit is intentional.`,- },- };- }- }-- // Generate file-specific guidance- let guidance = '';-- if (/test|spec/i.test(fileName)) {- guidance = 'Testing file: Use TDD London School patterns. Mock dependencies, test behavior not implementation.';- } else if (/security|auth/i.test(filePath)) {- guidance = 'Security module: Validate inputs, use parameterized queries, no hardcoded secrets.';- } else if (/memory|cache/i.test(filePath)) {- guidance = 'Memory module: Consider HNSW indexing, batch operations, proper cleanup.';- } else if (/swarm|coordinator/i.test(filePath)) {- guidance = 'Swarm module: Use event-driven communication, handle failures gracefully, respect bounded contexts.';- } else if (ext === '.ts' || ext === '.tsx') {- guidance = 'TypeScript: Use strict types, avoid any, export interfaces for public APIs.';- } else if (ext === '.js' || ext === '.mjs') {- guidance = 'JavaScript: Consider migrating to TypeScript for better type safety.';- }-- if (guidance) {- return {- hookSpecificOutput: {- hookEventName: 'PreToolUse',- permissionDecision: 'allow',- additionalContext: guidance,- },- };- }-- return { decision: 'allow' };-}--/**- * Generate post-edit feedback for course correction- */-export function generatePostEditFeedback(- filePath: string,- success: boolean = true-): HookOutput {- if (!success) {- return {- decision: 'block',- reason: 'Edit failed. Check file path and permissions.',- };- }-- if (!existsSync(filePath)) {- return { decision: 'allow' };- }-- const issues: string[] = [];- const content = readFileSync(filePath, 'utf-8');- const lines = content.split('\n');- const ext = extname(filePath);- const isTest = /test|spec/i.test(filePath);-- // Check for console.log in non-test files- if (!isTest && content.includes('console.log')) {- issues.push('Remove console.log statements (use proper logging)');- }-- // Check for TODO/FIXME- if (/TODO|FIXME|HACK/i.test(content)) {- issues.push('Address TODO/FIXME comments before committing');- }-- // Check for any type in TypeScript- if ((ext === '.ts' || ext === '.tsx') && /:\s*any\b/.test(content)) {- issues.push("Replace 'any' types with specific types");- }-- // Check file size- if (lines.length > CONFIG.performanceTargets.fileMaxLines) {- issues.push(- `File exceeds ${CONFIG.performanceTargets.fileMaxLines} lines (${lines.length}). Consider splitting.`- );- }-- // Check for hardcoded secrets patterns- if (/password\s*=\s*['"][^'"]+['"]|api[_-]?key\s*=\s*['"][^'"]+['"]/i.test(content)) {- issues.push('Possible hardcoded secret detected. Use environment variables.');- }-- if (issues.length > 0) {- return {- decision: 'allow',- reason: `Edit completed. Review suggestions:\n- ${issues.join('\n- ')}`,- hookSpecificOutput: {- hookEventName: 'PostToolUse',- additionalContext: `Quality check found items to address:\n- ${issues.join('\n- ')}`,- },- };- }-- return { decision: 'allow' };-}--/**- * Generate pre-command risk assessment- */-export function generatePreCommandGuidance(command: string): HookOutput {- // Block dangerous commands- const dangerousPatterns = [- 'rm -rf',- 'drop database',- 'truncate',- '--force.*push',- 'reset --hard',- 'format c:',- ];-- for (const pattern of dangerousPatterns) {- if (new RegExp(pattern, 'i').test(command)) {- return {- hookSpecificOutput: {- hookEventName: 'PreToolUse',- permissionDecision: 'deny',- permissionDecisionReason: `Destructive command blocked: ${pattern}. Use safer alternatives.`,- },- };- }- }-- // Warn about risky commands- const riskyPatterns = ['npm publish', 'git push', 'deploy', 'kubectl apply'];- for (const pattern of riskyPatterns) {- if (command.toLowerCase().includes(pattern)) {- return {- hookSpecificOutput: {- hookEventName: 'PreToolUse',- permissionDecision: 'ask',- permissionDecisionReason: `This command has external effects (${pattern}). Confirm before proceeding.`,- },- };- }- }-- // Guide test commands- if (/npm test|vitest|jest|pnpm test/i.test(command)) {- return {- hookSpecificOutput: {- hookEventName: 'PreToolUse',- permissionDecision: 'allow',- additionalContext:- 'Running tests. If failures occur, fix them before proceeding. Check coverage thresholds.',- },- };- }-- // Guide build commands- if (/npm run build|tsc|pnpm build/i.test(command)) {- return {- hookSpecificOutput: {- hookEventName: 'PreToolUse',- permissionDecision: 'allow',- additionalContext:- 'Building project. Watch for type errors and warnings. All must pass before commit.',- },- };- }-- return { decision: 'allow' };-}--/**- * Route task to optimal agent- */-export function routeTask(task: string): {- agent: string;- confidence: number;- alternatives: string[];- reasoning: string;-} {- const lowerTask = task.toLowerCase();-- // Define keyword patterns for each category- const patterns: Record<string, RegExp> = {- security: /security|auth|cve|vuln|encrypt|password|token/i,- testing: /test|spec|mock|coverage|tdd|assert/i,- performance: /perf|optim|fast|memory|cache|speed|slow/i,- architecture: /architect|design|ddd|domain|refactor|struct/i,- swarm: /swarm|agent|coordinate|orchestrat|parallel/i,- memory: /memory|agentdb|hnsw|vector|embedding/i,- code: /fix|bug|implement|create|add|build|error/i,- review: /review|quality|lint|check|audit/i,- };-- // Find best match- let bestCategory = 'code';- let bestConfidence = 70;-- for (const [category, pattern] of Object.entries(patterns)) {- if (pattern.test(lowerTask)) {- const matches = lowerTask.match(pattern);- const confidence = 85 + (matches ? matches.length * 5 : 0);- if (confidence > bestConfidence) {- bestCategory = category;- bestConfidence = Math.min(confidence, 98);- }- }- }-- const agents = CONFIG.agentMapping[bestCategory] || ['coder'];- const alternatives = Object.entries(CONFIG.agentMapping)- .filter(([cat]) => cat !== bestCategory)- .slice(0, 3)- .map(([, agentList]) => agentList[0]);-- return {- agent: agents[0],- confidence: bestConfidence,- alternatives,- reasoning: `Task matches ${bestCategory} patterns. Use Task tool with subagent_type="${agents[0]}".`,- };-}--/**- * Check if work is complete before stopping- */-export function checkStopConditions(): HookOutput {- const issues: string[] = [];-- // Check for uncommitted changes- try {- const uncommitted = parseInt(- execSync('git status --porcelain 2>/dev/null | wc -l', { encoding: 'utf-8' }).trim()- );- if (uncommitted > 0) {- issues.push(`${uncommitted} uncommitted files`);- }- } catch {- // Ignore git errors- }-- // Check for test failures- const testResultsPath = join(CONFIG.projectRoot, CONFIG.metricsDir, 'test-results.json');- if (existsSync(testResultsPath)) {- try {- const results = JSON.parse(readFileSync(testResultsPath, 'utf-8'));- if (results.failures > 0) {- issues.push(`${results.failures} failing tests`);- }- } catch {- // Ignore parse errors- }- }-- if (issues.length > 0) {- return {- decision: 'block',- reason: `Work may be incomplete:\n- ${issues.join('\n- ')}`,- };- }-- return { decision: 'approve' };-}--// =============================================================================-// CLI Interface-// =============================================================================--export function main(): void {- const args = process.argv.slice(2);- const command = args[0];-- switch (command) {- case 'session-context':- case 'session':- console.log(generateSessionContext());- process.exit(0);- break;-- case 'user-prompt':- case 'prompt':- console.log(generatePromptContext(args[1] || ''));- process.exit(0);- break;-- case 'pre-edit':- console.log(JSON.stringify(generatePreEditGuidance(args[1] || '', args[2])));- process.exit(0);- break;-- case 'post-edit':- console.log(JSON.stringify(generatePostEditFeedback(args[1] || '', args[2] !== 'false')));- process.exit(0);- break;-- case 'pre-command':- console.log(JSON.stringify(generatePreCommandGuidance(args[1] || '')));- process.exit(0);- break;-- case 'route':- const routing = routeTask(args[1] || '');- console.log(`**Recommended Agent**: ${routing.agent}`);- console.log(`**Confidence**: ${routing.confidence}%`);- console.log(`**Reasoning**: ${routing.reasoning}`);- console.log(`**Alternatives**: ${routing.alternatives.join(', ')}`);- process.exit(0);- break;-- case 'stop-check':- const stopResult = checkStopConditions();- if (stopResult.decision === 'block') {- console.error(stopResult.reason);- process.exit(2);- }- process.exit(0);- break;-- case 'help':- case '--help':- case '-h':- console.log(`-Claude Flow V3 - Intelligent Guidance System--Usage: guidance-system.ts <command> [args]--Commands:- session-context Output project context for SessionStart- user-prompt <prompt> Analyze prompt and inject relevant guidance- pre-edit <path> Validate and guide before file edit- post-edit <path> Provide feedback after file edit- pre-command <cmd> Risk assessment for bash commands- route <task> Suggest optimal agent for task- stop-check Verify work complete before stopping--Exit Codes:- 0 - Success (stdout added as context)- 2 - Block (stderr shown to Claude)-`);- break;-- default:- console.error(`Unknown command: ${command}`);- process.exit(1);- }-}--// Run if executed directly-if (require.main === module) {- main();-}diff --git a/v3/implementation/plugins/example-plugin.ts b/v3/implementation/plugins/example-plugin.tsdeleted file mode 100644index c15a55bdd3..0000000000--- a/v3/implementation/plugins/example-plugin.ts+++ /dev/null@@ -1,439 +0,0 @@-/**- * Example Plugin for Claude-Flow V3- *- * This example demonstrates how to create a complete plugin- * with all extension points and lifecycle management.- */--import type {- ClaudeFlowPlugin,- PluginContext,- AgentTypeDefinition,- TaskTypeDefinition,- MCPToolDefinition,- CLICommandDefinition,- MemoryBackendFactory,- ILogger,-} from '@claude-flow/shared';--/**- * Example plugin configuration- */-interface ExamplePluginConfig {- enableFeatureA: boolean;- featureATimeout: number;- apiKey?: string;-}--/**- * Example Plugin Implementation- *- * Demonstrates all extension points available in the V3 plugin system.- */-export class ExamplePlugin implements ClaudeFlowPlugin {- // Required: Unique plugin identifier- readonly name = 'example-plugin';-- // Required: Semantic version- readonly version = '1.0.0';-- // Optional: Plugin dependencies (loaded first)- readonly dependencies = [];-- // Optional: Human-readable description- readonly description = 'Example plugin demonstrating V3 plugin architecture';-- // Optional: Plugin author- readonly author = 'Claude-Flow Team';-- // Plugin state- private config: ExamplePluginConfig | null = null;- private logger: ILogger | null = null;- private isHealthy = true;-- /**- * Initialize the plugin- *- * Called after all dependencies are loaded.- * Use this to:- * - Validate configuration- * - Set up connections- * - Initialize internal state- */- async initialize(context: PluginContext): Promise<void> {- this.logger = context.logger;- this.logger.info('[ExamplePlugin] Initializing...');-- // Parse and validate configuration- this.config = this.parseConfig(context.config);-- // Register for events (optional)- context.eventBus.on('agent:spawned', (event) => {- this.logger?.debug('[ExamplePlugin] Agent spawned:', event.payload);- });-- // Register services in DI container (optional)- context.services.register('exampleService', {- greet: (name: string) => `Hello, ${name}!`,- });-- this.logger.info('[ExamplePlugin] Initialized successfully');- }-- /**- * Shutdown the plugin- *- * Called during system shutdown.- * Use this to:- * - Close connections- * - Flush buffers- * - Clean up resources- */- async shutdown(): Promise<void> {- this.logger?.info('[ExamplePlugin] Shutting down...');-- // Clean up resources- this.config = null;-- this.logger?.info('[ExamplePlugin] Shutdown complete');- }-- /**- * Register custom agent types- *- * @returns Array of agent type definitions- */- registerAgentTypes(): AgentTypeDefinition[] {- return [- {- type: 'example-specialist',- name: 'Example Specialist Agent',- description: 'Agent specialized in example tasks',- defaultConfig: {- model: 'claude-3-opus',- maxTokens: 4096,- temperature: 0.7,- },- requiredCapabilities: ['analysis', 'synthesis'],- metadata: {- category: 'specialist',- version: '1.0.0',- },- },- {- type: 'example-coordinator',- name: 'Example Coordinator Agent',- description: 'Agent for coordinating example workflows',- defaultConfig: {- model: 'claude-3-sonnet',- maxTokens: 2048,- },- requiredCapabilities: ['coordination'],- },- ];- }-- /**- * Register custom task types- *- * @returns Array of task type definitions- */- registerTaskTypes(): TaskTypeDefinition[] {- return [- {- type: 'example-analysis',- name: 'Example Analysis Task',- description: 'Perform example analysis on input data',- defaultPriority: 50,- defaultTimeout: 120000, // 2 minutes- requiredCapabilities: ['analysis'],- inputSchema: {- type: 'object',- properties: {- data: { type: 'string' },- depth: { type: 'number' },- options: {- type: 'object',- properties: {- detailed: { type: 'boolean' },- },- },- },- required: ['data'],- },- metadata: {- category: 'analysis',- },- },- ];- }-- /**- * Register MCP tools- *- * @returns Array of MCP tool definitions- */- registerMCPTools(): MCPToolDefinition[] {- return [- {- name: 'example_analyze',- description: 'Analyze data using the example plugin',- inputSchema: {- type: 'object',- properties: {- input: {- type: 'string',- description: 'Data to analyze',- },- format: {- type: 'string',- enum: ['json', 'text', 'markdown'],- description: 'Output format',- },- },- required: ['input'],- },- handler: async (input: Record<string, unknown>) => {- const data = input.input as string;- const format = (input.format as string) || 'json';-- // Perform analysis- const result = {- analyzed: true,- input: data,- length: data.length,- words: data.split(/\s+/).length,- };-- if (format === 'json') {- return result;- } else if (format === 'markdown') {- return `## Analysis Result\n- Length: ${result.length}\n- Words: ${result.words}`;- } else {- return `Analyzed: length=${result.length}, words=${result.words}`;- }- },- version: '1.0.0',- metadata: {- category: 'analysis',- },- },- {- name: 'example_transform',- description: 'Transform data using the example plugin',- inputSchema: {- type: 'object',- properties: {- data: { type: 'string', description: 'Data to transform' },- operation: {- type: 'string',- enum: ['uppercase', 'lowercase', 'reverse'],- description: 'Transformation operation',- },- },- required: ['data', 'operation'],- },- handler: async (input: Record<string, unknown>) => {- const data = input.data as string;- const operation = input.operation as string;-- switch (operation) {- case 'uppercase':- return { result: data.toUpperCase() };- case 'lowercase':- return { result: data.toLowerCase() };- case 'reverse':- return { result: data.split('').reverse().join('') };- default:- return { error: `Unknown operation: ${operation}` };- }- },- },- ];- }-- /**- * Register CLI commands- *- * @returns Array of CLI command definitions- */- registerCLICommands(): CLICommandDefinition[] {- return [- {- name: 'example',- description: 'Run example plugin commands',- aliases: ['ex'],- options: [- {- name: 'verbose',- short: 'v',- description: 'Enable verbose output',- type: 'boolean',- default: false,- },- {- name: 'format',- short: 'f',- description: 'Output format',- type: 'string',- default: 'text',- },- ],- arguments: [- {- name: 'action',- description: 'Action to perform',- required: true,- choices: ['status', 'analyze', 'info'],- },- ],- handler: async (args) => {- const action = args._[0];- const verbose = args.verbose as boolean;-- switch (action) {- case 'status':- console.log('Example plugin status: OK');- if (verbose) {- console.log(' Version:', this.version);- console.log(' Healthy:', this.isHealthy);- }- break;-- case 'info':- console.log('Example Plugin v' + this.version);- console.log(this.description);- break;-- case 'analyze':- console.log('Running analysis...');- break;- }- },- },- ];- }-- /**- * Register memory backends- *- * @returns Array of memory backend factories- */- registerMemoryBackends(): MemoryBackendFactory[] {- return [- {- name: 'example-memory',- description: 'Example in-memory backend for demonstration',- capabilities: {- supportsVectorSearch: false,- supportsFullText: true,- supportsTransactions: false,- supportsPersistence: false,- },- create: async (config) => {- return new ExampleMemoryBackend(config);- },- metadata: {- type: 'in-memory',- maxEntries: 10000,- },- },- ];- }-- /**- * Health check- *- * Called periodically when health checks are enabled.- * @returns true if healthy, false otherwise- */- async healthCheck(): Promise<boolean> {- // Perform health checks- // - Check connections- // - Verify resources- // - Test dependencies-- return this.isHealthy;- }-- /**- * Parse and validate plugin configuration- */- private parseConfig(config: Record<string, unknown>): ExamplePluginConfig {- return {- enableFeatureA: (config.enableFeatureA as boolean) ?? true,- featureATimeout: (config.featureATimeout as number) ?? 5000,- apiKey: config.apiKey as string | undefined,- };- }-}--/**- * Example Memory Backend Implementation- */-class ExampleMemoryBackend {- private store = new Map<string, { value: unknown; metadata?: Record<string, unknown> }>();-- constructor(private config: Record<string, unknown>) {}-- async initialize(): Promise<void> {- // Initialize backend- }-- async shutdown(): Promise<void> {- this.store.clear();- }-- async store(key: string, value: unknown, metadata?: Record<string, unknown>): Promise<void> {- this.store.set(key, { value, metadata });- }-- async retrieve(key: string): Promise<unknown | null> {- return this.store.get(key)?.value ?? null;- }-- async delete(key: string): Promise<boolean> {- return this.store.delete(key);- }-- async search(query: string, options?: Record<string, unknown>): Promise<Array<{ key: string; value: unknown; score: number }>> {- const results: Array<{ key: string; value: unknown; score: number }> = [];-- for (const [key, entry] of this.store.entries()) {- const valueStr = JSON.stringify(entry.value).toLowerCase();- if (valueStr.includes(query.toLowerCase())) {- results.push({- key,- value: entry.value,- score: 1.0,- });- }- }-- return results;- }-- async clear(): Promise<void> {- this.store.clear();- }-- async getStats(): Promise<{ entryCount: number; sizeBytes: number; memoryUsageBytes: number }> {- return {- entryCount: this.store.size,- sizeBytes: 0,- memoryUsageBytes: 0,- };- }-}--/**- * Plugin factory function- *- * Common pattern for creating plugin instances- */-export function createExamplePlugin(): ClaudeFlowPlugin {- return new ExamplePlugin();-}--// Default export for dynamic loading-export default ExamplePlugin;diff --git a/v3/mcp/types.d.ts b/v3/mcp/types.d.tsdeleted file mode 100644index a923cf6051..0000000000--- a/v3/mcp/types.d.ts+++ /dev/null@@ -1,438 +0,0 @@-/**- * V3 MCP Types and Interfaces- *- * Optimized type definitions for the V3 MCP server with:- * - Strict typing for performance- * - Connection pooling types- * - Transport layer abstractions- * - Tool registry interfaces- *- * Performance Targets:- * - Server startup: <400ms- * - Tool registration: <10ms- * - Tool execution: <50ms overhead- */-/**- * JSON-RPC 2.0 Protocol Version- */-export type JsonRpcVersion = '2.0';-/**- * MCP Protocol Version- */-export interface MCPProtocolVersion {- major: number;- minor: number;- patch: number;-}-/**- * MCP Request ID (can be string, number, or null)- */-export type RequestId = string | number | null;-/**- * Base MCP Message- */-export interface MCPMessage {- jsonrpc: JsonRpcVersion;-}-/**- * MCP Request- */-export interface MCPRequest extends MCPMessage {- id: RequestId;- method: string;- params?: Record<string, unknown>;-}-/**- * MCP Notification (request without id)- */-export interface MCPNotification extends MCPMessage {- method: string;- params?: Record<string, unknown>;-}-/**- * MCP Error- */-export interface MCPError {- code: number;- message: string;- data?: unknown;-}-/**- * MCP Response- */-export interface MCPResponse extends MCPMessage {- id: RequestId;- result?: unknown;- error?: MCPError;-}-/**- * Transport type options- */-export type TransportType = 'stdio' | 'http' | 'websocket' | 'in-process';-/**- * Authentication method- */-export type AuthMethod = 'token' | 'oauth' | 'api-key' | 'none';-/**- * Authentication configuration- */-export interface AuthConfig {- enabled: boolean;- method: AuthMethod;- tokens?: string[];- apiKeys?: string[];- jwtSecret?: string;- oauth?: {- clientId: string;- clientSecret: string;- authorizationUrl: string;- tokenUrl: string;- };-}-/**- * Load balancer configuration- */-export interface LoadBalancerConfig {- enabled: boolean;- maxConcurrentRequests: number;- rateLimit?: {- requestsPerSecond: number;- burstSize: number;- };- circuitBreaker?: {- failureThreshold: number;- resetTimeout: number;- };-}-/**- * Connection pool configuration- */-export interface ConnectionPoolConfig {- maxConnections: number;- minConnections: number;- idleTimeout: number;- acquireTimeout: number;- maxWaitingClients: number;- evictionRunInterval: number;-}-/**- * MCP Server configuration- */-export interface MCPServerConfig {- name: string;- version: string;- transport: TransportType;- host?: string;- port?: number;- tlsEnabled?: boolean;- tlsCert?: string;- tlsKey?: string;- auth?: AuthConfig;- loadBalancer?: LoadBalancerConfig;- connectionPool?: ConnectionPoolConfig;- corsEnabled?: boolean;- corsOrigins?: string[];- maxRequestSize?: number;- requestTimeout?: number;- enableMetrics?: boolean;- enableCaching?: boolean;- cacheTTL?: number;- logLevel?: 'debug' | 'info' | 'warn' | 'error';-}-/**- * MCP Session state- */-export type SessionState = 'created' | 'initializing' | 'ready' | 'closing' | 'closed' | 'error';-/**- * MCP Session- */-export interface MCPSession {- id: string;- state: SessionState;- transport: TransportType;- createdAt: Date;- lastActivityAt: Date;- isInitialized: boolean;- isAuthenticated: boolean;- clientInfo?: MCPClientInfo;- protocolVersion?: MCPProtocolVersion;- capabilities?: MCPCapabilities;- metadata?: Record<string, unknown>;-}-/**- * Client information from initialization- */-export interface MCPClientInfo {- name: string;- version: string;-}-/**- * MCP Capabilities- */-export interface MCPCapabilities {- logging?: {- level: 'debug' | 'info' | 'warn' | 'error';- };- tools?: {- listChanged: boolean;- };- resources?: {- listChanged: boolean;- subscribe: boolean;- };- prompts?: {- listChanged: boolean;- };- experimental?: Record<string, unknown>;-}-/**- * Initialize request parameters- */-export interface MCPInitializeParams {- protocolVersion: MCPProtocolVersion;- capabilities: MCPCapabilities;- clientInfo: MCPClientInfo;-}-/**- * Initialize response result- */-export interface MCPInitializeResult {- protocolVersion: MCPProtocolVersion;- capabilities: MCPCapabilities;- serverInfo: {- name: string;- version: string;- };- instructions?: string;-}-/**- * JSON Schema type for tool input- */-export interface JSONSchema {- type: string;- properties?: Record<string, JSONSchema>;- required?: string[];- items?: JSONSchema;- enum?: string[];- description?: string;- default?: unknown;- minimum?: number;- maximum?: number;- minLength?: number;- maxLength?: number;- pattern?: string;- additionalProperties?: boolean | JSONSchema;-}-/**- * Tool execution context- */-export interface ToolContext {- sessionId: string;- requestId?: RequestId;- orchestrator?: unknown;- swarmCoordinator?: unknown;- agentManager?: unknown;- resourceManager?: unknown;- messageBus?: unknown;- monitor?: unknown;- metadata?: Record<string, unknown>;-}-/**- * Tool handler function type- */-export type ToolHandler<TInput = unknown, TOutput = unknown> = (input: TInput, context?: ToolContext) => Promise<TOutput>;-/**- * MCP Tool definition- */-export interface MCPTool<TInput = unknown, TOutput = unknown> {- name: string;- description: string;- inputSchema: JSONSchema;- handler: ToolHandler<TInput, TOutput>;- category?: string;- tags?: string[];- version?: string;- deprecated?: boolean;- cacheable?: boolean;- cacheTTL?: number;- timeout?: number;-}-/**- * Tool call result- */-export interface ToolCallResult {- content: Array<{- type: 'text' | 'image' | 'resource';- text?: string;- data?: string;- mimeType?: string;- }>;- isError: boolean;-}-/**- * Tool registration options- */-export interface ToolRegistrationOptions {- override?: boolean;- validate?: boolean;- preload?: boolean;-}-/**- * Request handler function type- */-export type RequestHandler = (request: MCPRequest) => Promise<MCPResponse>;-/**- * Notification handler function type- */-export type NotificationHandler = (notification: MCPNotification) => Promise<void>;-/**- * Transport health status- */-export interface TransportHealthStatus {- healthy: boolean;- error?: string;- metrics?: Record<string, number>;-}-/**- * Transport interface- */-export interface ITransport {- readonly type: TransportType;- start(): Promise<void>;- stop(): Promise<void>;- onRequest(handler: RequestHandler): void;- onNotification(handler: NotificationHandler): void;- sendNotification?(notification: MCPNotification): Promise<void>;- getHealthStatus(): Promise<TransportHealthStatus>;-}-/**- * Connection state- */-export type ConnectionState = 'idle' | 'busy' | 'closing' | 'closed' | 'error';-/**- * Pooled connection- */-export interface PooledConnection {- id: string;- state: ConnectionState;- createdAt: Date;- lastUsedAt: Date;- useCount: number;- transport: TransportType;- metadata?: Record<string, unknown>;-}-/**- * Connection pool statistics- */-export interface ConnectionPoolStats {- totalConnections: number;- idleConnections: number;- busyConnections: number;- pendingRequests: number;- totalAcquired: number;- totalReleased: number;- totalCreated: number;- totalDestroyed: number;- avgAcquireTime: number;-}-/**- * Connection pool interface- */-export interface IConnectionPool {- acquire(): Promise<PooledConnection>;- release(connection: PooledConnection): void;- destroy(connection: PooledConnection): void;- getStats(): ConnectionPoolStats;- drain(): Promise<void>;- clear(): Promise<void>;-}-/**- * Tool call metrics- */-export interface ToolCallMetrics {- toolName: string;- duration: number;- success: boolean;- timestamp: number;- transport: TransportType;- cached?: boolean;-}-/**- * MCP Server metrics- */-export interface MCPServerMetrics {- totalRequests: number;- successfulRequests: number;- failedRequests: number;- averageResponseTime: number;- activeSessions: number;- toolInvocations: Record<string, number>;- errors: Record<string, number>;- lastReset: Date;- startupTime?: number;- uptime?: number;-}-/**- * Session metrics- */-export interface SessionMetrics {- total: number;- active: number;- authenticated: number;- expired: number;-}-/**- * MCP Event types- */-export type MCPEventType = 'server:started' | 'server:stopped' | 'server:error' | 'session:created' | 'session:initialized' | 'session:closed' | 'session:error' | 'tool:registered' | 'tool:unregistered' | 'tool:called' | 'tool:completed' | 'tool:error' | 'transport:connected' | 'transport:disconnected' | 'transport:error' | 'pool:connection:acquired' | 'pool:connection:released' | 'pool:connection:created' | 'pool:connection:destroyed';-/**- * MCP Event- */-export interface MCPEvent {- type: MCPEventType;- timestamp: Date;- data?: unknown;-}-/**- * Event handler function type- */-export type EventHandler = (event: MCPEvent) => void;-/**- * Log level- */-export type LogLevel = 'debug' | 'info' | 'warn' | 'error';-/**- * Logger interface- */-export interface ILogger {- debug(message: string, data?: unknown): void;- info(message: string, data?: unknown): void;- warn(message: string, data?: unknown): void;- error(message: string, data?: unknown): void;-}-/**- * Standard JSON-RPC error codes- */-export declare const ErrorCodes: {- readonly PARSE_ERROR: -32700;- readonly INVALID_REQUEST: -32600;- readonly METHOD_NOT_FOUND: -32601;- readonly INVALID_PARAMS: -32602;- readonly INTERNAL_ERROR: -32603;- readonly SERVER_NOT_INITIALIZED: -32002;- readonly UNKNOWN_ERROR: -32001;- readonly REQUEST_CANCELLED: -32800;- readonly RATE_LIMITED: -32000;- readonly AUTHENTICATION_REQUIRED: -32001;- readonly AUTHORIZATION_FAILED: -32002;-};-/**- * MCP Error class- */-export declare class MCPServerError extends Error {- code: number;- data?: unknown | undefined;- constructor(message: string, code?: number, data?: unknown | undefined);- toMCPError(): MCPError;-}-//# sourceMappingURL=types.d.ts.map\ No newline at end of file