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:

rUv44de76a1a44c
diff --git a/v3/@claude-flow/hooks/src/test-push.ts b/v3/@claude-flow/hooks/src/test-push.ts
deleted file mode 100644
index 5610d4ed7d..0000000000
--- a/v3/@claude-flow/hooks/src/test-push.ts
+++ /dev/null
@@ -1 +0,0 @@
-// Push test Mon Jan 5 22:05:43 UTC 2026
diff --git a/v3/@claude-flow/mcp/__tests__/integration.test.ts b/v3/@claude-flow/mcp/__tests__/integration.test.ts
new file mode 100644
index 0000000000..99046db50f
--- /dev/null
+++ b/v3/@claude-flow/mcp/__tests__/integration.test.ts
@@ -0,0 +1,449 @@
+/**
+ * @claude-flow/mcp - Integration Tests
+ *
+ * End-to-end tests for MCP 2025-11-25 features
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import {
+ createMCPServer,
+ createTextResource,
+ definePrompt,
+ textMessage,
+ resourceMessage,
+} from '../src/index.js';
+import type { ILogger, MCPRequest, MCPResponse } from '../src/types.js';
+
+const createMockLogger = (): ILogger => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+});
+
+describe('MCP 2025-11-25 Integration', () => {
+ let server: ReturnType<typeof createMCPServer>;
+ let logger: ILogger;
+
+ beforeEach(async () => {
+ logger = createMockLogger();
+ server = createMCPServer(
+ { name: 'Integration Test Server', transport: 'in-process' },
+ logger
+ );
+ });
+
+ afterEach(async () => {
+ await server.stop();
+ });
+
+ describe('Server Lifecycle', () => {
+ it('should start and report healthy', async () => {
+ await server.start();
+ const health = await server.getHealthStatus();
+
+ expect(health.healthy).toBe(true);
+ expect(health.metrics?.registeredTools).toBeGreaterThan(0);
+ });
+
+ it('should expose all registries', async () => {
+ await server.start();
+
+ expect(server.getResourceRegistry()).toBeDefined();
+ expect(server.getPromptRegistry()).toBeDefined();
+ expect(server.getTaskManager()).toBeDefined();
+ });
+ });
+
+ describe('Resources Integration', () => {
+ it('should register and read resources', async () => {
+ await server.start();
+ const registry = server.getResourceRegistry();
+
+ // Register multiple resources
+ const resources = [
+ createTextResource('file://config.json', 'Config', '{"key": "value"}', { mimeType: 'application/json' }),
+ createTextResource('file://readme.md', 'README', '# Hello World', { mimeType: 'text/markdown' }),
+ createTextResource('file://data.txt', 'Data', 'Some data content'),
+ ];
+
+ for (const { resource, handler } of resources) {
+ registry.registerResource(resource, handler);
+ }
+
+ // Verify listing
+ const list = registry.list();
+ expect(list.resources.length).toBe(3);
+
+ // Verify reading
+ const config = await registry.read('file://config.json');
+ expect(config.contents[0].text).toBe('{"key": "value"}');
+ expect(config.contents[0].mimeType).toBe('application/json');
+
+ const readme = await registry.read('file://readme.md');
+ expect(readme.contents[0].text).toBe('# Hello World');
+ });
+
+ it('should handle resource subscriptions', async () => {
+ await server.start();
+ const registry = server.getResourceRegistry();
+
+ const { resource, handler } = createTextResource('file://live.txt', 'Live', 'Initial');
+ registry.registerResource(resource, handler);
+
+ const callback = vi.fn();
+ const subId = registry.subscribe('file://live.txt', callback);
+
+ expect(subId).toBeDefined();
+ expect(registry.getSubscriptionCount('file://live.txt')).toBe(1);
+
+ // Unsubscribe
+ const unsubResult = registry.unsubscribe(subId);
+ expect(unsubResult).toBe(true);
+ expect(registry.getSubscriptionCount('file://live.txt')).toBe(0);
+ });
+
+ it('should cache resources', async () => {
+ await server.start();
+ const registry = server.getResourceRegistry();
+
+ let callCount = 0;
+ registry.registerResource(
+ { uri: 'file://counter.txt', name: 'Counter', mimeType: 'text/plain' },
+ async () => {
+ callCount++;
+ return [{ uri: 'file://counter.txt', text: `Count: ${callCount}` }];
+ }
+ );
+
+ // First read
+ await registry.read('file://counter.txt');
+ expect(callCount).toBe(1);
+
+ // Second read should be cached
+ await registry.read('file://counter.txt');
+ expect(callCount).toBe(1); // Still 1 due to cache
+ });
+ });
+
+ describe('Prompts Integration', () => {
+ it('should register and execute prompts', async () => {
+ await server.start();
+ const registry = server.getPromptRegistry();
+
+ // Register code review prompt
+ registry.register(definePrompt(
+ 'code_review',
+ 'Review code quality',
+ async (args) => [
+ textMessage('user', `Review this ${args.language || 'code'}:\n\n${args.code}`),
+ ],
+ {
+ title: 'Code Review',
+ arguments: [
+ { name: 'code', required: true },
+ { name: 'language', required: false },
+ ],
+ }
+ ));
+
+ // Register translation prompt
+ registry.register(definePrompt(
+ 'translate',
+ 'Translate text',
+ async (args) => [
+ textMessage('user', `Translate to ${args.target}: ${args.text}`),
+ ],
+ {
+ arguments: [
+ { name: 'text', required: true },
+ { name: 'target', required: true },
+ ],
+ }
+ ));
+
+ // List prompts
+ const list = registry.list();
+ expect(list.prompts.length).toBe(2);
+
+ // Execute code review
+ const review = await registry.get('code_review', {
+ code: 'const x = 1;',
+ language: 'TypeScript',
+ });
+ expect(review.messages[0].content.type).toBe('text');
+ expect((review.messages[0].content as any).text).toContain('TypeScript');
+
+ // Execute translation
+ const translate = await registry.get('translate', {
+ text: 'Hello',
+ target: 'Spanish',
+ });
+ expect((translate.messages[0].content as any).text).toContain('Spanish');
+ });
+
+ it('should validate required arguments', async () => {
+ await server.start();
+ const registry = server.getPromptRegistry();
+
+ registry.register(definePrompt(
+ 'greet',
+ 'Greet someone',
+ async (args) => [textMessage('user', `Hello ${args.name}`)],
+ { arguments: [{ name: 'name', required: true }] }
+ ));
+
+ // Should throw without required argument
+ await expect(registry.get('greet', {})).rejects.toThrow('Missing required argument: name');
+
+ // Should work with argument
+ const result = await registry.get('greet', { name: 'World' });
+ expect((result.messages[0].content as any).text).toBe('Hello World');
+ });
+ });
+
+ describe('Tasks Integration', () => {
+ it('should create and complete tasks', async () => {
+ await server.start();
+ const taskManager = server.getTaskManager();
+
+ const taskId = taskManager.createTask(async (reportProgress) => {
+ reportProgress({ progress: 50, total: 100 });
+ return { success: true };
+ });
+
+ const result = await taskManager.waitForTask(taskId, 5000);
+ expect(result.state).toBe('completed');
+ expect(result.result).toEqual({ success: true });
+ });
+
+ it('should track progress', async () => {
+ await server.start();
+ const taskManager = server.getTaskManager();
+
+ const progressUpdates: number[] = [];
+
+ taskManager.on('task:progress', (event: { taskId: string; progress: { progress: number } }) => {
+ progressUpdates.push(event.progress.progress);
+ });
+
+ const taskId = taskManager.createTask(async (reportProgress) => {
+ for (let i = 25; i <= 100; i += 25) {
+ reportProgress({ progress: i, total: 100 });
+ await new Promise(r => setTimeout(r, 10));
+ }
+ return 'done';
+ });
+
+ await taskManager.waitForTask(taskId, 5000);
+ expect(progressUpdates.length).toBeGreaterThan(0);
+ });
+
+ it('should cancel running tasks', async () => {
+ await server.start();
+ const taskManager = server.getTaskManager();
+
+ const taskId = taskManager.createTask(async (reportProgress, signal) => {
+ await new Promise((resolve, reject) => {
+ const timeout = setTimeout(resolve, 10000);
+ signal.addEventListener('abort', () => {
+ clearTimeout(timeout);
+ reject(new Error('Cancelled'));
+ });
+ });
+ });
+
+ // Cancel immediately
+ const cancelled = taskManager.cancelTask(taskId, 'Test cancel');
+ expect(cancelled).toBe(true);
+
+ // Wait a bit and check status
+ await new Promise(r => setTimeout(r, 50));
+ const status = taskManager.getTask(taskId);
+ expect(status?.state).toBe('cancelled');
+ });
+
+ it('should handle concurrent tasks', async () => {
+ await server.start();
+ const taskManager = server.getTaskManager();
+
+ const taskIds = [];
+ for (let i = 0; i < 5; i++) {
+ const id = taskManager.createTask(async () => {
+ await new Promise(r => setTimeout(r, 10));
+ return `Task ${i} done`;
+ });
+ taskIds.push(id);
+ }
+
+ // Wait for all
+ const results = await Promise.all(
+ taskIds.map(id => taskManager.waitForTask(id, 5000))
+ );
+
+ expect(results.every(r => r.state === 'completed')).toBe(true);
+ });
+ });
+
+ describe('Full Server Flow', () => {
+ it('should handle complete MCP workflow', async () => {
+ await server.start();
+
+ // Setup resources
+ const resourceRegistry = server.getResourceRegistry();
+ const { resource, handler } = createTextResource(
+ 'context://project',
+ 'Project Context',
+ 'This is a TypeScript project using MCP.'
+ );
+ resourceRegistry.registerResource(resource, handler);
+
+ // Setup prompts
+ const promptRegistry = server.getPromptRegistry();
+ promptRegistry.register(definePrompt(
+ 'analyze',
+ 'Analyze project',
+ async (args) => {
+ // Could include embedded resource here
+ return [
+ textMessage('user', `Analyze: ${args.focus}`),
+ ];
+ },
+ { arguments: [{ name: 'focus', required: true }] }
+ ));
+
+ // Setup long-running task
+ const taskManager = server.getTaskManager();
+ const analysisTaskId = taskManager.createTask(async (reportProgress) => {
+ reportProgress({ progress: 0, message: 'Starting analysis' });
+ await new Promise(r => setTimeout(r, 20));
+ reportProgress({ progress: 50, message: 'Processing' });
+ await new Promise(r => setTimeout(r, 20));
+ reportProgress({ progress: 100, message: 'Complete' });
+ return { findings: ['All good!'] };
+ });
+
+ // Verify all components work together
+ const resourceList = resourceRegistry.list();
+ expect(resourceList.resources.length).toBe(1);
+
+ const promptList = promptRegistry.list();
+ expect(promptList.prompts.length).toBe(1);
+
+ const taskResult = await taskManager.waitForTask(analysisTaskId, 5000);
+ expect(taskResult.state).toBe('completed');
+ expect((taskResult.result as any).findings).toContain('All good!');
+
+ // Check metrics
+ const health = await server.getHealthStatus();
+ expect(health.healthy).toBe(true);
+ });
+ });
+
+ describe('Security Validation', () => {
+ it('should not expose internal state', async () => {
+ await server.start();
+ const metrics = server.getMetrics();
+
+ // Metrics should only contain safe data
+ expect(metrics).not.toHaveProperty('_internal');
+ expect(metrics).not.toHaveProperty('password');
+ expect(metrics).not.toHaveProperty('secret');
+ });
+
+ it('should validate tool inputs', async () => {
+ await server.start();
+
+ // Register a tool with schema
+ server.registerTool({
+ name: 'secure-tool',
+ description: 'A tool with input validation',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ allowed: { type: 'string', maxLength: 100 },
+ },
+ required: ['allowed'],
+ },
+ handler: async (input) => ({ received: input }),
+ });
+
+ // Tool registry should have it
+ const tools = server.getMetrics().toolInvocations;
+ expect(tools).toBeDefined();
+ });
+
+ it('should handle resource access errors gracefully', async () => {
+ await server.start();
+ const registry = server.getResourceRegistry();
+
+ // Try to read non-existent resource
+ await expect(registry.read('file://nonexistent.txt'))
+ .rejects.toThrow('Resource not found');
+ });
+
+ it('should prevent duplicate subscriptions overflow', async () => {
+ await server.start();
+ const registry = server.getResourceRegistry();
+
+ const { resource, handler } = createTextResource('file://test.txt', 'Test', 'content');
+ registry.registerResource(resource, handler);
+
+ // Subscribe many times (should be limited by maxSubscriptionsPerResource)
+ for (let i = 0; i < 100; i++) {
+ registry.subscribe('file://test.txt', vi.fn());
+ }
+
+ expect(registry.getSubscriptionCount('file://test.txt')).toBe(100);
+ });
+
+ it('should enforce cache size limits (CVE fix)', async () => {
+ await server.start();
+ const registry = server.getResourceRegistry();
+
+ // Register many resources to test cache eviction
+ for (let i = 0; i < 10; i++) {
+ const { resource, handler } = createTextResource(
+ `file://cache-test-${i}.txt`,
+ `Cache Test ${i}`,
+ `Content ${i}`
+ );
+ registry.registerResource(resource, handler);
+ }
+
+ // Read all resources to populate cache
+ for (let i = 0; i < 10; i++) {
+ await registry.read(`file://cache-test-${i}.txt`);
+ }
+
+ // Cache should be limited (default 1000, but should work)
+ const stats = registry.getStats();
+ expect(stats.cacheSize).toBeLessThanOrEqual(1000);
+ });
+
+ it('should escape regex in template matching (ReDoS fix)', async () => {
+ await server.start();
+ const registry = server.getResourceRegistry();
+
+ // Register a template with potentially dangerous regex chars
+ registry.registerTemplate(
+ {
+ uriTemplate: 'db://users/{id}',
+ name: 'User Data',
+ mimeType: 'application/json',
+ },
+ async (uri) => [{ uri, text: '{}' }]
+ );
+
+ // This should not cause ReDoS - test with various inputs
+ const startTime = Date.now();
+ expect(registry.hasResource('db://users/123')).toBe(true);
+ expect(registry.hasResource('db://users/abc')).toBe(true);
+ expect(registry.hasResource('invalid://path')).toBe(false);
+ const elapsed = Date.now() - startTime;
+
+ // Should complete quickly (< 100ms), not hang due to ReDoS
+ expect(elapsed).toBeLessThan(100);
+ });
+ });
+});
diff --git a/v3/@claude-flow/mcp/src/resource-registry.ts b/v3/@claude-flow/mcp/src/resource-registry.ts
index 59a7462a15..b44965611c 100644
--- a/v3/@claude-flow/mcp/src/resource-registry.ts
+++ b/v3/@claude-flow/mcp/src/resource-registry.ts
@@ -24,6 +24,7 @@ export interface ResourceRegistryOptions {
maxSubscriptionsPerResource?: number;
cacheEnabled?: boolean;
cacheTTL?: number;
+ maxCacheSize?: number; // SECURITY: Prevent unbounded cache growth
}
interface CachedResource {
@@ -59,6 +60,7 @@ export class ResourceRegistry extends EventEmitter {
maxSubscriptionsPerResource: options.maxSubscriptionsPerResource ?? 100,
cacheEnabled: options.cacheEnabled ?? true,
cacheTTL: options.cacheTTL ?? 60000, // 1 minute default
+ maxCacheSize: options.maxCacheSize ?? 1000, // SECURITY: Default max 1000 entries
};
}
@@ -174,8 +176,18 @@ export class ResourceRegistry extends EventEmitter {
const contents = await handler(uri);
- // Cache the result
+ // Cache the result with size limit (LRU eviction)
if (this.options.cacheEnabled) {
+ // SECURITY: Enforce max cache size to prevent memory exhaustion
+ if (this.cache.size >= this.options.maxCacheSize) {
+ // Remove oldest entry (first entry in Map iteration order)
+ const oldestKey = this.cache.keys().next().value;
+ if (oldestKey) {
+ this.cache.delete(oldestKey);
+ this.logger.debug('Cache evicted oldest entry', { uri: oldestKey });
+ }
+ }
+
this.cache.set(uri, {
content: contents,
cachedAt: Date.now(),
@@ -340,20 +352,45 @@ export class ResourceRegistry extends EventEmitter {
return undefined;
}
+ /**
+ * Escape regex metacharacters to prevent ReDoS attacks
+ * SECURITY: Critical for preventing regex denial of service
+ */
+ private escapeRegex(str: string): string {
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ }
+
/**
* Check if URI matches any template
+ * SECURITY: Uses escaped regex to prevent ReDoS
*/
private matchesTemplate(uri: string, template?: string): boolean {
if (template) {
- // Simple template matching (supports {param} style)
- const regex = new RegExp('^' + template.replace(/\{[^}]+\}/g, '[^/]+') + '$');
- return regex.test(uri);
+ // SECURITY: Escape regex metacharacters before converting template
+ // First extract placeholders, escape the rest, then add placeholder pattern
+ const escaped = this.escapeRegex(template);
+ // Replace escaped placeholder braces with the pattern
+ const pattern = escaped.replace(/\\\{[^}]+\\\}/g, '[^/]+');
+ try {
+ const regex = new RegExp('^' + pattern + '$');
+ return regex.test(uri);
+ } catch {
+ // Invalid regex pattern - return false safely
+ return false;
+ }
}
for (const t of this.templates.keys()) {
- const regex = new RegExp('^' + t.replace(/\{[^}]+\}/g, '[^/]+') + '$');
- if (regex.test(uri)) {
- return true;
+ const escaped = this.escapeRegex(t);
+ const pattern = escaped.replace(/\\\{[^}]+\\\}/g, '[^/]+');
+ try {
+ const regex = new RegExp('^' + pattern + '$');
+ if (regex.test(uri)) {
+ return true;
+ }
+ } catch {
+ // Skip invalid patterns
+ continue;
}
}
return false;
@@ -426,6 +463,7 @@ export function createTextResource(
/**
* Helper to create a file resource
+ * SECURITY: Validates path to prevent path traversal attacks
*/
export function createFileResource(
uri: string,
@@ -434,6 +472,7 @@ export function createFileResource(
options?: {
description?: string;
mimeType?: string;
+ allowedBasePaths?: string[]; // Security: restrict to these base paths
}
): { resource: MCPResource; handler: ResourceHandler } {
const resource: MCPResource = {
@@ -445,7 +484,39 @@ export function createFileResource(
const handler: ResourceHandler = async () => {
const fs = await import('fs/promises');
- const content = await fs.readFile(filePath);
+ const path = await import('path');
+
+ // SECURITY: Normalize and validate the path
+ const normalizedPath = path.normalize(filePath);
+
+ // Prevent path traversal
+ if (normalizedPath.includes('..') || normalizedPath.includes('\0')) {
+ throw new Error('Invalid file path: path traversal detected');
+ }
+
+ // Prevent access to sensitive system paths
+ const blockedPaths = ['/etc/', '/proc/', '/sys/', '/dev/', '/root/', '/var/log/'];
+ const lowerPath = normalizedPath.toLowerCase();
+ for (const blocked of blockedPaths) {
+ if (lowerPath.startsWith(blocked) || lowerPath.includes('/.')) {
+ throw new Error('Access to system paths is not allowed');
+ }
+ }
+
+ // If allowedBasePaths specified, validate against them
+ if (options?.allowedBasePaths && options.allowedBasePaths.length > 0) {
+ const resolvedPath = path.resolve(normalizedPath);
+ const isAllowed = options.allowedBasePaths.some((basePath) => {
+ const resolvedBase = path.resolve(basePath);
+ return resolvedPath.startsWith(resolvedBase);
+ });
+
+ if (!isAllowed) {
+ throw new Error('File path is outside allowed directories');
+ }
+ }
+
+ const content = await fs.readFile(normalizedPath);
return [
{
uri,
diff --git a/v3/@claude-flow/mcp/src/transport/http.ts b/v3/@claude-flow/mcp/src/transport/http.ts
index 6879efc4f1..6426f664ff 100644
--- a/v3/@claude-flow/mcp/src/transport/http.ts
+++ b/v3/@claude-flow/mcp/src/transport/http.ts
@@ -283,10 +283,41 @@ export class HttpTransport extends EventEmitter implements ITransport {
private setupWebSocketHandlers(): void {
if (!this.wss) return;
- this.wss.on('connection', (ws) => {
+ // SECURITY: Handle WebSocket authentication via upgrade request
+ this.wss.on('connection', (ws, req) => {
+ // Validate authentication if enabled
+ if (this.config.auth?.enabled) {
+ const url = new URL(req.url || '', `http://${req.headers.host}`);
+ const token = url.searchParams.get('token') || req.headers['authorization']?.replace(/^Bearer\s+/i, '');
+
+ if (!token) {
+ this.logger.warn('WebSocket connection rejected: no authentication token');
+ ws.close(4001, 'Authentication required');
+ return;
+ }
+
+ // SECURITY: Timing-safe token validation
+ let valid = false;
+ if (this.config.auth.tokens?.length) {
+ for (const validToken of this.config.auth.tokens) {
+ if (this.timingSafeCompare(token, validToken)) {
+ valid = true;
+ break;
+ }
+ }
+ }
+
+ if (!valid) {
+ this.logger.warn('WebSocket connection rejected: invalid token');
+ ws.close(4003, 'Invalid token');
+ return;
+ }
+ }
+
this.activeConnections.add(ws);
this.logger.info('WebSocket client connected', {
total: this.activeConnections.size,
+ authenticated: !!this.config.auth?.enabled,
});
ws.on('message', async (data) => {
@@ -441,6 +472,26 @@ export class HttpTransport extends EventEmitter implements ITransport {
}
}
+ /**
+ * SECURITY: Timing-safe token comparison to prevent timing attacks
+ */
+ private timingSafeCompare(a: string, b: string): boolean {
+ const crypto = require('crypto');
+
+ // Ensure both strings are the same length for timing-safe comparison
+ const bufA = Buffer.from(a, 'utf-8');
+ const bufB = Buffer.from(b, 'utf-8');
+
+ // If lengths differ, still do a comparison to prevent length-based timing
+ if (bufA.length !== bufB.length) {
+ // Compare against itself to maintain constant time
+ crypto.timingSafeEqual(bufA, bufA);
+ return false;
+ }
+
+ return crypto.timingSafeEqual(bufA, bufB);
+ }
+
private validateAuth(req: Request): { valid: boolean; error?: string } {
const auth = req.headers.authorization;
@@ -456,7 +507,15 @@ export class HttpTransport extends EventEmitter implements ITransport {
const token = tokenMatch[1];
if (this.config.auth?.tokens?.length) {
- if (!this.config.auth.tokens.includes(token)) {
+ // SECURITY: Use timing-safe comparison to prevent timing attacks
+ let valid = false;
+ for (const validToken of this.config.auth.tokens) {
+ if (this.timingSafeCompare(token, validToken)) {
+ valid = true;
+ break;
+ }
+ }
+ if (!valid) {
return { valid: false, error: 'Invalid token' };
}
}
diff --git a/v3/@claude-flow/providers/src/ruvector-provider.ts b/v3/@claude-flow/providers/src/ruvector-provider.ts
index e5e74b88ae..f83e524f7a 100644
--- a/v3/@claude-flow/providers/src/ruvector-provider.ts
+++ b/v3/@claude-flow/providers/src/ruvector-provider.ts
@@ -91,7 +91,7 @@ interface RuVectorResponse {
}
export class RuVectorProvider extends BaseProvider {
- readonly name: LLMProvider = 'custom'; // RuVector is custom provider type
+ readonly name: LLMProvider = 'ruvector';
readonly capabilities: ProviderCapabilities = {
supportedModels: [
// RuVector-managed models
@@ -99,13 +99,18 @@ export class RuVectorProvider extends BaseProvider {
'ruvector-fast', // Optimized for speed
'ruvector-quality', // Optimized for quality
'ruvector-balanced', // Balanced speed/quality
- // Local models via ruvLLM
+ // Local models via ruvLLM or Ollama fallback
'llama3.2',
'mistral',
'phi-4',
'deepseek-coder',
'codellama',
'qwen2.5',
+ 'qwen2.5:0.5b', // CPU-friendly Qwen
+ 'qwen2.5:1.5b',
+ 'smollm:135m', // SmolLM models
+ 'smollm:360m',
+ 'tinyllama',
],
maxContextLength: {
'ruvector-auto': 128000,
@@ -159,9 +164,12 @@ export class RuVectorProvider extends BaseProvider {
},
};
- private baseUrl: string = 'http://localhost:8787';
+ private baseUrl: string = 'http://localhost:3000'; // ruvLLM default port
+ private ollamaUrl: string = 'http://localhost:11434';
private ruvectorConfig: RuVectorConfig = {};
private ruvllm: unknown; // Dynamic import of @ruvector/ruvllm
+ private useOllamaFallback: boolean = false;
+ private ruvllmAvailable: boolean = false;
constructor(options: BaseProviderOptions) {
super(options);
@@ -169,33 +177,56 @@ export class RuVectorProvider extends BaseProvider {
}
protected async doInitialize(): Promise<void> {
- this.baseUrl = this.config.apiUrl || 'http://localhost:8787';
+ // Configure URLs from options
+ this.baseUrl = this.config.apiUrl || 'http://localhost:3000';
+ this.ollamaUrl = (this.config.providerOptions as any)?.ollamaUrl || 'http://localhost:11434';
- // Try to dynamically import @ruvector/ruvllm
+ // Try to dynamically import @ruvector/ruvllm native module
try {
this.ruvllm = await import('@ruvector/ruvllm').catch(() => null);
if (this.ruvllm) {
- this.logger.info('RuVector ruvLLM module loaded');
+ this.logger.info('RuVector ruvLLM native module loaded');
+ this.ruvllmAvailable = true;
}
} catch {
- this.logger.warn('RuVector ruvLLM module not available, using HTTP API');
+ this.logger.debug('RuVector ruvLLM native module not available');
}
- // Check if RuVector server is running
+ // Check if RuVector HTTP server is running
const health = await this.doHealthCheck();
- if (!health.healthy) {
- this.logger.warn('RuVector server not detected. Using fallback mode.');
+ if (health.healthy) {
+ this.logger.info('RuVector server connected');
+ return;
+ }
+
+ // Fallback: Check if Ollama is running for local model execution
+ try {
+ const ollamaHealth = await fetch(`${this.ollamaUrl}/api/tags`, {
+ signal: AbortSignal.timeout(3000),
+ });
+ if (ollamaHealth.ok) {
+ this.useOllamaFallback = true;
+ this.logger.info('Using Ollama as fallback for local model execution');
+ }
+ } catch {
+ this.logger.warn('Neither RuVector nor Ollama available. Provider may not work.');
}
}
protected async doComplete(request: LLMRequest): Promise<LLMResponse> {
- const ruvectorRequest = this.buildRequest(request);
+ // Use Ollama fallback if RuVector server isn't available
+ if (this.useOllamaFallback) {
+ return this.completeWithOllama(request);
+ }
+
+ const ruvectorRequest = this.buildRuvectorQuery(request);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), this.config.timeout || 120000);
try {
- const response = await fetch(`${this.baseUrl}/v1/chat/completions`, {
+ // Use ruvLLM's /query endpoint (not OpenAI-compatible)
+ const response = await fetch(`${this.baseUrl}/query`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -215,6 +246,94 @@ export class RuVectorProvider extends BaseProvider {
return this.transformResponse(data, request);
} catch (error) {
clearTimeout(timeout);
+
+ // Auto-fallback to Ollama on connection error
+ if (error instanceof Error && (error.message.includes('ECONNREFUSED') || error.message.includes('fetch failed'))) {
+ this.useOllamaFallback = true;
+ this.logger.info('RuVector connection failed, falling back to Ollama');
+ return this.completeWithOllama(request);
+ }
+
+ throw this.transformError(error);
+ }
+ }
+
+ /**
+ * Fallback completion using Ollama API
+ */
+ private async completeWithOllama(request: LLMRequest): Promise<LLMResponse> {
+ const model = request.model || this.config.model;
+
+ const ollamaRequest = {
+ model,
+ messages: request.messages.map((msg) => ({
+ role: msg.role === 'tool' ? 'assistant' : msg.role,
+ content: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content),
+ })),
+ stream: false,
+ options: {
+ temperature: request.temperature ?? this.config.temperature ?? 0.7,
+ num_predict: request.maxTokens || this.config.maxTokens || 2048,
+ },
+ };
+
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), this.config.timeout || 120000);
+
+ try {
+ const response = await fetch(`${this.ollamaUrl}/api/chat`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(ollamaRequest),
+ signal: controller.signal,
+ });
+
+ clearTimeout(timeout);
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new LLMProviderError(
+ `Ollama error: ${errorText}`,
+ `OLLAMA_${response.status}`,
+ 'ruvector',
+ response.status,
+ true
+ );
+ }
+
+ const data = await response.json() as {
+ message?: { content: string };
+ prompt_eval_count?: number;
+ eval_count?: number;
+ };
+
+ const promptTokens = data.prompt_eval_count || this.estimateTokens(JSON.stringify(request.messages));
+ const completionTokens = data.eval_count || this.estimateTokens(data.message?.content || '');
+
+ return {
+ id: `ruvector-ollama-${Date.now()}`,
+ model: model as LLMModel,
+ provider: 'ruvector',
+ content: data.message?.content || '',
+ usage: {
+ promptTokens,
+ completionTokens,
+ totalTokens: promptTokens + completionTokens,
+ },
+ cost: {
+ promptCost: 0,
+ completionCost: 0,
+ totalCost: 0,
+ currency: 'USD',
+ },
+ finishReason: 'stop',
+ metadata: {
+ backend: 'ollama',
+ sona: { enabled: false },
+ },
+ };
+ } catch (error) {
+ clearTimeout(timeout);
throw this.transformError(error);
}
}
@@ -409,6 +528,29 @@ export class RuVectorProvider extends BaseProvider {
}
}
+ /**
+ * Build ruvLLM native API query format
+ * See: https://github.com/ruvnet/ruvector/tree/main/examples/ruvLLM
+ */
+ private buildRuvectorQuery(request: LLMRequest): { query: string; session_id?: string } {
+ // ruvLLM uses simple query format, not OpenAI-compatible
+ const lastUserMessage = [...request.messages].reverse().find(m => m.role === 'user');
+ const systemPrompt = request.messages.find(m => m.role === 'system');
+
+ let query = '';
+ if (systemPrompt) {
+ query += `[System]: ${typeof systemPrompt.content === 'string' ? systemPrompt.content : JSON.stringify(systemPrompt.content)}\n\n`;
+ }
+ query += typeof lastUserMessage?.content === 'string'
+ ? lastUserMessage.content
+ : JSON.stringify(lastUserMessage?.content || '');
+
+ return {
+ query,
+ session_id: request.requestId,
+ };
+ }
+
private buildRequest(request: LLMRequest, stream = false): RuVectorRequest {
const ruvectorRequest: RuVectorRequest = {
model: request.model || this.config.model,