Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 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

checkpoint: File edit:

rUv969ffc221bd0
diff --git a/v3/@claude-flow/shared/src/index.ts b/v3/@claude-flow/shared/src/index.ts
index 03832d9721..46792786e5 100644
--- a/v3/@claude-flow/shared/src/index.ts
+++ b/v3/@claude-flow/shared/src/index.ts
@@ -29,3 +29,6 @@ export * from './hooks/index.js';
// Security Utilities - Secure random generation, input validation
export * from './security/index.js';
+
+// Resilience Patterns - Retry, circuit breaker, rate limiting
+export * from './resilience/index.js';
diff --git a/v3/@claude-flow/shared/src/resilience/bulkhead.ts b/v3/@claude-flow/shared/src/resilience/bulkhead.ts
new file mode 100644
index 0000000000..08cbb731a4
--- /dev/null
+++ b/v3/@claude-flow/shared/src/resilience/bulkhead.ts
@@ -0,0 +1,277 @@
+/**
+ * Bulkhead Pattern
+ *
+ * Isolates failures by limiting concurrent executions.
+ *
+ * @module v3/shared/resilience/bulkhead
+ */
+
+import { EventEmitter } from 'events';
+
+/**
+ * Bulkhead options
+ */
+export interface BulkheadOptions {
+ /** Name for identification */
+ name: string;
+
+ /** Maximum concurrent executions */
+ maxConcurrent: number;
+
+ /** Maximum queue size */
+ maxQueue: number;
+
+ /** Timeout for queued items in ms */
+ queueTimeout: number;
+
+ /** Callback when rejected */
+ onRejected?: (reason: 'full' | 'timeout') => void;
+}
+
+/**
+ * Bulkhead statistics
+ */
+export interface BulkheadStats {
+ active: number;
+ queued: number;
+ maxConcurrent: number;
+ maxQueue: number;
+ completed: number;
+ rejected: number;
+ timedOut: number;
+}
+
+/**
+ * Queued item
+ */
+interface QueuedItem<T> {
+ fn: () => Promise<T>;
+ resolve: (value: T) => void;
+ reject: (error: Error) => void;
+ queuedAt: number;
+ timeoutId?: ReturnType<typeof setTimeout>;
+}
+
+/**
+ * Default options
+ */
+const DEFAULT_OPTIONS: Omit<BulkheadOptions, 'name'> = {
+ maxConcurrent: 10,
+ maxQueue: 100,
+ queueTimeout: 30000,
+};
+
+/**
+ * Bulkhead
+ *
+ * Limits concurrent executions to prevent resource exhaustion.
+ *
+ * @example
+ * const bulkhead = new Bulkhead({
+ * name: 'database',
+ * maxConcurrent: 10,
+ * maxQueue: 50,
+ * });
+ *
+ * try {
+ * const result = await bulkhead.execute(() => dbQuery());
+ * } catch (error) {
+ * if (error.message.includes('Bulkhead full')) {
+ * // Handle capacity exceeded
+ * }
+ * }
+ */
+export class Bulkhead extends EventEmitter {
+ private readonly options: BulkheadOptions;
+ private active = 0;
+ private readonly queue: Array<QueuedItem<unknown>> = [];
+ private completed = 0;
+ private rejected = 0;
+ private timedOut = 0;
+
+ constructor(options: BulkheadOptions) {
+ super();
+ this.options = { ...DEFAULT_OPTIONS, ...options };
+ }
+
+ /**
+ * Execute a function within the bulkhead
+ */
+ async execute<T>(fn: () => Promise<T>): Promise<T> {
+ // If there's room for execution, run immediately
+ if (this.active < this.options.maxConcurrent) {
+ return this.runNow(fn);
+ }
+
+ // Check if queue is full
+ if (this.queue.length >= this.options.maxQueue) {
+ this.rejected++;
+ this.options.onRejected?.('full');
+ throw new Error(`Bulkhead '${this.options.name}' is full. Max concurrent: ${this.options.maxConcurrent}, queue: ${this.options.maxQueue}`);
+ }
+
+ // Add to queue
+ return this.addToQueue(fn);
+ }
+
+ /**
+ * Get current statistics
+ */
+ getStats(): BulkheadStats {
+ return {
+ active: this.active,
+ queued: this.queue.length,
+ maxConcurrent: this.options.maxConcurrent,
+ maxQueue: this.options.maxQueue,
+ completed: this.completed,
+ rejected: this.rejected,
+ timedOut: this.timedOut,
+ };
+ }
+
+ /**
+ * Check if there's capacity available
+ */
+ hasCapacity(): boolean {
+ return this.active < this.options.maxConcurrent || this.queue.length < this.options.maxQueue;
+ }
+
+ /**
+ * Get available capacity (concurrent + queue)
+ */
+ availableCapacity(): number {
+ const concurrentAvailable = this.options.maxConcurrent - this.active;
+ const queueAvailable = this.options.maxQueue - this.queue.length;
+ return concurrentAvailable + queueAvailable;
+ }
+
+ /**
+ * Reset statistics
+ */
+ resetStats(): void {
+ this.completed = 0;
+ this.rejected = 0;
+ this.timedOut = 0;
+ }
+
+ /**
+ * Run function immediately
+ */
+ private async runNow<T>(fn: () => Promise<T>): Promise<T> {
+ this.active++;
+ this.emit('acquire');
+
+ try {
+ const result = await fn();
+ this.completed++;
+ return result;
+ } finally {
+ this.active--;
+ this.emit('release');
+ this.processQueue();
+ }
+ }
+
+ /**
+ * Add function to queue
+ */
+ private addToQueue<T>(fn: () => Promise<T>): Promise<T> {
+ return new Promise((resolve, reject) => {
+ const item: QueuedItem<T> = {
+ fn,
+ resolve,
+ reject,
+ queuedAt: Date.now(),
+ };
+
+ // Set timeout for queued item
+ item.timeoutId = setTimeout(() => {
+ const index = this.queue.indexOf(item as QueuedItem<unknown>);
+ if (index !== -1) {
+ this.queue.splice(index, 1);
+ this.timedOut++;
+ this.options.onRejected?.('timeout');
+ reject(new Error(`Bulkhead '${this.options.name}' queue timeout after ${this.options.queueTimeout}ms`));
+ }
+ }, this.options.queueTimeout);
+
+ this.queue.push(item as QueuedItem<unknown>);
+ this.emit('queued', { queueLength: this.queue.length });
+ });
+ }
+
+ /**
+ * Process next item in queue
+ */
+ private processQueue(): void {
+ if (this.active >= this.options.maxConcurrent) {
+ return;
+ }
+
+ const item = this.queue.shift();
+ if (!item) {
+ return;
+ }
+
+ // Clear timeout
+ if (item.timeoutId) {
+ clearTimeout(item.timeoutId);
+ }
+
+ // Execute the queued function
+ this.active++;
+ this.emit('acquire');
+
+ item.fn()
+ .then((result) => {
+ this.completed++;
+ item.resolve(result);
+ })
+ .catch((error) => {
+ item.reject(error);
+ })
+ .finally(() => {
+ this.active--;
+ this.emit('release');
+ this.processQueue();
+ });
+ }
+}
+
+/**
+ * Create a semaphore for limiting concurrent access
+ */
+export function createSemaphore(maxConcurrent: number): {
+ acquire: () => Promise<void>;
+ release: () => void;
+ available: () => number;
+} {
+ let current = 0;
+ const waiting: Array<() => void> = [];
+
+ return {
+ async acquire(): Promise<void> {
+ if (current < maxConcurrent) {
+ current++;
+ return;
+ }
+
+ return new Promise<void>((resolve) => {
+ waiting.push(resolve);
+ });
+ },
+
+ release(): void {
+ const next = waiting.shift();
+ if (next) {
+ next();
+ } else {
+ current = Math.max(0, current - 1);
+ }
+ },
+
+ available(): number {
+ return maxConcurrent - current;
+ },
+ };
+}
diff --git a/v3/@claude-flow/shared/src/resilience/circuit-breaker.ts b/v3/@claude-flow/shared/src/resilience/circuit-breaker.ts
new file mode 100644
index 0000000000..5d01c9422a
--- /dev/null
+++ b/v3/@claude-flow/shared/src/resilience/circuit-breaker.ts
@@ -0,0 +1,326 @@
+/**
+ * Circuit Breaker Pattern
+ *
+ * Prevents cascading failures by breaking the circuit after failures.
+ *
+ * @module v3/shared/resilience/circuit-breaker
+ */
+
+import { EventEmitter } from 'events';
+
+/**
+ * Circuit breaker states
+ */
+export enum CircuitBreakerState {
+ /** Circuit is closed, requests flow normally */
+ CLOSED = 'CLOSED',
+
+ /** Circuit is open, requests are rejected immediately */
+ OPEN = 'OPEN',
+
+ /** Circuit is testing if service recovered */
+ HALF_OPEN = 'HALF_OPEN',
+}
+
+/**
+ * Circuit breaker options
+ */
+export interface CircuitBreakerOptions {
+ /** Name for identification */
+ name: string;
+
+ /** Failure threshold before opening circuit (default: 5) */
+ failureThreshold: number;
+
+ /** Success threshold in half-open state to close circuit (default: 3) */
+ successThreshold: number;
+
+ /** Time to wait before testing again in ms (default: 30000) */
+ timeout: number;
+
+ /** Time window to track failures in ms (default: 60000) */
+ rollingWindow: number;
+
+ /** Volume threshold - minimum requests before tripping (default: 10) */
+ volumeThreshold: number;
+
+ /** Custom failure detection */
+ isFailure?: (error: Error) => boolean;
+
+ /** Fallback function when circuit is open */
+ fallback?: <T>(error: Error) => T | Promise<T>;
+
+ /** Callback when state changes */
+ onStateChange?: (from: CircuitBreakerState, to: CircuitBreakerState) => void;
+}
+
+/**
+ * Circuit breaker statistics
+ */
+export interface CircuitBreakerStats {
+ state: CircuitBreakerState;
+ failures: number;
+ successes: number;
+ totalRequests: number;
+ rejectedRequests: number;
+ lastFailure: Date | null;
+ lastSuccess: Date | null;
+ openSince: Date | null;
+}
+
+/**
+ * Default options
+ */
+const DEFAULT_OPTIONS: Omit<CircuitBreakerOptions, 'name'> = {
+ failureThreshold: 5,
+ successThreshold: 3,
+ timeout: 30000,
+ rollingWindow: 60000,
+ volumeThreshold: 10,
+};
+
+/**
+ * Request tracking entry
+ */
+interface RequestEntry {
+ timestamp: number;
+ success: boolean;
+}
+
+/**
+ * Circuit Breaker
+ *
+ * Implements the circuit breaker pattern to prevent cascading failures.
+ *
+ * @example
+ * const breaker = new CircuitBreaker({
+ * name: 'external-api',
+ * failureThreshold: 5,
+ * timeout: 30000,
+ * });
+ *
+ * try {
+ * const result = await breaker.execute(() => fetchExternalAPI());
+ * } catch (error) {
+ * if (error.message === 'Circuit is open') {
+ * // Handle circuit open case
+ * }
+ * }
+ */
+export class CircuitBreaker extends EventEmitter {
+ private readonly options: CircuitBreakerOptions;
+ private state: CircuitBreakerState = CircuitBreakerState.CLOSED;
+ private requests: RequestEntry[] = [];
+ private halfOpenSuccesses = 0;
+ private openedAt: Date | null = null;
+ private lastFailure: Date | null = null;
+ private lastSuccess: Date | null = null;
+ private rejectedCount = 0;
+ private timeoutId?: ReturnType<typeof setTimeout>;
+
+ constructor(options: CircuitBreakerOptions) {
+ super();
+ this.options = { ...DEFAULT_OPTIONS, ...options };
+ }
+
+ /**
+ * Execute a function through the circuit breaker
+ */
+ async execute<T>(fn: () => Promise<T>): Promise<T> {
+ // Clean up old requests
+ this.cleanOldRequests();
+
+ // Check if circuit should be tested
+ this.checkState();
+
+ // If open, reject immediately or use fallback
+ if (this.state === CircuitBreakerState.OPEN) {
+ this.rejectedCount++;
+ const error = new Error(`Circuit breaker '${this.options.name}' is open`);
+
+ if (this.options.fallback) {
+ return this.options.fallback(error);
+ }
+
+ throw error;
+ }
+
+ try {
+ const result = await fn();
+ this.onSuccess();
+ return result;
+ } catch (error) {
+ const err = error instanceof Error ? error : new Error(String(error));
+
+ // Check if this should be counted as failure
+ const isFailure = this.options.isFailure?.(err) ?? true;
+
+ if (isFailure) {
+ this.onFailure(err);
+ }
+
+ throw error;
+ }
+ }
+
+ /**
+ * Get current state
+ */
+ getState(): CircuitBreakerState {
+ this.checkState();
+ return this.state;
+ }
+
+ /**
+ * Get statistics
+ */
+ getStats(): CircuitBreakerStats {
+ this.cleanOldRequests();
+
+ return {
+ state: this.state,
+ failures: this.requests.filter((r) => !r.success).length,
+ successes: this.requests.filter((r) => r.success).length,
+ totalRequests: this.requests.length,
+ rejectedRequests: this.rejectedCount,
+ lastFailure: this.lastFailure,
+ lastSuccess: this.lastSuccess,
+ openSince: this.openedAt,
+ };
+ }
+
+ /**
+ * Force reset the circuit breaker
+ */
+ reset(): void {
+ const previousState = this.state;
+ this.state = CircuitBreakerState.CLOSED;
+ this.requests = [];
+ this.halfOpenSuccesses = 0;
+ this.openedAt = null;
+
+ if (this.timeoutId) {
+ clearTimeout(this.timeoutId);
+ this.timeoutId = undefined;
+ }
+
+ if (previousState !== this.state) {
+ this.notifyStateChange(previousState, this.state);
+ }
+ }
+
+ /**
+ * Handle successful request
+ */
+ private onSuccess(): void {
+ this.lastSuccess = new Date();
+ this.requests.push({ timestamp: Date.now(), success: true });
+
+ if (this.state === CircuitBreakerState.HALF_OPEN) {
+ this.halfOpenSuccesses++;
+
+ if (this.halfOpenSuccesses >= this.options.successThreshold) {
+ this.transitionTo(CircuitBreakerState.CLOSED);
+ this.halfOpenSuccesses = 0;
+ }
+ }
+ }
+
+ /**
+ * Handle failed request
+ */
+ private onFailure(error: Error): void {
+ this.lastFailure = new Date();
+ this.requests.push({ timestamp: Date.now(), success: false });
+
+ if (this.state === CircuitBreakerState.HALF_OPEN) {
+ // Failed during half-open, go back to open
+ this.transitionTo(CircuitBreakerState.OPEN);
+ this.halfOpenSuccesses = 0;
+ return;
+ }
+
+ // Check if we should open the circuit
+ const failures = this.requests.filter((r) => !r.success).length;
+ const totalRequests = this.requests.length;
+
+ if (
+ totalRequests >= this.options.volumeThreshold &&
+ failures >= this.options.failureThreshold
+ ) {
+ this.transitionTo(CircuitBreakerState.OPEN);
+ }
+ }
+
+ /**
+ * Check if state should change based on timeout
+ */
+ private checkState(): void {
+ if (this.state === CircuitBreakerState.OPEN && this.openedAt) {
+ const elapsed = Date.now() - this.openedAt.getTime();
+
+ if (elapsed >= this.options.timeout) {
+ this.transitionTo(CircuitBreakerState.HALF_OPEN);
+ }
+ }
+ }
+
+ /**
+ * Transition to new state
+ */
+ private transitionTo(newState: CircuitBreakerState): void {
+ const previousState = this.state;
+
+ if (previousState === newState) {
+ return;
+ }
+
+ this.state = newState;
+
+ if (newState === CircuitBreakerState.OPEN) {
+ this.openedAt = new Date();
+ this.scheduleHalfOpen();
+ } else if (newState === CircuitBreakerState.CLOSED) {
+ this.openedAt = null;
+ this.requests = [];
+
+ if (this.timeoutId) {
+ clearTimeout(this.timeoutId);
+ this.timeoutId = undefined;
+ }
+ }
+
+ this.notifyStateChange(previousState, newState);
+ }
+
+ /**
+ * Schedule transition to half-open
+ */
+ private scheduleHalfOpen(): void {
+ if (this.timeoutId) {
+ clearTimeout(this.timeoutId);
+ }
+
+ this.timeoutId = setTimeout(() => {
+ if (this.state === CircuitBreakerState.OPEN) {
+ this.transitionTo(CircuitBreakerState.HALF_OPEN);
+ }
+ }, this.options.timeout);
+ }
+
+ /**
+ * Notify state change
+ */
+ private notifyStateChange(from: CircuitBreakerState, to: CircuitBreakerState): void {
+ this.emit('stateChange', { from, to });
+ this.options.onStateChange?.(from, to);
+ }
+
+ /**
+ * Clean old requests outside rolling window
+ */
+ private cleanOldRequests(): void {
+ const cutoff = Date.now() - this.options.rollingWindow;
+ this.requests = this.requests.filter((r) => r.timestamp >= cutoff);
+ }
+}
diff --git a/v3/@claude-flow/shared/src/resilience/index.ts b/v3/@claude-flow/shared/src/resilience/index.ts
new file mode 100644
index 0000000000..b7f0d6aac3
--- /dev/null
+++ b/v3/@claude-flow/shared/src/resilience/index.ts
@@ -0,0 +1,38 @@
+/**
+ * Resilience Patterns
+ *
+ * Production-ready resilience utilities:
+ * - Retry with exponential backoff
+ * - Circuit breaker pattern
+ * - Rate limiting
+ *
+ * @module v3/shared/resilience
+ */
+
+export {
+ retry,
+ RetryOptions,
+ RetryError,
+ type RetryResult,
+} from './retry.js';
+
+export {
+ CircuitBreaker,
+ CircuitBreakerOptions,
+ CircuitBreakerState,
+ type CircuitBreakerStats,
+} from './circuit-breaker.js';
+
+export {
+ RateLimiter,
+ RateLimiterOptions,
+ SlidingWindowRateLimiter,
+ TokenBucketRateLimiter,
+ type RateLimitResult,
+} from './rate-limiter.js';
+
+export {
+ Bulkhead,
+ BulkheadOptions,
+ type BulkheadStats,
+} from './bulkhead.js';
diff --git a/v3/@claude-flow/shared/src/resilience/rate-limiter.ts b/v3/@claude-flow/shared/src/resilience/rate-limiter.ts
new file mode 100644
index 0000000000..82996e0c50
--- /dev/null
+++ b/v3/@claude-flow/shared/src/resilience/rate-limiter.ts
@@ -0,0 +1,420 @@
+/**
+ * Rate Limiter
+ *
+ * Production-ready rate limiting implementations.
+ *
+ * @module v3/shared/resilience/rate-limiter
+ */
+
+/**
+ * Rate limiter options
+ */
+export interface RateLimiterOptions {
+ /** Maximum requests allowed in the window */
+ maxRequests: number;
+
+ /** Time window in milliseconds */
+ windowMs: number;
+
+ /** Enable sliding window (vs fixed window) */
+ slidingWindow?: boolean;
+
+ /** Key generator for per-key limiting */
+ keyGenerator?: (context: unknown) => string;
+
+ /** Skip limiter for certain requests */
+ skip?: (context: unknown) => boolean;
+
+ /** Handler when rate limit is exceeded */
+ onRateLimited?: (key: string, remaining: number, resetAt: Date) => void;
+}
+
+/**
+ * Rate limit result
+ */
+export interface RateLimitResult {
+ allowed: boolean;
+ remaining: number;
+ resetAt: Date;
+ retryAfter: number; // ms until reset
+ total: number;
+ used: number;
+}
+
+/**
+ * Base Rate Limiter interface
+ */
+export interface RateLimiter {
+ /** Check if request is allowed */
+ check(key?: string): RateLimitResult;
+
+ /** Consume a request token */
+ consume(key?: string): RateLimitResult;
+
+ /** Reset a specific key or all keys */
+ reset(key?: string): void;
+
+ /** Get current status */
+ status(key?: string): RateLimitResult;
+}
+
+/**
+ * Request entry for tracking
+ */
+interface RequestEntry {
+ timestamp: number;
+ key: string;
+}
+
+/**
+ * Sliding Window Rate Limiter
+ *
+ * Uses sliding window algorithm for smooth rate limiting.
+ *
+ * @example
+ * const limiter = new SlidingWindowRateLimiter({
+ * maxRequests: 100,
+ * windowMs: 60000, // 100 requests per minute
+ * });
+ *
+ * const result = limiter.consume('user-123');
+ * if (!result.allowed) {
+ * throw new Error(`Rate limited. Retry in ${result.retryAfter}ms`);
+ * }
+ */
+export class SlidingWindowRateLimiter implements RateLimiter {
+ private readonly options: RateLimiterOptions;
+ private readonly requests: Map<string, RequestEntry[]> = new Map();
+ private cleanupInterval?: ReturnType<typeof setInterval>;
+
+ constructor(options: RateLimiterOptions) {
+ this.options = {
+ slidingWindow: true,
+ ...options,
+ };
+
+ // Periodic cleanup of old entries
+ this.cleanupInterval = setInterval(() => {
+ this.cleanup();
+ }, this.options.windowMs);
+ }
+
+ /**
+ * Check if a request would be allowed without consuming
+ */
+ check(key: string = 'default'): RateLimitResult {
+ this.cleanupKey(key);
+ const entries = this.requests.get(key) || [];
+
+ return {
+ allowed: entries.length < this.options.maxRequests,
+ remaining: Math.max(0, this.options.maxRequests - entries.length),
+ resetAt: this.getResetTime(entries),
+ retryAfter: this.getRetryAfter(entries),
+ total: this.options.maxRequests,
+ used: entries.length,
+ };
+ }
+
+ /**
+ * Consume a request token
+ */
+ consume(key: string = 'default'): RateLimitResult {
+ // Clean old entries first
+ this.cleanupKey(key);
+
+ let entries = this.requests.get(key);
+ if (!entries) {
+ entries = [];
+ this.requests.set(key, entries);
+ }
+
+ // Check if allowed
+ if (entries.length >= this.options.maxRequests) {
+ const result: RateLimitResult = {
+ allowed: false,
+ remaining: 0,
+ resetAt: this.getResetTime(entries),
+ retryAfter: this.getRetryAfter(entries),
+ total: this.options.maxRequests,
+ used: entries.length,
+ };
+
+ this.options.onRateLimited?.(key, 0, result.resetAt);
+ return result;
+ }
+
+ // Add new entry
+ entries.push({ timestamp: Date.now(), key });
+
+ return {
+ allowed: true,
+ remaining: this.options.maxRequests - entries.length,
+ resetAt: this.getResetTime(entries),
+ retryAfter: 0,
+ total: this.options.maxRequests,
+ used: entries.length,
+ };
+ }
+
+ /**
+ * Reset rate limit for a key
+ */
+ reset(key?: string): void {
+ if (key) {
+ this.requests.delete(key);
+ } else {
+ this.requests.clear();
+ }
+ }
+
+ /**
+ * Get current status
+ */
+ status(key: string = 'default'): RateLimitResult {
+ return this.check(key);
+ }
+
+ /**
+ * Cleanup resources
+ */
+ destroy(): void {
+ if (this.cleanupInterval) {
+ clearInterval(this.cleanupInterval);
+ this.cleanupInterval = undefined;
+ }
+ this.requests.clear();
+ }
+
+ /**
+ * Clean old entries for a specific key
+ */
+ private cleanupKey(key: string): void {
+ const entries = this.requests.get(key);
+ if (!entries) return;
+
+ const cutoff = Date.now() - this.options.windowMs;
+ const filtered = entries.filter((e) => e.timestamp >= cutoff);
+
+ if (filtered.length === 0) {
+ this.requests.delete(key);
+ } else if (filtered.length !== entries.length) {
+ this.requests.set(key, filtered);
+ }
+ }
+
+ /**
+ * Clean all old entries
+ */
+ private cleanup(): void {
+ for (const key of this.requests.keys()) {
+ this.cleanupKey(key);
+ }
+ }
+
+ /**
+ * Get reset time based on oldest entry
+ */
+ private getResetTime(entries: RequestEntry[]): Date {
+ if (entries.length === 0) {
+ return new Date(Date.now() + this.options.windowMs);
+ }
+
+ const oldest = entries[0]!;
+ return new Date(oldest.timestamp + this.options.windowMs);
+ }
+
+ /**
+ * Get retry after time in ms
+ */
+ private getRetryAfter(entries: RequestEntry[]): number {
+ if (entries.length < this.options.maxRequests) {
+ return 0;
+ }
+
+ const oldest = entries[0]!;
+ const resetAt = oldest.timestamp + this.options.windowMs;
+ return Math.max(0, resetAt - Date.now());
+ }
+}
+
+/**
+ * Token Bucket Rate Limiter
+ *
+ * Uses token bucket algorithm for burst-friendly rate limiting.
+ *
+ * @example
+ * const limiter = new TokenBucketRateLimiter({
+ * maxRequests: 10, // bucket size
+ * windowMs: 1000, // refill interval
+ * });
+ */
+export class TokenBucketRateLimiter implements RateLimiter {
+ private readonly options: RateLimiterOptions;
+ private readonly buckets: Map<string, { tokens: number; lastRefill: number }> = new Map();
+ private cleanupInterval?: ReturnType<typeof setInterval>;
+
+ constructor(options: RateLimiterOptions) {
+ this.options = options;
+
+ // Periodic cleanup
+ this.cleanupInterval = setInterval(() => {
+ this.cleanup();
+ }, this.options.windowMs * 10);
+ }
+
+ /**
+ * Check if a request would be allowed
+ */
+ check(key: string = 'default'): RateLimitResult {
+ this.refill(key);
+ const bucket = this.getBucket(key);
+
+ return {
+ allowed: bucket.tokens >= 1,
+ remaining: Math.floor(bucket.tokens),
+ resetAt: new Date(bucket.lastRefill + this.options.windowMs),
+ retryAfter: bucket.tokens >= 1 ? 0 : this.options.windowMs,
+ total: this.options.maxRequests,
+ used: this.options.maxRequests - Math.floor(bucket.tokens),
+ };
+ }
+
+ /**
+ * Consume a token
+ */
+ consume(key: string = 'default'): RateLimitResult {
+ this.refill(key);
+ const bucket = this.getBucket(key);
+
+ if (bucket.tokens < 1) {
+ const result: RateLimitResult = {
+ allowed: false,
+ remaining: 0,
+ resetAt: new Date(bucket.lastRefill + this.options.windowMs),
+ retryAfter: this.options.windowMs,
+ total: this.options.maxRequests,
+ used: this.options.maxRequests,
+ };
+
+ this.options.onRateLimited?.(key, 0, result.resetAt);
+ return result;
+ }
+
+ bucket.tokens -= 1;
+
+ return {
+ allowed: true,
+ remaining: Math.floor(bucket.tokens),
+ resetAt: new Date(bucket.lastRefill + this.options.windowMs),
+ retryAfter: 0,
+ total: this.options.maxRequests,
+ used: this.options.maxRequests - Math.floor(bucket.tokens),
+ };
+ }
+
+ /**
+ * Reset bucket for a key
+ */
+ reset(key?: string): void {
+ if (key) {
+ this.buckets.delete(key);
+ } else {
+ this.buckets.clear();
+ }
+ }
+
+ /**
+ * Get current status
+ */
+ status(key: string = 'default'): RateLimitResult {
+ return this.check(key);
+ }
+
+ /**
+ * Cleanup resources
+ */
+ destroy(): void {
+ if (this.cleanupInterval) {
+ clearInterval(this.cleanupInterval);
+ this.cleanupInterval = undefined;
+ }
+ this.buckets.clear();
+ }
+
+ /**
+ * Get or create bucket for key
+ */
+ private getBucket(key: string): { tokens: number; lastRefill: number } {
+ let bucket = this.buckets.get(key);
+ if (!bucket) {
+ bucket = { tokens: this.options.maxRequests, lastRefill: Date.now() };
+ this.buckets.set(key, bucket);
+ }
+ return bucket;
+ }
+
+ /**
+ * Refill tokens based on elapsed time
+ */
+ private refill(key: string): void {
+ const bucket = this.getBucket(key);
+ const now = Date.now();
+ const elapsed = now - bucket.lastRefill;
+
+ if (elapsed >= this.options.windowMs) {
+ // Full refill after window
+ const intervals = Math.floor(elapsed / this.options.windowMs);
+ bucket.tokens = Math.min(
+ this.options.maxRequests,
+ bucket.tokens + intervals * this.options.maxRequests
+ );
+ bucket.lastRefill = now;
+ }
+ }
+
+ /**
+ * Clean inactive buckets
+ */
+ private cleanup(): void {
+ const cutoff = Date.now() - this.options.windowMs * 10;
+
+ for (const [key, bucket] of this.buckets) {
+ if (bucket.lastRefill < cutoff && bucket.tokens >= this.options.maxRequests) {
+ this.buckets.delete(key);
+ }
+ }
+ }
+}
+
+/**
+ * Rate limiter middleware for Express-like frameworks
+ */
+export function createRateLimiterMiddleware(limiter: RateLimiter) {
+ return (req: { ip?: string; headers?: Record<string, string> }, res: {
+ status: (code: number) => { json: (body: unknown) => void };
+ setHeader: (name: string, value: string) => void;
+ }, next: () => void): void => {
+ // Get key from IP or header
+ const key = req.ip || req.headers?.['x-forwarded-for'] || 'anonymous';
+
+ const result = limiter.consume(key);
+
+ // Set rate limit headers
+ res.setHeader('X-RateLimit-Limit', String(result.total));
+ res.setHeader('X-RateLimit-Remaining', String(result.remaining));
+ res.setHeader('X-RateLimit-Reset', String(Math.ceil(result.resetAt.getTime() / 1000)));
+
+ if (!result.allowed) {
+ res.setHeader('Retry-After', String(Math.ceil(result.retryAfter / 1000)));
+ res.status(429).json({
+ error: 'Too Many Requests',
+ retryAfter: result.retryAfter,
+ resetAt: result.resetAt.toISOString(),
+ });
+ return;
+ }
+
+ next();
+ };
+}
diff --git a/v3/@claude-flow/shared/src/resilience/retry.ts b/v3/@claude-flow/shared/src/resilience/retry.ts
new file mode 100644
index 0000000000..8d43790bbd
--- /dev/null
+++ b/v3/@claude-flow/shared/src/resilience/retry.ts
@@ -0,0 +1,224 @@
+/**
+ * Retry with Exponential Backoff
+ *
+ * Production-ready retry logic with jitter, max retries, and error filtering.
+ *
+ * @module v3/shared/resilience/retry
+ */
+
+/**
+ * Retry options
+ */
+export interface RetryOptions {
+ /** Maximum number of retry attempts (default: 3) */
+ maxAttempts: number;
+
+ /** Initial delay in milliseconds (default: 100) */
+ initialDelay: number;
+
+ /** Maximum delay in milliseconds (default: 10000) */
+ maxDelay: number;
+
+ /** Backoff multiplier (default: 2) */
+ backoffMultiplier: number;
+
+ /** Jitter factor 0-1 to randomize delays (default: 0.1) */
+ jitter: number;
+
+ /** Timeout for each attempt in milliseconds (default: 30000) */
+ timeout: number;
+
+ /** Errors that should trigger a retry (default: all errors) */
+ retryableErrors?: (error: Error) => boolean;
+
+ /** Callback for each retry attempt */
+ onRetry?: (error: Error, attempt: number, delay: number) => void;
+}
+
+/**
+ * Retry result
+ */
+export interface RetryResult<T> {
+ success: boolean;
+ result?: T;
+ attempts: number;
+ totalTime: number;
+ errors: Error[];
+}
+
+/**
+ * Retry error with attempt history
+ */
+export class RetryError extends Error {
+ constructor(
+ message: string,
+ public readonly attempts: number,
+ public readonly errors: Error[],
+ public readonly totalTime: number
+ ) {
+ super(message);
+ this.name = 'RetryError';
+ }
+}
+
+/**
+ * Default retry options
+ */
+const DEFAULT_OPTIONS: RetryOptions = {
+ maxAttempts: 3,
+ initialDelay: 100,
+ maxDelay: 10000,
+ backoffMultiplier: 2,
+ jitter: 0.1,
+ timeout: 30000,
+};
+
+/**
+ * Retry a function with exponential backoff
+ *
+ * @param fn Function to retry
+ * @param options Retry configuration
+ * @returns Result with success/failure and metadata
+ *
+ * @example
+ * const result = await retry(
+ * () => fetchData(),
+ * { maxAttempts: 5, initialDelay: 200 }
+ * );
+ *
+ * if (result.success) {
+ * console.log('Data:', result.result);
+ * } else {
+ * console.log('Failed after', result.attempts, 'attempts');
+ * }
+ */
+export async function retry<T>(
+ fn: () => Promise<T>,
+ options: Partial<RetryOptions> = {}
+): Promise<RetryResult<T>> {
+ const opts = { ...DEFAULT_OPTIONS, ...options };
+ const errors: Error[] = [];
+ const startTime = Date.now();
+
+ for (let attempt = 1; attempt <= opts.maxAttempts; attempt++) {
+ try {
+ // Execute with timeout
+ const result = await withTimeout(fn(), opts.timeout, attempt);
+
+ return {
+ success: true,
+ result,
+ attempts: attempt,
+ totalTime: Date.now() - startTime,
+ errors,
+ };
+ } catch (error) {
+ const err = error instanceof Error ? error : new Error(String(error));
+ errors.push(err);
+
+ // Check if error is retryable
+ if (opts.retryableErrors && !opts.retryableErrors(err)) {
+ return {
+ success: false,
+ attempts: attempt,
+ totalTime: Date.now() - startTime,
+ errors,
+ };
+ }
+
+ // If this was the last attempt, don't delay
+ if (attempt >= opts.maxAttempts) {
+ break;
+ }
+
+ // Calculate delay with exponential backoff and jitter
+ const baseDelay = opts.initialDelay * Math.pow(opts.backoffMultiplier, attempt - 1);
+ const jitter = baseDelay * opts.jitter * (Math.random() * 2 - 1);
+ const delay = Math.min(baseDelay + jitter, opts.maxDelay);
+
+ // Callback before retry
+ if (opts.onRetry) {
+ opts.onRetry(err, attempt, delay);
+ }
+
+ // Wait before next attempt
+ await sleep(delay);
+ }
+ }
+
+ return {
+ success: false,
+ attempts: opts.maxAttempts,
+ totalTime: Date.now() - startTime,
+ errors,
+ };
+}
+
+/**
+ * Wrap a function with retry behavior
+ *
+ * @param fn Function to wrap
+ * @param options Retry configuration
+ * @returns Wrapped function that retries on failure
+ */
+export function withRetry<T extends (...args: unknown[]) => Promise<unknown>>(
+ fn: T,
+ options: Partial<RetryOptions> = {}
+): (...args: Parameters<T>) => Promise<RetryResult<Awaited<ReturnType<T>>>> {
+ return async (...args: Parameters<T>) => {
+ return retry(() => fn(...args) as Promise<Awaited<ReturnType<T>>>, options);
+ };
+}
+
+/**
+ * Execute with timeout
+ */
+async function withTimeout<T>(promise: Promise<T>, timeout: number, attempt: number): Promise<T> {
+ const timeoutPromise = new Promise<never>((_, reject) => {
+ setTimeout(() => {
+ reject(new Error(`Attempt ${attempt} timed out after ${timeout}ms`));
+ }, timeout);
+ });
+
+ return Promise.race([promise, timeoutPromise]);
+}
+
+/**
+ * Sleep for specified milliseconds
+ */
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+/**
+ * Common retryable error predicates
+ */
+export const RetryableErrors = {
+ /** Network errors (ECONNRESET, ETIMEDOUT, etc.) */
+ network: (error: Error): boolean => {
+ const networkCodes = ['ECONNRESET', 'ETIMEDOUT', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN'];
+ return networkCodes.some((code) => error.message.includes(code));
+ },
+
+ /** Rate limit errors (429) */
+ rateLimit: (error: Error): boolean => {
+ return error.message.includes('429') || error.message.toLowerCase().includes('rate limit');
+ },
+
+ /** Server errors (5xx) */
+ serverError: (error: Error): boolean => {
+ return /5\d\d/.test(error.message) || error.message.includes('Internal Server Error');
+ },
+
+ /** Transient errors (network + rate limit + 5xx) */
+ transient: (error: Error): boolean => {
+ return (
+ RetryableErrors.network(error) ||
+ RetryableErrors.rateLimit(error) ||
+ RetryableErrors.serverError(error)
+ );
+ },
+
+ /** All errors are retryable */
+ all: (): boolean => true,
+};