diff --git a/src/cli/commands/mcp.ts b/src/cli/commands/mcp.ts index 16cbb5516..3b47e1503 100644 --- a/src/cli/commands/mcp.ts +++ b/src/cli/commands/mcp.ts @@ -8,11 +8,12 @@ import type { CommandModule, Argv } from "yargs"; import type { UnknownRecord } from "../../lib/types/common.js"; import type { MCPServerInfo, + MCPStatus, MCPTransportType, } from "../../lib/types/mcpTypes.js"; import { createExternalServerInfo } from "../../lib/utils/mcpDefaults.js"; import type { MCPCommandArgs } from "../../lib/types/cli.js"; -import { NeuroLink, type MCPStatus } from "../../lib/neurolink.js"; +import { NeuroLink } from "../../lib/neurolink.js"; import { logger } from "../../lib/utils/logger.js"; import chalk from "chalk"; import ora from "ora"; diff --git a/src/cli/commands/models.ts b/src/cli/commands/models.ts index f4bded876..042039a1e 100644 --- a/src/cli/commands/models.ts +++ b/src/cli/commands/models.ts @@ -5,7 +5,7 @@ */ import type { CommandModule, Argv } from "yargs"; -import type { AIProviderName } from "../../lib/types/index.js"; +import type { AIProviderName } from "../../lib/constants/enums.js"; import type { ModelsCommandArgs } from "../../lib/types/cli.js"; import type { ModelPricing } from "../../lib/types/providers.js"; import { @@ -19,11 +19,13 @@ import { getModelsByProvider, getAvailableProviders, formatModelForDisplay, - type ModelSearchFilters, - type ModelCapabilities, - type UseCaseSuitability, } from "../../lib/models/modelRegistry.js"; -import type { RecommendationContext } from "../../lib/models/modelResolver.js"; +import type { + RecommendationContext, + ModelSearchFilters, + ModelCapabilities, + UseCaseSuitability, +} from "../../lib/types/modelTypes.js"; import chalk from "chalk"; import ora from "ora"; diff --git a/src/cli/commands/setup-google-ai.ts b/src/cli/commands/setup-google-ai.ts index 009077345..a415d6655 100644 --- a/src/cli/commands/setup-google-ai.ts +++ b/src/cli/commands/setup-google-ai.ts @@ -15,7 +15,7 @@ import inquirer from "inquirer"; import chalk from "chalk"; import ora from "ora"; import { logger } from "../../lib/utils/logger.js"; -import { GoogleAIModels } from "../../lib/types/providers.js"; +import { GoogleAIModels } from "../../lib/constants/enums.js"; import { updateEnvFile as updateEnvFileManager, displayEnvUpdateSummary, diff --git a/src/cli/loop/optionsSchema.ts b/src/cli/loop/optionsSchema.ts index 0096d67db..d910a3e80 100644 --- a/src/cli/loop/optionsSchema.ts +++ b/src/cli/loop/optionsSchema.ts @@ -1,14 +1,6 @@ -import { AIProviderName } from "../../lib/types/providers.js"; +import { AIProviderName } from "../../lib/constants/enums.js"; import type { TextGenerationOptions } from "../../lib/types/generateTypes.js"; - -/** - * Defines the schema for a session variable or a generation option. - */ -export interface OptionSchema { - type: "string" | "boolean" | "number"; - description: string; - allowedValues?: string[]; -} +import type { OptionSchema } from "../../lib/types/cli.js"; /** * Master schema for all text generation options. diff --git a/src/cli/loop/session.ts b/src/cli/loop/session.ts index 394b458ee..7b46cfe6d 100644 --- a/src/cli/loop/session.ts +++ b/src/cli/loop/session.ts @@ -9,7 +9,7 @@ import type { NeurolinkOptions, } from "../../lib/types/conversation.js"; import { textGenerationOptionsSchema } from "./optionsSchema.js"; -import type { OptionSchema } from "./optionsSchema.js"; +import type { OptionSchema } from "../../lib/types/cli.js"; import { handleError } from "../errorHandler.js"; import { ConversationSelector } from "./conversationSelector.js"; import { NeuroLink } from "../../lib/neurolink.js"; diff --git a/src/cli/utils/envManager.ts b/src/cli/utils/envManager.ts index 1972d8374..cbad4d731 100644 --- a/src/cli/utils/envManager.ts +++ b/src/cli/utils/envManager.ts @@ -7,19 +7,7 @@ import fs from "fs"; import chalk from "chalk"; import { logger } from "../../lib/utils/logger.js"; - -export interface EnvBackupResult { - backupPath?: string; - existed: boolean; -} - -export interface EnvUpdateResult { - backup: EnvBackupResult; - updated: string[]; - added: string[]; - unchanged: string[]; - deleted: string[]; -} +import type { EnvBackupResult, EnvUpdateResult } from "../../lib/types/cli.js"; /** * Create a timestamped backup of the existing .env file diff --git a/src/cli/utils/interactiveSetup.ts b/src/cli/utils/interactiveSetup.ts index 7c0358e3d..38c917dc2 100644 --- a/src/cli/utils/interactiveSetup.ts +++ b/src/cli/utils/interactiveSetup.ts @@ -5,7 +5,7 @@ * credential collection, testing, and environment file management. */ -import { AIProviderName } from "../../lib/types/index.js"; +import { AIProviderName } from "../../lib/constants/enums.js"; import { NeuroLink } from "../../lib/neurolink.js"; import chalk from "chalk"; import ora from "ora"; diff --git a/src/lib/constants/enums.ts b/src/lib/constants/enums.ts new file mode 100644 index 000000000..c9445ee5f --- /dev/null +++ b/src/lib/constants/enums.ts @@ -0,0 +1,150 @@ +// ============================================================================ +// ENUMS +// ============================================================================ + +/** + * Supported AI Provider Names + */ +export enum AIProviderName { + BEDROCK = "bedrock", + OPENAI = "openai", + OPENAI_COMPATIBLE = "openai-compatible", + VERTEX = "vertex", + ANTHROPIC = "anthropic", + AZURE = "azure", + GOOGLE_AI = "google-ai", + HUGGINGFACE = "huggingface", + OLLAMA = "ollama", + MISTRAL = "mistral", + LITELLM = "litellm", + SAGEMAKER = "sagemaker", + AUTO = "auto", +} + +/** + * Supported Models for Amazon Bedrock + */ +export enum BedrockModels { + CLAUDE_3_SONNET = "anthropic.claude-3-sonnet-20240229-v1:0", + CLAUDE_3_HAIKU = "anthropic.claude-3-haiku-20240307-v1:0", + CLAUDE_3_5_SONNET = "anthropic.claude-3-5-sonnet-20240620-v1:0", + CLAUDE_3_7_SONNET = "arn:aws:bedrock:us-east-2:225681119357:inference-profile/us.anthropic.claude-3-7-sonnet-20250219-v1:0", +} + +/** + * Supported Models for OpenAI + */ +export enum OpenAIModels { + GPT_4 = "gpt-4", + GPT_4_TURBO = "gpt-4-turbo", + GPT_4O = "gpt-4o", + GPT_4O_MINI = "gpt-4o-mini", + GPT_3_5_TURBO = "gpt-3.5-turbo", + O1_PREVIEW = "o1-preview", + O1_MINI = "o1-mini", +} + +/** + * Supported Models for Google Vertex AI + */ +export enum VertexModels { + // Claude 4 Series (Latest - May 2025) + CLAUDE_4_0_SONNET = "claude-sonnet-4@20250514", + CLAUDE_4_0_OPUS = "claude-opus-4@20250514", + + // Claude 3.5 Series (Still supported) + CLAUDE_3_5_SONNET = "claude-3-5-sonnet-20241022", + CLAUDE_3_5_HAIKU = "claude-3-5-haiku-20241022", + + // Claude 3 Series (Legacy support) + CLAUDE_3_SONNET = "claude-3-sonnet-20240229", + CLAUDE_3_OPUS = "claude-3-opus-20240229", + CLAUDE_3_HAIKU = "claude-3-haiku-20240307", + + // Gemini 2.5 Series (Latest - 2025) + GEMINI_2_5_PRO = "gemini-2.5-pro", + GEMINI_2_5_FLASH = "gemini-2.5-flash", + GEMINI_2_5_FLASH_LITE = "gemini-2.5-flash-lite", + + // Gemini 2.0 Series + GEMINI_2_0_FLASH_001 = "gemini-2.0-flash-001", + + // Gemini 1.5 Series (Legacy support) + GEMINI_1_5_PRO = "gemini-1.5-pro", + GEMINI_1_5_FLASH = "gemini-1.5-flash", +} + +/** + * Supported Models for Google AI Studio + */ +export enum GoogleAIModels { + // Gemini 2.5 Series (Latest - 2025) + GEMINI_2_5_PRO = "gemini-2.5-pro", + GEMINI_2_5_FLASH = "gemini-2.5-flash", + GEMINI_2_5_FLASH_LITE = "gemini-2.5-flash-lite", + + // Gemini 2.0 Series + GEMINI_2_0_FLASH_001 = "gemini-2.0-flash-001", + + // Gemini 1.5 Series (Legacy support) + GEMINI_1_5_PRO = "gemini-1.5-pro", + GEMINI_1_5_FLASH = "gemini-1.5-flash", + GEMINI_1_5_FLASH_LITE = "gemini-1.5-flash-lite", +} + +/** + * Supported Models for Anthropic (Direct API) + */ +export enum AnthropicModels { + // Claude 3.5 Series (Latest) + CLAUDE_3_5_SONNET = "claude-3-5-sonnet-20241022", + CLAUDE_3_5_HAIKU = "claude-3-5-haiku-20241022", + + // Claude 3 Series (Legacy support) + CLAUDE_3_SONNET = "claude-3-sonnet-20240229", + CLAUDE_3_OPUS = "claude-3-opus-20240229", + CLAUDE_3_HAIKU = "claude-3-haiku-20240307", +} + +/** + * API Versions for various providers + */ +export enum APIVersions { + // Azure OpenAI API versions + AZURE_LATEST = "2025-04-01-preview", + AZURE_STABLE = "2024-10-21", + AZURE_LEGACY = "2023-12-01-preview", + + // OpenAI API versions + OPENAI_CURRENT = "v1", + OPENAI_BETA = "v1-beta", + + // Google AI API versions + GOOGLE_AI_CURRENT = "v1", + GOOGLE_AI_BETA = "v1beta", + + // Anthropic API versions + ANTHROPIC_CURRENT = "2023-06-01", + + // Other provider versions can be added here +} + +// Error categories for proper handling +export enum ErrorCategory { + VALIDATION = "validation", + TIMEOUT = "timeout", + NETWORK = "network", + RESOURCE = "resource", + PERMISSION = "permission", + CONFIGURATION = "configuration", + EXECUTION = "execution", + SYSTEM = "system", +} + +// Error severity levels +export enum ErrorSeverity { + LOW = "low", + MEDIUM = "medium", + HIGH = "high", + CRITICAL = "critical", +} diff --git a/src/lib/core/baseProvider.ts b/src/lib/core/baseProvider.ts index 69d935fb5..c7fda57be 100644 --- a/src/lib/core/baseProvider.ts +++ b/src/lib/core/baseProvider.ts @@ -12,10 +12,10 @@ import type { TextGenerationResult, EnhancedGenerateResult, AnalyticsData, - AIProviderName, ExtendedTool, AISDKGenerateResult, } from "../types/index.js"; +import { AIProviderName } from "../constants/enums.js"; import type { EvaluationData } from "../index.js"; import { MiddlewareFactory } from "../middleware/factory.js"; import type { MiddlewareFactoryOptions } from "../types/middlewareTypes.js"; diff --git a/src/lib/core/factory.ts b/src/lib/core/factory.ts index d9eac2186..bcd4955e7 100644 --- a/src/lib/core/factory.ts +++ b/src/lib/core/factory.ts @@ -5,11 +5,8 @@ import { ProviderRegistry } from "../factories/providerRegistry.js"; import { getBestProvider } from "../utils/providerUtils.js"; import { logger } from "../utils/logger.js"; import { dynamicModelProvider } from "./dynamicModels.js"; -import type { - AIProvider, - AIProviderName, - SupportedModelName, -} from "../types/index.js"; +import type { AIProvider, SupportedModelName } from "../types/index.js"; +import { AIProviderName } from "../constants/enums.js"; import type { UnknownRecord } from "../types/common.js"; import type { ProviderPairResult } from "../types/typeAliases.js"; diff --git a/src/lib/factories/providerFactory.ts b/src/lib/factories/providerFactory.ts index 799460b86..26651d466 100644 --- a/src/lib/factories/providerFactory.ts +++ b/src/lib/factories/providerFactory.ts @@ -1,6 +1,7 @@ -import type { AIProvider, AIProviderName } from "../types/index.js"; +import type { AIProvider } from "../types/index.js"; import type { UnknownRecord } from "../types/common.js"; import { logger } from "../utils/logger.js"; +import { AIProviderName } from "../constants/enums.js"; // Pure factory pattern with no hardcoded imports // All providers loaded dynamically via registry to avoid circular dependencies diff --git a/src/lib/factories/providerRegistry.ts b/src/lib/factories/providerRegistry.ts index 350b53243..19c5aedc4 100644 --- a/src/lib/factories/providerRegistry.ts +++ b/src/lib/factories/providerRegistry.ts @@ -2,26 +2,16 @@ import { ProviderFactory } from "./providerFactory.js"; // Lazy loading all providers to avoid circular dependencies // Removed all static imports - providers loaded dynamically when needed // This breaks the circular dependency chain completely -import { - AIProviderName, - GoogleAIModels, - OpenAIModels, -} from "../types/index.js"; +import type { ProviderRegistryOptions } from "../types/index.js"; import { logger } from "../utils/logger.js"; import type { UnknownRecord } from "../types/common.js"; import type { NeuroLink } from "../neurolink.js"; import type { MistralProvider as MistralProviderType } from "@ai-sdk/mistral"; - -/** - * Configuration options for the provider registry - */ -export interface ProviderRegistryOptions { - /** - * Enable loading of manual MCP configurations from .mcp-config.json - * Should only be true for CLI mode, false for SDK mode - */ - enableManualMCP?: boolean; -} +import { + AIProviderName, + GoogleAIModels, + OpenAIModels, +} from "../constants/enums.js"; /** * Provider Registry - registers all providers with the factory diff --git a/src/lib/hitl/hitlManager.ts b/src/lib/hitl/hitlManager.ts index b4eee4a41..64069ca21 100644 --- a/src/lib/hitl/hitlManager.ts +++ b/src/lib/hitl/hitlManager.ts @@ -17,7 +17,7 @@ import type { ConfirmationTimeoutEvent, HITLStatistics, HITLAuditLog, -} from "./types.js"; +} from "../types/hitlTypes.js"; import { HITLTimeoutError, HITLConfigurationError } from "./hitlErrors.js"; import { logger } from "../utils/logger.js"; diff --git a/src/lib/hitl/index.ts b/src/lib/hitl/index.ts index b9522ecd7..fbf32bb42 100644 --- a/src/lib/hitl/index.ts +++ b/src/lib/hitl/index.ts @@ -7,19 +7,6 @@ // Core HITL Manager export { HITLManager } from "./hitlManager.js"; -// Type Definitions -export type { - HITLConfig, - HITLRule, - ConfirmationRequest, - ConfirmationResult, - ConfirmationRequestEvent, - ConfirmationResponseEvent, - ConfirmationTimeoutEvent, - HITLStatistics, - HITLAuditLog, -} from "./types.js"; - // Error Classes export { HITLError, diff --git a/src/lib/index.ts b/src/lib/index.ts index cbaa630fa..1fe0b40fe 100644 --- a/src/lib/index.ts +++ b/src/lib/index.ts @@ -12,7 +12,6 @@ import { AIProviderFactory } from "./core/factory.js"; export { AIProviderFactory }; export type { AIProvider, - AIProviderName, AIModelProviderConfig, StreamingOptions, ProviderAttempt, @@ -33,12 +32,14 @@ export { validateTool } from "./sdk/toolRegistration.js"; export type { ToolResult, ToolDefinition } from "./types/tools.js"; // Model enums +export { DEFAULT_PROVIDER_CONFIGS } from "./types/index.js"; + export { + AIProviderName, BedrockModels, OpenAIModels, VertexModels, - DEFAULT_PROVIDER_CONFIGS, -} from "./types/index.js"; +} from "./constants/enums.js"; // Utility exports export { @@ -54,7 +55,6 @@ export type { DynamicModelConfig, ModelRegistry } from "./types/modelTypes.js"; // Main NeuroLink wrapper class and diagnostic types import { NeuroLink } from "./neurolink.js"; export { NeuroLink }; -export type { ProviderStatus, MCPStatus } from "./neurolink.js"; export type { MCPServerInfo } from "./types/mcpTypes.js"; // Observability configuration types @@ -195,14 +195,15 @@ export { mcpLogger, } from "./mcp/index.js"; +export type { McpMetadata, DiscoveredMcp } from "./types/mcpTypes.js"; + export type { - McpMetadata, ExecutionContext, - DiscoveredMcp, ToolInfo, ToolExecutionResult, - LogLevel, -} from "./mcp/index.js"; +} from "./types/tools.js"; + +export type { LogLevel } from "./utils/logger.js"; // ============================================================================ // REAL-TIME SERVICES & TELEMETRY - Enterprise Platform Features diff --git a/src/lib/mcp/index.ts b/src/lib/mcp/index.ts index 42356fcb9..e2d57062d 100644 --- a/src/lib/mcp/index.ts +++ b/src/lib/mcp/index.ts @@ -3,22 +3,9 @@ * Universal AI Development Platform with Extensible Plugin Architecture * Implementation based on research blueprint */ +import type { McpMetadata } from "../types/mcpTypes.js"; -// Core contracts and types - using camelCase standard -export type { McpMetadata, DiscoveredMcp } from "../types/mcpTypes.js"; - -export type { - ExecutionContext, - ToolInfo, - ToolExecutionResult, -} from "../types/tools.js"; - -// Core functionality exports export { mcpLogger } from "../utils/logger.js"; -export type { LogLevel } from "../utils/logger.js"; - -// Core contracts and types remain -import type { McpMetadata } from "../types/mcpTypes.js"; /** * Initialize the MCP ecosystem - simplified diff --git a/src/lib/memory/mem0Initializer.ts b/src/lib/memory/mem0Initializer.ts index 8d93bf9ad..a6efef73a 100644 --- a/src/lib/memory/mem0Initializer.ts +++ b/src/lib/memory/mem0Initializer.ts @@ -6,25 +6,7 @@ import type { MemoryConfig } from "mem0ai/oss"; import { Memory } from "mem0ai/oss"; import { logger } from "../utils/logger.js"; - -/** - * Interface for mem0 Memory instance methods based on actual mem0ai/oss API - */ -export interface Mem0Memory { - search( - query: string, - config: { userId?: string; limit?: number }, - ): Promise<{ results: Array<{ memory: string; id: string }> }>; - add( - messages: string, - config: { userId?: string; metadata?: Record }, - ): Promise<{ results: Array<{ id: string; memory: string }> }>; - get(memoryId: string): Promise<{ id: string; memory: string } | null>; - update(memoryId: string, data: string): Promise<{ message: string }>; - delete(memoryId: string): Promise<{ message: string }>; - history(memoryId: string): Promise; - reset(): Promise; -} +import type { Mem0Memory } from "../types/utilities.js"; /** * Initialize mem0 memory instance with configuration diff --git a/src/lib/middleware/builtin/guardrails.ts b/src/lib/middleware/builtin/guardrails.ts index 01a6cad34..9c06775f1 100644 --- a/src/lib/middleware/builtin/guardrails.ts +++ b/src/lib/middleware/builtin/guardrails.ts @@ -13,8 +13,6 @@ import { } from "../utils/guardrailsUtils.js"; import { logger } from "../../utils/logger.js"; -export type { GuardrailsMiddlewareConfig } from "../../types/guardrails.js"; - /** * Create Guardrails AI middleware for content filtering and policy enforcement * @param config Configuration for the guardrails middleware diff --git a/src/lib/middleware/utils/guardrailsUtils.ts b/src/lib/middleware/utils/guardrailsUtils.ts index de8e07c31..bbf2f099d 100644 --- a/src/lib/middleware/utils/guardrailsUtils.ts +++ b/src/lib/middleware/utils/guardrailsUtils.ts @@ -1,10 +1,11 @@ import { AIProviderFactory } from "../../core/factory.js"; import { logger } from "../../utils/logger.js"; import type { - PrecallEvaluationResult, - PrecallEvaluationConfig, - EvaluationActionResult, BadWordsConfig, + ContentFilteringResult, + EvaluationActionResult, + PrecallEvaluationConfig, + PrecallEvaluationResult, } from "../../types/guardrails.js"; import type { LanguageModelV1CallOptions } from "ai"; @@ -357,20 +358,6 @@ export function createBlockedStream() { }); } -/** - * Result from content filtering operation - */ -export interface ContentFilteringResult { - filteredText: string; - hasChanges: boolean; - appliedFilters: string[]; - filteringStats: { - regexPatternsApplied: number; - stringFiltersApplied: number; - totalMatches: number; - }; -} - /** * Apply content filtering using bad words configuration * Handles both regex patterns and string lists with proper priority diff --git a/src/lib/models/modelRegistry.ts b/src/lib/models/modelRegistry.ts index 5e151b619..e2b650a73 100644 --- a/src/lib/models/modelRegistry.ts +++ b/src/lib/models/modelRegistry.ts @@ -4,111 +4,15 @@ * Part of Phase 4.1 - Models Command System */ +import { DEFAULT_MODEL_ALIASES } from "../types/providers.js"; import { AIProviderName, OpenAIModels, GoogleAIModels, AnthropicModels, - DEFAULT_MODEL_ALIASES, -} from "../types/providers.js"; +} from "../constants/enums.js"; import type { JsonValue } from "../types/common.js"; - -/** - * Model capabilities interface - */ -export interface ModelCapabilities { - vision: boolean; - functionCalling: boolean; - codeGeneration: boolean; - reasoning: boolean; - multimodal: boolean; - streaming: boolean; - jsonMode: boolean; -} - -/** - * Model pricing information - */ -export interface ModelPricing { - inputCostPer1K: number; // Cost per 1K input tokens in USD - outputCostPer1K: number; // Cost per 1K output tokens in USD - currency: string; // Always USD for now -} - -/** - * Model performance characteristics - */ -export interface ModelPerformance { - speed: "fast" | "medium" | "slow"; // Response speed - quality: "high" | "medium" | "low"; // Output quality - accuracy: "high" | "medium" | "low"; // Factual accuracy -} - -/** - * Model limitations and constraints - */ -export interface ModelLimits { - maxContextTokens: number; - maxOutputTokens: number; - maxRequestsPerMinute?: number; - maxRequestsPerDay?: number; -} - -/** - * Use case suitability scores (1-10 scale) - */ -export interface UseCaseSuitability { - coding: number; - creative: number; - analysis: number; - conversation: number; - reasoning: number; - translation: number; - summarization: number; -} - -/** - * Complete model information - */ -export interface ModelInfo { - id: string; - name: string; - provider: AIProviderName; - description: string; - capabilities: ModelCapabilities; - pricing: ModelPricing; - performance: ModelPerformance; - limits: ModelLimits; - useCases: UseCaseSuitability; - aliases: string[]; - deprecated: boolean; - isLocal: boolean; // Whether the model runs locally (e.g., Ollama) - releaseDate?: string; - category: "general" | "coding" | "creative" | "vision" | "reasoning"; -} - -/** - * Model search filters - */ -export interface ModelSearchFilters { - provider?: AIProviderName | AIProviderName[]; - capability?: keyof ModelCapabilities | (keyof ModelCapabilities)[]; - useCase?: keyof UseCaseSuitability; - maxCost?: number; // Max cost per 1K tokens - minContextSize?: number; - maxContextSize?: number; - performance?: ModelPerformance["speed"] | ModelPerformance["quality"]; - category?: ModelInfo["category"] | ModelInfo["category"][]; -} - -/** - * Model search result with ranking - */ -export interface ModelSearchResult { - model: ModelInfo; - score: number; // Relevance score 0-1 - matchReasons: string[]; -} +import type { ModelInfo } from "../types/modelTypes.js"; /** * Comprehensive model registry diff --git a/src/lib/models/modelResolver.ts b/src/lib/models/modelResolver.ts index 4b2572735..ea4bb1ca9 100644 --- a/src/lib/models/modelResolver.ts +++ b/src/lib/models/modelResolver.ts @@ -4,17 +4,11 @@ * Part of Phase 4.1 - Models Command System */ -import { AIProviderName } from "../types/index.js"; import type { JsonValue } from "../types/common.js"; import { MODEL_REGISTRY, MODEL_ALIASES, USE_CASE_RECOMMENDATIONS, - type ModelInfo, - type ModelSearchFilters, - type ModelSearchResult, - type ModelCapabilities, - type UseCaseSuitability, getAllModels, getModelById, getModelsByProvider, @@ -23,42 +17,15 @@ import { formatModelForDisplay, } from "./modelRegistry.js"; import { isNonNullObject } from "../utils/typeUtils.js"; - -/** - * Model recommendation context - */ -export interface RecommendationContext { - useCase?: keyof UseCaseSuitability; - maxCost?: number; - minQuality?: "low" | "medium" | "high"; - requireCapabilities?: (keyof ModelCapabilities)[]; - excludeProviders?: AIProviderName[]; - contextSize?: number; - preferLocal?: boolean; -} - -/** - * Model recommendation result - */ -export interface ModelRecommendation { - model: ModelInfo; - score: number; - reasoning: string[]; - alternatives: ModelInfo[]; -} - -/** - * Model comparison result - */ -export interface ModelComparison { - models: ModelInfo[]; - comparison: { - capabilities: Record; - pricing: { cheapest: ModelInfo; mostExpensive: ModelInfo }; - performance: Record; - contextSize: { largest: ModelInfo; smallest: ModelInfo }; - }; -} +import type { + ModelCapabilities, + ModelComparison, + ModelInfo, + ModelRecommendation, + ModelSearchFilters, + ModelSearchResult, + RecommendationContext, +} from "../types/modelTypes.js"; /** * Model resolver class with advanced search and recommendation functionality diff --git a/src/lib/neurolink.ts b/src/lib/neurolink.ts index b9710ea21..fbed5fb67 100644 --- a/src/lib/neurolink.ts +++ b/src/lib/neurolink.ts @@ -16,13 +16,16 @@ try { } import type { - AIProviderName, TextGenerationOptions, TextGenerationResult, AnalyticsData, + ProviderStatus, } from "./types/index.js"; import { AIProviderFactory } from "./core/factory.js"; - +import { isNonNullObject } from "./utils/typeUtils.js"; +import { isZodSchema } from "./utils/schemaConversion.js"; +import type { Mem0Memory } from "./types/utilities.js"; +import { AIProviderName } from "./constants/enums.js"; import { mcpLogger } from "./utils/logger.js"; import { SYSTEM_LIMITS } from "./core/constants.js"; import { @@ -52,9 +55,10 @@ import type { } from "./types/streamTypes.js"; import type { TokenUsage, EvaluationData } from "./types/index.js"; import type { - MCPServerInfo, MCPExecutableTool, MCPServerCategory, + MCPServerInfo, + MCPStatus, } from "./types/mcpTypes.js"; import type { ToolInfo } from "./types/tools.js"; import type { NeuroLinkEvents, TypedEventEmitter } from "./types/common.js"; @@ -114,14 +118,16 @@ import { storeConversationTurn, } from "./utils/conversationMemory.js"; import { ExternalServerManager } from "./mcp/externalServerManager.js"; -import type { HITLConfig } from "./hitl/types.js"; +import type { + HITLConfig, + ConfirmationResponseEvent, +} from "./types/hitlTypes.js"; import { HITLManager } from "./hitl/hitlManager.js"; import type { ExternalMCPServerInstance, ExternalMCPOperationResult, ExternalMCPToolInfo, } from "./types/externalMcp.js"; -import type { ConfirmationResponseEvent } from "./hitl/types.js"; // Import direct tools server for automatic registration import { directToolsServer } from "./mcp/servers/agent/directToolsServer.js"; // Import orchestration components @@ -135,50 +141,7 @@ import { getLangfuseHealthStatus, } from "./services/server/ai/observability/instrumentation.js"; import type { ObservabilityConfig } from "./types/observability.js"; - -/** - * Configuration object for NeuroLink constructor. - */ -export interface NeurolinkConstructorConfig { - conversationMemory?: Partial; - enableOrchestration?: boolean; - hitl?: HITLConfig; - toolRegistry?: MCPToolRegistry; - observability?: ObservabilityConfig; -} - -// Provider and MCP diagnostic types -export interface ProviderStatus { - provider: string; - status: "working" | "failed" | "not-configured"; - configured: boolean; - authenticated: boolean; - error?: string; - responseTime?: number; - model?: string; -} - -export interface MCPStatus { - mcpInitialized: boolean; - totalServers: number; - availableServers: number; - autoDiscoveredCount: number; - totalTools: number; - autoDiscoveredServers: MCPServerInfo[]; - customToolsCount: number; - inMemoryServersCount: number; - externalMCPServersCount?: number; - externalMCPConnectedCount?: number; - externalMCPFailedCount?: number; - externalMCPServers?: MCPServerInfo[]; - error?: string; - [key: string]: unknown; // Add index signature for flexible object access -} - -import { isNonNullObject } from "./utils/typeUtils.js"; -import { isZodSchema } from "./utils/schemaConversion.js"; - -// Core types imported from "./types/index.js" +import type { NeurolinkConstructorConfig } from "./types/configTypes.js"; export class NeuroLink { private mcpInitialized = false; @@ -261,9 +224,7 @@ export class NeuroLink { private hitlManager?: HITLManager; // Mem0 memory instance and config for conversation context - private mem0Instance?: - | import("./memory/mem0Initializer.js").Mem0Memory - | null; + private mem0Instance?: Mem0Memory | null; private mem0Config?: MemoryConfig; /** @@ -282,9 +243,7 @@ export class NeuroLink { /** * Async initialization called during generate/stream */ - private async ensureMem0Ready(): Promise< - import("./memory/mem0Initializer.js").Mem0Memory | null - > { + private async ensureMem0Ready(): Promise { if (this.mem0Instance !== undefined) { return this.mem0Instance; } diff --git a/src/lib/providers/amazonBedrock.ts b/src/lib/providers/amazonBedrock.ts index 132825024..4045b44f5 100644 --- a/src/lib/providers/amazonBedrock.ts +++ b/src/lib/providers/amazonBedrock.ts @@ -20,10 +20,10 @@ import { } from "@aws-sdk/client-bedrock"; import { BaseProvider } from "../core/baseProvider.js"; import type { - AIProviderName, EnhancedGenerateResult, TextGenerationOptions, } from "../types/index.js"; +import { AIProviderName } from "../constants/enums.js"; import type { StreamOptions, StreamResult } from "../types/streamTypes.js"; import type { ToolDefinition, ToolArgs } from "../types/tools.js"; import type { JsonValue } from "../types/common.js"; diff --git a/src/lib/providers/amazonSagemaker.ts b/src/lib/providers/amazonSagemaker.ts index bd507e08d..8d8e0e870 100644 --- a/src/lib/providers/amazonSagemaker.ts +++ b/src/lib/providers/amazonSagemaker.ts @@ -7,7 +7,7 @@ import type { ZodType, ZodTypeDef } from "zod"; import type { Schema, LanguageModelV1 } from "ai"; -import type { AIProviderName } from "../types/index.js"; +import { AIProviderName } from "../constants/enums.js"; import type { StreamOptions, StreamResult } from "../types/streamTypes.js"; import type { ConnectivityResult } from "../types/typeAliases.js"; import { BaseProvider } from "../core/baseProvider.js"; diff --git a/src/lib/providers/anthropic.ts b/src/lib/providers/anthropic.ts index 2dbf55ec6..dc92cf846 100644 --- a/src/lib/providers/anthropic.ts +++ b/src/lib/providers/anthropic.ts @@ -1,8 +1,7 @@ import { createAnthropic } from "@ai-sdk/anthropic"; import { streamText, type LanguageModelV1 } from "ai"; import type { ValidationSchema } from "../types/typeAliases.js"; -import type { AIProviderName } from "../types/index.js"; -import { AnthropicModels } from "../types/index.js"; +import { AIProviderName, AnthropicModels } from "../constants/enums.js"; import type { StreamOptions, StreamResult } from "../types/streamTypes.js"; import type { UnknownRecord, JsonValue } from "../types/common.js"; import type { NeuroLink } from "../neurolink.js"; diff --git a/src/lib/providers/anthropicBaseProvider.ts b/src/lib/providers/anthropicBaseProvider.ts index 21e8c0ef0..75e411f84 100644 --- a/src/lib/providers/anthropicBaseProvider.ts +++ b/src/lib/providers/anthropicBaseProvider.ts @@ -1,8 +1,7 @@ import { createAnthropic } from "@ai-sdk/anthropic"; import type { ZodType, ZodTypeDef } from "zod"; import { streamText, type Schema, type LanguageModelV1 } from "ai"; -import type { AIProviderName } from "../types/index.js"; -import { AnthropicModels } from "../types/index.js"; +import { AIProviderName, AnthropicModels } from "../constants/enums.js"; import type { StreamOptions, StreamResult } from "../types/streamTypes.js"; import { BaseProvider } from "../core/baseProvider.js"; import { logger } from "../utils/logger.js"; diff --git a/src/lib/providers/azureOpenai.ts b/src/lib/providers/azureOpenai.ts index 7ac0bb7a0..1dca1427f 100644 --- a/src/lib/providers/azureOpenai.ts +++ b/src/lib/providers/azureOpenai.ts @@ -1,8 +1,7 @@ import { createAzure } from "@ai-sdk/azure"; import { streamText, type LanguageModelV1 } from "ai"; import { BaseProvider } from "../core/baseProvider.js"; -import { APIVersions } from "../types/providers.js"; -import type { AIProviderName } from "../types/providers.js"; +import { AIProviderName, APIVersions } from "../constants/enums.js"; import type { StreamOptions, StreamResult } from "../types/streamTypes.js"; import type { UnknownRecord } from "../types/common.js"; import type { NeuroLink } from "../neurolink.js"; diff --git a/src/lib/providers/googleAiStudio.ts b/src/lib/providers/googleAiStudio.ts index 3ed02d010..a45caec83 100644 --- a/src/lib/providers/googleAiStudio.ts +++ b/src/lib/providers/googleAiStudio.ts @@ -1,8 +1,7 @@ import { createGoogleGenerativeAI } from "@ai-sdk/google"; import { streamText, type Schema, type LanguageModelV1 } from "ai"; import type { ZodUnknownSchema } from "../types/typeAliases.js"; -import type { AIProviderName } from "../types/index.js"; -import { GoogleAIModels } from "../types/index.js"; +import { AIProviderName, GoogleAIModels } from "../constants/enums.js"; import type { StreamOptions, StreamResult, diff --git a/src/lib/providers/googleVertex.ts b/src/lib/providers/googleVertex.ts index 90cac43b8..0c6672412 100644 --- a/src/lib/providers/googleVertex.ts +++ b/src/lib/providers/googleVertex.ts @@ -14,7 +14,7 @@ import { type LanguageModelV1, type LanguageModel, } from "ai"; -import type { AIProviderName } from "../types/index.js"; +import { AIProviderName } from "../constants/enums.js"; import type { StreamOptions, StreamResult } from "../types/streamTypes.js"; import type { UnknownRecord } from "../types/common.js"; import type { NeuroLink } from "../neurolink.js"; diff --git a/src/lib/providers/huggingFace.ts b/src/lib/providers/huggingFace.ts index d3555d1fc..2184fe37b 100644 --- a/src/lib/providers/huggingFace.ts +++ b/src/lib/providers/huggingFace.ts @@ -7,7 +7,7 @@ import { type ToolSet, type ToolChoice, } from "ai"; -import type { AIProviderName } from "../types/index.js"; +import { AIProviderName } from "../constants/enums.js"; import type { StreamOptions, StreamResult } from "../types/streamTypes.js"; import { BaseProvider } from "../core/baseProvider.js"; import { logger } from "../utils/logger.js"; diff --git a/src/lib/providers/index.ts b/src/lib/providers/index.ts index 01f39a74f..284bc770e 100644 --- a/src/lib/providers/index.ts +++ b/src/lib/providers/index.ts @@ -15,6 +15,3 @@ export { HuggingFaceProvider as HuggingFace } from "./huggingFace.js"; export { OllamaProvider as Ollama } from "./ollama.js"; export { MistralProvider as MistralAI } from "./mistral.js"; export { LiteLLMProvider as LiteLLM } from "./litellm.js"; - -// Re-export the AIProvider type for convenience -export type { AIProvider } from "../types/index.js"; diff --git a/src/lib/providers/litellm.ts b/src/lib/providers/litellm.ts index 0612c308f..ed0978f62 100644 --- a/src/lib/providers/litellm.ts +++ b/src/lib/providers/litellm.ts @@ -1,7 +1,7 @@ import { createOpenAI } from "@ai-sdk/openai"; import type { ZodType, ZodTypeDef } from "zod"; import { streamText, type Schema, type LanguageModelV1 } from "ai"; -import type { AIProviderName } from "../types/index.js"; +import { AIProviderName } from "../constants/enums.js"; import type { StreamOptions, StreamResult } from "../types/streamTypes.js"; import type { UnknownRecord } from "../types/common.js"; import type { NeuroLink } from "../neurolink.js"; diff --git a/src/lib/providers/mistral.ts b/src/lib/providers/mistral.ts index b74721af8..5f8484419 100644 --- a/src/lib/providers/mistral.ts +++ b/src/lib/providers/mistral.ts @@ -1,7 +1,7 @@ import { createMistral } from "@ai-sdk/mistral"; import { streamText, type LanguageModelV1 } from "ai"; import type { ValidationSchema } from "../types/typeAliases.js"; -import type { AIProviderName } from "../types/index.js"; +import { AIProviderName } from "../constants/enums.js"; import type { StreamOptions, StreamResult } from "../types/streamTypes.js"; import type { UnknownRecord } from "../types/common.js"; import type { NeuroLink } from "../neurolink.js"; diff --git a/src/lib/providers/ollama.ts b/src/lib/providers/ollama.ts index 9b3c83788..f783fbd94 100644 --- a/src/lib/providers/ollama.ts +++ b/src/lib/providers/ollama.ts @@ -1,4 +1,4 @@ -import type { AIProviderName } from "../types/index.js"; +import { AIProviderName } from "../constants/enums.js"; import type { LanguageModelV1, LanguageModelV1CallOptions, diff --git a/src/lib/providers/openAI.ts b/src/lib/providers/openAI.ts index e4c03268f..b5a4d6de5 100644 --- a/src/lib/providers/openAI.ts +++ b/src/lib/providers/openAI.ts @@ -1,7 +1,7 @@ import { createOpenAI } from "@ai-sdk/openai"; import { streamText, type LanguageModelV1, type Tool } from "ai"; import type { ValidationSchema } from "../types/typeAliases.js"; -import { AIProviderName } from "../types/index.js"; +import { AIProviderName } from "../constants/enums.js"; import type { StreamOptions, StreamResult } from "../types/streamTypes.js"; import { BaseProvider } from "../core/baseProvider.js"; import { logger } from "../utils/logger.js"; diff --git a/src/lib/providers/openaiCompatible.ts b/src/lib/providers/openaiCompatible.ts index 5e0aed1f3..ea598ddf6 100644 --- a/src/lib/providers/openaiCompatible.ts +++ b/src/lib/providers/openaiCompatible.ts @@ -1,7 +1,7 @@ import { createOpenAI } from "@ai-sdk/openai"; import { streamText, type Schema, type LanguageModelV1 } from "ai"; import type { ZodUnknownSchema } from "../types/typeAliases.js"; -import type { AIProviderName } from "../types/index.js"; +import { AIProviderName } from "../constants/enums.js"; import type { StreamOptions, StreamResult } from "../types/streamTypes.js"; import type { UnknownRecord } from "../types/common.js"; import type { ModelsResponse } from "../types/providers.js"; diff --git a/src/lib/proxy/proxyFetch.ts b/src/lib/proxy/proxyFetch.ts index b661ba31c..b33d6715b 100644 --- a/src/lib/proxy/proxyFetch.ts +++ b/src/lib/proxy/proxyFetch.ts @@ -7,6 +7,7 @@ import { logger } from "../utils/logger.js"; import type { ProxyAgent } from "undici"; import { shouldBypassProxy } from "./utils/noProxyUtils.js"; +import type { ParsedProxyConfig } from "../types/utilities.js"; /** * Mask credentials in proxy URLs for secure logging @@ -50,19 +51,7 @@ function maskProxyEnvVars( // ==================== LIGHTWEIGHT PROXY IMPLEMENTATIONS ==================== -/** - * Parsed proxy configuration - */ -interface ParsedProxyConfig { - protocol: string; - hostname: string; - port: number; - auth?: { - username: string; - password: string; - }; - cleanUrl: string; -} +// ParsedProxyConfig interface moved to ../types/utilities.js /** * Parse proxy URL with authentication support diff --git a/src/lib/types/analytics.ts b/src/lib/types/analytics.ts index dbf453718..d0bba3bd8 100644 --- a/src/lib/types/analytics.ts +++ b/src/lib/types/analytics.ts @@ -56,3 +56,17 @@ export type StreamAnalyticsData = { /** Provider analytics */ providerAnalytics?: AnalyticsData; }; + +export type PerformanceMetrics = { + startTime: number; + endTime?: number; + duration?: number; + memoryStart: NodeJS.MemoryUsage; + memoryEnd?: NodeJS.MemoryUsage; + memoryDelta?: { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + }; +}; diff --git a/src/lib/types/cli.ts b/src/lib/types/cli.ts index dcf3cb707..789c1fe58 100644 --- a/src/lib/types/cli.ts +++ b/src/lib/types/cli.ts @@ -7,6 +7,28 @@ import type { AnalyticsData, TokenUsage } from "./analytics.js"; import type { EvaluationData } from "../index.js"; import type { ToolCall, ToolResult } from "./tools.js"; +/** + * Ollama command utilities type + */ +export type AllowedCommand = + | "ollama" + | "curl" + | "systemctl" + | "pkill" + | "killall" + | "open" + | "taskkill" + | "start"; + +/** + * Defines the schema for a session variable or a generation option. + */ +export type OptionSchema = { + type: "string" | "boolean" | "number"; + description: string; + allowedValues?: string[]; +}; + /** * Base command arguments type */ @@ -505,3 +527,281 @@ export function isCommandResult(value: unknown): value is CommandResult { typeof (value as CommandResult).success === "boolean" ); } + +// ============================================================================ +// CLI Setup and Utility Types (moved from CLI modules) +// ============================================================================ + +/** + * Environment file backup result + */ +export type EnvBackupResult = { + backupPath?: string; + existed: boolean; +}; + +/** + * Environment file update result + */ +export type EnvUpdateResult = { + backup: EnvBackupResult; + updated: string[]; + added: string[]; + unchanged: string[]; + deleted: string[]; +}; + +/** + * Provider configuration for interactive setup + */ +export type CLIProviderConfig = { + id: string; + name: string; + description: string; + envVars: Array<{ + key: string; + prompt: string; + secure?: boolean; + default?: string; + optional?: boolean; + }>; +}; + +/** + * Interactive setup result + */ +export type CLISetupResult = { + selectedProviders: string[]; + credentials: Record; + envFileBackup?: string; + testResults: Array<{ + provider: string; + status: "working" | "failed"; + error?: string; + responseTime?: number; + }>; +}; + +/** + * Main setup command arguments + */ +export type SetupArgs = { + provider?: string; + list?: boolean; + status?: boolean; + interactive?: boolean; + help?: boolean; +}; + +/** + * Provider information for setup display + */ +export type ProviderInfo = { + id: string; + name: string; + emoji: string; + description: string; + setupTime: string; + cost: string; + difficulty?: "Easy" | "Medium" | "Hard"; + features?: string[]; + bestFor?: string; + models?: string; + strengths?: string; + pricing?: string; + setupCommand?: string; + handler?: (argv: { + check?: boolean; + nonInteractive?: boolean; + }) => Promise; +}; + +/** + * Setup command factory arguments + */ +export type SetupCommandArgs = BaseCommandArgs & { + provider?: string; + check?: boolean; + list?: boolean; + status?: boolean; + interactive?: boolean; + nonInteractive?: boolean; +}; + +/** + * MCP server configuration for CLI + */ +export type CLIMCPServerConfig = { + name: string; + transport: "stdio" | "websocket" | "tcp" | "unix"; + command?: string; + args?: string[]; + env?: Record; + url?: string; + description?: string; +}; + +// ============================================================================ +// Provider-Specific Setup Types +// ============================================================================ + +/** + * OpenAI setup configuration types + */ +export namespace OpenAISetup { + export interface SetupOptions { + checkOnly?: boolean; + interactive?: boolean; + } + + export interface SetupArgv { + check?: boolean; + nonInteractive?: boolean; + } + + export interface Config { + apiKey?: string; + organization?: string; + model?: string; + isReconfiguring?: boolean; + } +} + +/** + * Anthropic setup configuration types + */ +export namespace AnthropicSetup { + export interface SetupOptions { + checkOnly?: boolean; + interactive?: boolean; + } + + export interface SetupArgv { + check?: boolean; + nonInteractive?: boolean; + } + + export interface Config { + apiKey?: string; + model?: string; + isReconfiguring?: boolean; + } +} + +/** + * Google AI setup configuration types + */ +export namespace GoogleAISetup { + export interface SetupOptions { + checkOnly?: boolean; + interactive?: boolean; + } + + export interface SetupArgv { + check?: boolean; + nonInteractive?: boolean; + } + + export interface Config { + apiKey?: string; + model?: string; + isReconfiguring?: boolean; + } +} + +/** + * Azure setup configuration types + */ +export namespace AzureSetup { + export interface SetupOptions { + checkOnly?: boolean; + interactive?: boolean; + } + + export interface SetupArgv { + check?: boolean; + nonInteractive?: boolean; + } + + export interface Config { + apiKey?: string; + endpoint?: string; + deploymentName?: string; + apiVersion?: string; + model?: string; + isReconfiguring?: boolean; + } +} + +/** + * AWS Bedrock setup configuration types + */ +export namespace BedrockSetup { + export interface SetupOptions { + checkOnly?: boolean; + interactive?: boolean; + } + + export interface SetupArgv { + check?: boolean; + nonInteractive?: boolean; + } + + export interface ConfigData { + region?: string; + accessKeyId?: string; + secretAccessKey?: string; + model?: string; + } + + export interface ConfigStatus { + hasCredentials: boolean; + hasRegion: boolean; + hasModel: boolean; + isReconfiguring?: boolean; + } +} + +/** + * GCP/Vertex AI setup configuration types + */ +export namespace GCPSetup { + export interface SetupOptions { + checkOnly?: boolean; + interactive?: boolean; + } + + export interface SetupArgv { + check?: boolean; + nonInteractive?: boolean; + } + + export interface AuthMethodStatus { + hasServiceAccount: boolean; + hasGcloudAuth: boolean; + hasApplicationDefault: boolean; + preferredMethod?: "service-account" | "gcloud" | "adc"; + } +} + +/** + * Hugging Face setup configuration types + */ +export namespace HuggingFaceSetup { + export interface SetupArgs { + check?: boolean; + nonInteractive?: boolean; + help?: boolean; + } +} + +/** + * Mistral setup configuration types + */ +export namespace MistralSetup { + export interface SetupArgs { + check?: boolean; + nonInteractive?: boolean; + help?: boolean; + } +} diff --git a/src/lib/types/configTypes.ts b/src/lib/types/configTypes.ts index 1ebc4df77..44dd9a3bd 100644 --- a/src/lib/types/configTypes.ts +++ b/src/lib/types/configTypes.ts @@ -3,6 +3,11 @@ * Centralized configuration type definitions following the established architecture pattern */ +import { MCPToolRegistry } from "../mcp/toolRegistry.js"; +import type { HITLConfig } from "../types/hitlTypes.js"; +import type { ConversationMemoryConfig } from "./conversation.js"; +import type { ObservabilityConfig } from "./observability.js"; + /** * Main NeuroLink configuration type */ @@ -16,6 +21,17 @@ export type NeuroLinkConfig = { [key: string]: unknown; // Extensibility for existing config }; +/** + * Configuration object for NeuroLink constructor. + */ +export type NeurolinkConstructorConfig = { + conversationMemory?: Partial; + enableOrchestration?: boolean; + hitl?: HITLConfig; + toolRegistry?: MCPToolRegistry; + observability?: ObservabilityConfig; +}; + /** * Provider-specific configuration */ diff --git a/src/lib/types/fileTypes.ts b/src/lib/types/fileTypes.ts index 24f4b6680..47f9b64d0 100644 --- a/src/lib/types/fileTypes.ts +++ b/src/lib/types/fileTypes.ts @@ -74,13 +74,13 @@ export type PDFAPIType = "document" | "files-api" | "unsupported"; /** * PDF provider configuration */ -export interface PDFProviderConfig { +export type PDFProviderConfig = { maxSizeMB: number; maxPages: number; supportsNative: boolean; requiresCitations: boolean | "auto"; apiType: PDFAPIType; -} +}; /** * PDF processor options @@ -107,7 +107,7 @@ export type FileDetectorOptions = { /** * Google AI Studio Files API types */ -export interface GoogleFilesAPIUploadResult { +export type GoogleFilesAPIUploadResult = { file: { name: string; displayName: string; @@ -119,4 +119,4 @@ export interface GoogleFilesAPIUploadResult { sha256Hash: string; uri: string; }; -} +}; diff --git a/src/lib/types/generateTypes.ts b/src/lib/types/generateTypes.ts index 62dc59a64..46561602c 100644 --- a/src/lib/types/generateTypes.ts +++ b/src/lib/types/generateTypes.ts @@ -4,7 +4,7 @@ import type { StandardRecord, ZodUnknownSchema, } from "./typeAliases.js"; -import type { AIProviderName } from "./providers.js"; +import { AIProviderName } from "../constants/enums.js"; import type { AnalyticsData, TokenUsage } from "./analytics.js"; import type { EvaluationData } from "./evaluation.js"; import type { ChatMessage, ConversationMemoryConfig } from "./conversation.js"; diff --git a/src/lib/types/guardrails.ts b/src/lib/types/guardrails.ts index e14609e57..767e9b559 100644 --- a/src/lib/types/guardrails.ts +++ b/src/lib/types/guardrails.ts @@ -126,3 +126,17 @@ export type EvaluationIssue = { severity: IssueSeverity; description: string; }; + +/** + * Result from content filtering operation + */ +export type ContentFilteringResult = { + filteredText: string; + hasChanges: boolean; + appliedFilters: string[]; + filteringStats: { + regexPatternsApplied: number; + stringFiltersApplied: number; + totalMatches: number; + }; +}; diff --git a/src/lib/hitl/types.ts b/src/lib/types/hitlTypes.ts similarity index 94% rename from src/lib/hitl/types.ts rename to src/lib/types/hitlTypes.ts index 51107038a..39c196d6c 100644 --- a/src/lib/hitl/types.ts +++ b/src/lib/types/hitlTypes.ts @@ -10,7 +10,7 @@ * Core HITL configuration interface * Controls how the HITL system behaves and what tools require confirmation */ -export interface HITLConfig { +export type HITLConfig = { /** Master enable/disable switch for HITL functionality */ enabled: boolean; @@ -34,13 +34,13 @@ export interface HITLConfig { /** Advanced custom rules for complex tool scenarios (default: []) */ customRules?: HITLRule[]; -} +}; /** * Custom rule for advanced HITL scenarios * Allows enterprises to define complex conditions for when tools require confirmation */ -export interface HITLRule { +export type HITLRule = { /** Human-readable name for the rule */ name: string; @@ -52,13 +52,13 @@ export interface HITLRule { /** Custom message to show users when this rule is triggered */ customMessage?: string; -} +}; /** * Internal confirmation request tracking * Used by HITLManager to track pending confirmations */ -export interface ConfirmationRequest { +export type ConfirmationRequest = { /** Unique identifier for this confirmation request */ confirmationId: string; @@ -79,13 +79,13 @@ export interface ConfirmationRequest { /** Promise reject function */ reject: (error: Error) => void; -} +}; /** * Result of a confirmation request * Contains user decision and potentially modified arguments */ -export interface ConfirmationResult { +export type ConfirmationResult = { /** Whether the user approved the tool execution */ approved: boolean; @@ -97,13 +97,13 @@ export interface ConfirmationResult { /** Time taken for user to respond in milliseconds */ responseTime: number; -} +}; /** * Event payload for confirmation requests * Sent to frontends via EventEmitter when tool needs approval */ -export interface ConfirmationRequestEvent { +export type ConfirmationRequestEvent = { type: "hitl:confirmation-request"; payload: { /** Unique ID for tracking this request */ @@ -142,13 +142,13 @@ export interface ConfirmationRequestEvent { /** Whether user can modify arguments */ allowModification: boolean; }; -} +}; /** * Event payload for confirmation responses * Sent from frontends back to HITLManager with user decision */ -export interface ConfirmationResponseEvent { +export type ConfirmationResponseEvent = { type: "hitl:confirmation-response"; payload: { /** Matching confirmation ID from the request */ @@ -175,13 +175,13 @@ export interface ConfirmationResponseEvent { userId?: string; }; }; -} +}; /** * Event payload for confirmation timeouts * Emitted when user doesn't respond within timeout period */ -export interface ConfirmationTimeoutEvent { +export type ConfirmationTimeoutEvent = { type: "hitl:timeout"; payload: { /** Confirmation ID that timed out */ @@ -193,13 +193,13 @@ export interface ConfirmationTimeoutEvent { /** Timeout duration in milliseconds */ timeout: number; }; -} +}; /** * HITL audit log entry * Used for compliance and debugging purposes */ -export interface HITLAuditLog { +export type HITLAuditLog = { /** ISO timestamp of the event */ timestamp: string; @@ -234,13 +234,13 @@ export interface HITLAuditLog { /** Response time in milliseconds (if applicable) */ responseTime?: number; -} +}; /** * HITL statistics interface * Provides metrics about HITL usage for monitoring */ -export interface HITLStatistics { +export type HITLStatistics = { /** Total number of confirmation requests made */ totalRequests: number; @@ -258,4 +258,4 @@ export interface HITLStatistics { /** Number of timed out requests */ timedOutRequests: number; -} +}; diff --git a/src/lib/types/index.ts b/src/lib/types/index.ts index 507da41e4..bd2a041d4 100644 --- a/src/lib/types/index.ts +++ b/src/lib/types/index.ts @@ -105,7 +105,6 @@ export type { MCPServerConfig, DiscoveredMcp, McpMetadata, - ProviderStatus, ToolDiscoveryResult, ExternalToolExecutionOptions, ToolValidationResult, @@ -191,6 +190,12 @@ export * from "./evaluationProviders.js"; // SDK Types - Core types for external developers export * from "./sdkTypes.js"; +// Utilities Types - Utility module types (selective export to avoid conflicts) +export * from "./utilities.js"; + +// Middleware Types - Middleware system types +export * from "./middlewareTypes.js"; + // File detection and processing types export * from "./fileTypes.js"; diff --git a/src/lib/types/mcpTypes.ts b/src/lib/types/mcpTypes.ts index 4cdd71301..594d2da2a 100644 --- a/src/lib/types/mcpTypes.ts +++ b/src/lib/types/mcpTypes.ts @@ -229,6 +229,23 @@ export type MCPToolMetadata = { */ export type MCPServerRegistryEntry = [string, MCPServerInfo]; +export type MCPStatus = { + mcpInitialized: boolean; + totalServers: number; + availableServers: number; + autoDiscoveredCount: number; + totalTools: number; + autoDiscoveredServers: MCPServerInfo[]; + customToolsCount: number; + inMemoryServersCount: number; + externalMCPServersCount?: number; + externalMCPConnectedCount?: number; + externalMCPFailedCount?: number; + externalMCPServers?: MCPServerInfo[]; + error?: string; + [key: string]: unknown; // Allows runtime-added status fields from plugins/extensions +}; + /** * Call record for circuit breaker statistics tracking * Extracted from mcpCircuitBreaker.ts for centralized type management @@ -472,19 +489,6 @@ export type McpMetadata = { category?: string; // Server category (e.g., "ai-tools", "database", "api") }; -/** - * Provider status information - * Moved from src/lib/mcp/contracts/mcpContract.ts - */ -export type ProviderStatus = { - available: boolean; - lastCheck: number; - reason?: string; - model?: string; - cost?: number; - latencyMs?: number; -}; - /** * Tool discovery result * Moved from src/lib/mcp/toolDiscoveryService.ts diff --git a/src/lib/types/modelTypes.ts b/src/lib/types/modelTypes.ts index e31bb968e..ca3c2ed11 100644 --- a/src/lib/types/modelTypes.ts +++ b/src/lib/types/modelTypes.ts @@ -5,6 +5,7 @@ import { z } from "zod"; import type { JsonValue } from "./common.js"; +import { AIProviderName } from "../constants/enums.js"; /** * Model performance tier definition @@ -109,47 +110,134 @@ export type DynamicModelConfig = z.infer; export type ModelRegistry = z.infer; /** - * Model name constants structure + * Model capabilities interface */ -export type ModelNameConstants = { - readonly [provider: string]: { - readonly FAST: string; - readonly BALANCED: string; - readonly QUALITY: string; - }; +export type ModelCapabilities = { + vision: boolean; + functionCalling: boolean; + codeGeneration: boolean; + reasoning: boolean; + multimodal: boolean; + streaming: boolean; + jsonMode: boolean; +}; + +/** + * Model pricing information + */ +export type ModelPricingInfo = { + inputCostPer1K: number; // Cost per 1K input tokens in USD + outputCostPer1K: number; // Cost per 1K output tokens in USD + currency: string; // Always USD for now }; /** - * Model metadata for registry + * Model performance characteristics */ -export type ModelMetadata = { - version: string; - lastUpdated: string; - modelCount: number; +export type ModelPerformance = { + speed: "fast" | "medium" | "slow"; // Response speed + quality: "high" | "medium" | "low"; // Output quality + accuracy: "high" | "medium" | "low"; // Factual accuracy }; /** - * Model search options + * Model limitations and constraints */ -export type ModelSearchOptions = { - provider?: string; - maxPrice?: number; - excludeDeprecated?: boolean; +export type ModelLimits = { + maxContextTokens: number; + maxOutputTokens: number; + maxRequestsPerMinute?: number; + maxRequestsPerDay?: number; +}; + +/** + * Use case suitability scores (1-10 scale) + */ +export type UseCaseSuitability = { + coding: number; + creative: number; + analysis: number; + conversation: number; + reasoning: number; + translation: number; + summarization: number; +}; + +/** + * Complete model information + */ +export type ModelInfo = { + id: string; + name: string; + provider: AIProviderName; + description: string; + capabilities: ModelCapabilities; + pricing: ModelPricingInfo; + performance: ModelPerformance; + limits: ModelLimits; + useCases: UseCaseSuitability; + aliases: string[]; + deprecated: boolean; + isLocal: boolean; // Whether the model runs locally (e.g., Ollama) + releaseDate?: string; + category: "general" | "coding" | "creative" | "vision" | "reasoning"; }; /** - * Model search result + * Model search filters + */ +export type ModelSearchFilters = { + provider?: AIProviderName | AIProviderName[]; + capability?: keyof ModelCapabilities | (keyof ModelCapabilities)[]; + useCase?: keyof UseCaseSuitability; + maxCost?: number; // Max cost per 1K tokens + minContextSize?: number; + maxContextSize?: number; + performance?: ModelPerformance["speed"] | ModelPerformance["quality"]; + category?: ModelInfo["category"] | ModelInfo["category"][]; +}; + +/** + * Model search result with ranking */ export type ModelSearchResult = { - provider: string; - model: string; - config: DynamicModelConfig; + model: ModelInfo; + score: number; // Relevance score 0-1 + matchReasons: string[]; +}; + +/** + * Model recommendation context + */ +export type RecommendationContext = { + useCase?: keyof UseCaseSuitability; + maxCost?: number; + minQuality?: "low" | "medium" | "high"; + requireCapabilities?: (keyof ModelCapabilities)[]; + excludeProviders?: AIProviderName[]; + contextSize?: number; + preferLocal?: boolean; }; /** - * Cost information structure + * Model recommendation result */ -export type CostInfo = { - input: number; - output: number; +export type ModelRecommendation = { + model: ModelInfo; + score: number; + reasoning: string[]; + alternatives: ModelInfo[]; +}; + +/** + * Model comparison result + */ +export type ModelComparison = { + models: ModelInfo[]; + comparison: { + capabilities: Record; + pricing: { cheapest: ModelInfo; mostExpensive: ModelInfo }; + performance: Record; + contextSize: { largest: ModelInfo; smallest: ModelInfo }; + }; }; diff --git a/src/lib/types/observability.ts b/src/lib/types/observability.ts index f2319e3e2..c419ed08d 100644 --- a/src/lib/types/observability.ts +++ b/src/lib/types/observability.ts @@ -7,7 +7,7 @@ /** * Langfuse observability configuration */ -export interface LangfuseConfig { +export type LangfuseConfig = { /** Whether Langfuse is enabled */ enabled: boolean; /** Langfuse public key */ @@ -25,12 +25,12 @@ export interface LangfuseConfig { environment?: string; /** Release/version identifier */ release?: string; -} +}; /** * OpenTelemetry configuration */ -export interface OpenTelemetryConfig { +export type OpenTelemetryConfig = { /** Whether OpenTelemetry is enabled */ enabled: boolean; /** OTLP endpoint URL */ @@ -39,14 +39,14 @@ export interface OpenTelemetryConfig { serviceName?: string; /** Service version */ serviceVersion?: string; -} +}; /** * Complete observability configuration for Neurolink SDK */ -export interface ObservabilityConfig { +export type ObservabilityConfig = { /** Langfuse configuration */ langfuse?: LangfuseConfig; /** OpenTelemetry configuration */ openTelemetry?: OpenTelemetryConfig; -} +}; diff --git a/src/lib/types/providers.ts b/src/lib/types/providers.ts index 50e4b4612..7cbd46d33 100644 --- a/src/lib/types/providers.ts +++ b/src/lib/types/providers.ts @@ -3,6 +3,14 @@ */ import type { UnknownRecord, JsonValue } from "./common.js"; +import { + AIProviderName, + AnthropicModels, + BedrockModels, + GoogleAIModels, + OpenAIModels, + VertexModels, +} from "../constants/enums.js"; import type { Tool } from "ai"; import type { ValidationSchema } from "./typeAliases.js"; import type { @@ -13,137 +21,6 @@ import type { import type { StreamOptions, StreamResult } from "./streamTypes.js"; import type { ExternalMCPToolInfo } from "./externalMcp.js"; -// ============================================================================ -// ENUMS -// ============================================================================ - -/** - * Supported AI Provider Names - */ -export enum AIProviderName { - BEDROCK = "bedrock", - OPENAI = "openai", - OPENAI_COMPATIBLE = "openai-compatible", - VERTEX = "vertex", - ANTHROPIC = "anthropic", - AZURE = "azure", - GOOGLE_AI = "google-ai", - HUGGINGFACE = "huggingface", - OLLAMA = "ollama", - MISTRAL = "mistral", - LITELLM = "litellm", - SAGEMAKER = "sagemaker", - AUTO = "auto", -} - -/** - * Supported Models for Amazon Bedrock - */ -export enum BedrockModels { - CLAUDE_3_SONNET = "anthropic.claude-3-sonnet-20240229-v1:0", - CLAUDE_3_HAIKU = "anthropic.claude-3-haiku-20240307-v1:0", - CLAUDE_3_5_SONNET = "anthropic.claude-3-5-sonnet-20240620-v1:0", - CLAUDE_3_7_SONNET = "arn:aws:bedrock:us-east-2:225681119357:inference-profile/us.anthropic.claude-3-7-sonnet-20250219-v1:0", -} - -/** - * Supported Models for OpenAI - */ -export enum OpenAIModels { - GPT_4 = "gpt-4", - GPT_4_TURBO = "gpt-4-turbo", - GPT_4O = "gpt-4o", - GPT_4O_MINI = "gpt-4o-mini", - GPT_3_5_TURBO = "gpt-3.5-turbo", - O1_PREVIEW = "o1-preview", - O1_MINI = "o1-mini", -} - -/** - * Supported Models for Google Vertex AI - */ -export enum VertexModels { - // Claude 4 Series (Latest - May 2025) - CLAUDE_4_0_SONNET = "claude-sonnet-4@20250514", - CLAUDE_4_0_OPUS = "claude-opus-4@20250514", - - // Claude 3.5 Series (Still supported) - CLAUDE_3_5_SONNET = "claude-3-5-sonnet-20241022", - CLAUDE_3_5_HAIKU = "claude-3-5-haiku-20241022", - - // Claude 3 Series (Legacy support) - CLAUDE_3_SONNET = "claude-3-sonnet-20240229", - CLAUDE_3_OPUS = "claude-3-opus-20240229", - CLAUDE_3_HAIKU = "claude-3-haiku-20240307", - - // Gemini 2.5 Series (Latest - 2025) - GEMINI_2_5_PRO = "gemini-2.5-pro", - GEMINI_2_5_FLASH = "gemini-2.5-flash", - GEMINI_2_5_FLASH_LITE = "gemini-2.5-flash-lite", - - // Gemini 2.0 Series - GEMINI_2_0_FLASH_001 = "gemini-2.0-flash-001", - - // Gemini 1.5 Series (Legacy support) - GEMINI_1_5_PRO = "gemini-1.5-pro", - GEMINI_1_5_FLASH = "gemini-1.5-flash", -} - -/** - * Supported Models for Google AI Studio - */ -export enum GoogleAIModels { - // Gemini 2.5 Series (Latest - 2025) - GEMINI_2_5_PRO = "gemini-2.5-pro", - GEMINI_2_5_FLASH = "gemini-2.5-flash", - GEMINI_2_5_FLASH_LITE = "gemini-2.5-flash-lite", - - // Gemini 2.0 Series - GEMINI_2_0_FLASH_001 = "gemini-2.0-flash-001", - - // Gemini 1.5 Series (Legacy support) - GEMINI_1_5_PRO = "gemini-1.5-pro", - GEMINI_1_5_FLASH = "gemini-1.5-flash", - GEMINI_1_5_FLASH_LITE = "gemini-1.5-flash-lite", -} - -/** - * Supported Models for Anthropic (Direct API) - */ -export enum AnthropicModels { - // Claude 3.5 Series (Latest) - CLAUDE_3_5_SONNET = "claude-3-5-sonnet-20241022", - CLAUDE_3_5_HAIKU = "claude-3-5-haiku-20241022", - - // Claude 3 Series (Legacy support) - CLAUDE_3_SONNET = "claude-3-sonnet-20240229", - CLAUDE_3_OPUS = "claude-3-opus-20240229", - CLAUDE_3_HAIKU = "claude-3-haiku-20240307", -} - -/** - * API Versions for various providers - */ -export enum APIVersions { - // Azure OpenAI API versions - AZURE_LATEST = "2025-04-01-preview", - AZURE_STABLE = "2024-10-21", - AZURE_LEGACY = "2023-12-01-preview", - - // OpenAI API versions - OPENAI_CURRENT = "v1", - OPENAI_BETA = "v1-beta", - - // Google AI API versions - GOOGLE_AI_CURRENT = "v1", - GOOGLE_AI_BETA = "v1beta", - - // Anthropic API versions - ANTHROPIC_CURRENT = "2023-06-01", - - // Other provider versions can be added here -} - // ============================================================================ // TYPE ALIASES // ============================================================================ @@ -169,7 +46,20 @@ export type SupportedModelName = /** * Extract provider names from enum */ -export type ProviderName = keyof typeof AIProviderName; +export type ProviderName = (typeof AIProviderName)[keyof typeof AIProviderName]; + +/** + * Provider status information + */ +export type ProviderStatus = { + provider: string; + status: "working" | "failed" | "not-configured"; + configured: boolean; + authenticated: boolean; + error?: string; + responseTime?: number; + model?: string; +}; /** * Provider error information @@ -477,6 +367,17 @@ export type ProviderRegistration = { defaultConfig?: IndividualProviderConfig; }; +/** + * Configuration options for the provider registry + */ +export type ProviderRegistryOptions = { + /** + * Enable loading of manual MCP configurations from .mcp-config.json + * Should only be true for CLI mode, false for SDK mode + */ + enableManualMCP?: boolean; +}; + /** * Provider metadata type */ @@ -1277,6 +1178,27 @@ export type SageMakerGenerateResult = { object?: unknown; }; +export type ProviderHealthStatusOptions = { + provider: AIProviderName; + isHealthy: boolean; + isConfigured: boolean; + hasApiKey: boolean; + lastChecked: Date; + error?: string; + warning?: string; + responseTime?: number; + configurationIssues: string[]; + recommendations: string[]; +}; + +export type ProviderHealthCheckOptions = { + timeout?: number; + includeConnectivityTest?: boolean; + includeModelValidation?: boolean; + cacheResults?: boolean; + maxCacheAge?: number; +}; + // ============================================================================ // Provider-Specific Namespace Types (Using Interfaces for Declaration Merging) // ============================================================================ diff --git a/src/lib/types/sdkTypes.ts b/src/lib/types/sdkTypes.ts index 88fab428e..701ee0197 100644 --- a/src/lib/types/sdkTypes.ts +++ b/src/lib/types/sdkTypes.ts @@ -80,7 +80,6 @@ export type { AISDKModel, ProviderError, AIModelProviderConfig, - AIProviderName, ProviderName, ModelCapability, ModelUseCase, diff --git a/src/lib/types/streamTypes.ts b/src/lib/types/streamTypes.ts index 1b40cdd3d..8581bb8f5 100644 --- a/src/lib/types/streamTypes.ts +++ b/src/lib/types/streamTypes.ts @@ -3,11 +3,11 @@ import type { ValidationSchema, StandardRecord } from "./typeAliases.js"; import type { AIModelProviderConfig } from "./providers.js"; import type { TextContent, ImageContent } from "./content.js"; import type { - AIProviderName, AnalyticsData, ToolExecutionEvent, ToolExecutionSummary, } from "../types/index.js"; +import { AIProviderName } from "../constants/enums.js"; import type { TokenUsage } from "./analytics.js"; import type { EvaluationData } from "../index.js"; import type { UnknownRecord, JsonValue } from "./common.js"; diff --git a/src/lib/types/taskClassificationTypes.ts b/src/lib/types/taskClassificationTypes.ts index 47a8ba154..2cfc76411 100644 --- a/src/lib/types/taskClassificationTypes.ts +++ b/src/lib/types/taskClassificationTypes.ts @@ -11,31 +11,31 @@ export type TaskType = "fast" | "reasoning"; /** * Result of task classification analysis */ -export interface TaskClassification { +export type TaskClassification = { /** The classified task type */ type: TaskType; /** Confidence score (0-1) in the classification */ confidence: number; /** Human-readable explanation of the classification decision */ reasoning: string; -} +}; /** * Internal scoring data used during classification analysis */ -export interface ClassificationScores { +export type ClassificationScores = { /** Score indicating likelihood of fast task */ fastScore: number; /** Score indicating likelihood of reasoning task */ reasoningScore: number; /** Array of reasons contributing to the scores */ reasons: string[]; -} +}; /** * Statistics for batch classification analysis */ -export interface ClassificationStats { +export type ClassificationStats = { /** Total number of prompts analyzed */ total: number; /** Number of prompts classified as fast */ @@ -44,14 +44,14 @@ export interface ClassificationStats { reasoning: number; /** Average confidence across all classifications */ averageConfidence: number; -} +}; /** * Validation result for testing classification accuracy */ -export interface ClassificationValidation { +export type ClassificationValidation = { /** Whether the classification matched the expected result */ correct: boolean; /** The actual classification result */ classification: TaskClassification; -} +}; diff --git a/src/lib/types/universalProviderOptions.ts b/src/lib/types/universalProviderOptions.ts index a32166bd8..76ef43934 100644 --- a/src/lib/types/universalProviderOptions.ts +++ b/src/lib/types/universalProviderOptions.ts @@ -9,7 +9,7 @@ import type { BaseContext, ContextConfig } from "./contextTypes.js"; * Base configuration interface for all AI providers * Uses Parameter Object Pattern for flexible, extensible configuration */ -export interface UniversalProviderOptions { +export type UniversalProviderOptions = { // Core parameters (common across all providers) prompt?: string; model?: string; @@ -28,7 +28,7 @@ export interface UniversalProviderOptions { // Provider-specific extensions (type-safe extensibility) extensionOptions?: Record; -} +}; /** * Generic provider options (without providerType) @@ -42,31 +42,31 @@ export type GenericProviderOptions = Omit< * Provider-specific configuration extensions * Discriminated union pattern for type-safe provider configs */ -export interface OpenAIProviderOptions extends UniversalProviderOptions { +export type OpenAIProviderOptions = UniversalProviderOptions & { providerType: "openai"; organization?: string; seed?: number; topP?: number; -} +}; -export interface GoogleAIProviderOptions extends UniversalProviderOptions { +export type GoogleAIProviderOptions = UniversalProviderOptions & { providerType: "google-ai"; topK?: number; candidateCount?: number; stopSequences?: string[]; -} +}; -export interface AnthropicProviderOptions extends UniversalProviderOptions { +export type AnthropicProviderOptions = UniversalProviderOptions & { providerType: "anthropic"; topK?: number; stopSequences?: string[]; -} +}; -export interface BedrockProviderOptions extends UniversalProviderOptions { +export type BedrockProviderOptions = UniversalProviderOptions & { providerType: "bedrock"; inferenceProfileArn?: string; region?: string; -} +}; /** * Discriminated union for type-safe provider configuration @@ -82,12 +82,12 @@ export type ProviderSpecificOptions = * Factory configuration interface * Supports both universal and provider-specific parameters */ -export interface ProviderFactoryConfig { +export type ProviderFactoryConfig = { providerName: string; modelName?: string; options?: UniversalProviderOptions | ProviderSpecificOptions; enableMCP?: boolean; -} +}; /** * Parameter normalization utilities diff --git a/src/lib/types/utilities.ts b/src/lib/types/utilities.ts index ac5bbcea9..b3a8c5863 100644 --- a/src/lib/types/utilities.ts +++ b/src/lib/types/utilities.ts @@ -31,3 +31,36 @@ export type APIValidationResult = { errorType?: "missing" | "format" | "config"; error?: string; }; + +/** + * Parsed proxy configuration + */ +export type ParsedProxyConfig = { + protocol: string; + hostname: string; + port: number; + auth?: { + username: string; + password: string; + }; + cleanUrl: string; +}; + +/** + * Interface for mem0 Memory instance methods based on actual mem0ai/oss API + */ +export type Mem0Memory = { + search( + query: string, + config: { userId?: string; limit?: number }, + ): Promise<{ results: Array<{ memory: string; id: string }> }>; + add( + messages: string, + config: { userId?: string; metadata?: Record }, + ): Promise<{ results: Array<{ id: string; memory: string }> }>; + get(memoryId: string): Promise<{ id: string; memory: string } | null>; + update(memoryId: string, data: string): Promise<{ message: string }>; + delete(memoryId: string): Promise<{ message: string }>; + history(memoryId: string): Promise; + reset(): Promise; +}; diff --git a/src/lib/utils/errorHandling.ts b/src/lib/utils/errorHandling.ts index 26ff5957c..749f28db2 100644 --- a/src/lib/utils/errorHandling.ts +++ b/src/lib/utils/errorHandling.ts @@ -26,7 +26,7 @@ export enum ErrorSeverity { } // Structured error interface -export interface StructuredError { +export type StructuredError = { code: string; message: string; category: ErrorCategory; @@ -37,7 +37,7 @@ export interface StructuredError { timestamp: Date; toolName?: string; serverId?: string; -} +}; // Error codes for different scenarios export const ERROR_CODES = { diff --git a/src/lib/utils/modelRouter.ts b/src/lib/utils/modelRouter.ts index 22309fa91..fc32cf612 100644 --- a/src/lib/utils/modelRouter.ts +++ b/src/lib/utils/modelRouter.ts @@ -11,14 +11,14 @@ import type { } from "../types/taskClassificationTypes.js"; import { redactForRouting } from "./promptRedaction.js"; -export interface ModelRoute { +export type ModelRoute = { provider: string; model: string; reasoning: string; confidence: number; -} +}; -export interface ModelRoutingOptions { +export type ModelRoutingOptions = { /** Override the task classification */ forceTaskType?: TaskType; /** Require specific performance characteristics */ @@ -27,7 +27,7 @@ export interface ModelRoutingOptions { requireCapability?: string; /** Fallback strategy if primary choice fails */ fallbackStrategy?: "fast" | "reasoning" | "auto"; -} +}; /** * Routing configuration constants diff --git a/src/lib/utils/providerHealth.ts b/src/lib/utils/providerHealth.ts index 170c30541..87bddea14 100644 --- a/src/lib/utils/providerHealth.ts +++ b/src/lib/utils/providerHealth.ts @@ -10,37 +10,20 @@ import { GoogleAIModels, AnthropicModels, BedrockModels, -} from "../types/providers.js"; +} from "../constants/enums.js"; import { API_KEY_LENGTHS, PROJECT_ID_FORMAT } from "./providerConfig.js"; import { basename } from "path"; import { createProxyFetch } from "../proxy/proxyFetch.js"; - -export interface ProviderHealthStatus { - provider: AIProviderName; - isHealthy: boolean; - isConfigured: boolean; - hasApiKey: boolean; - lastChecked: Date; - error?: string; - warning?: string; - responseTime?: number; - configurationIssues: string[]; - recommendations: string[]; -} - -export interface ProviderHealthCheckOptions { - timeout?: number; - includeConnectivityTest?: boolean; - includeModelValidation?: boolean; - cacheResults?: boolean; - maxCacheAge?: number; -} +import type { + ProviderHealthCheckOptions, + ProviderHealthStatusOptions, +} from "$lib/types/providers.js"; export class ProviderHealthChecker { private static healthCache = new Map< string, { - status: ProviderHealthStatus; + status: ProviderHealthStatusOptions; timestamp: number; } >(); @@ -77,7 +60,7 @@ export class ProviderHealthChecker { static async checkProviderHealth( providerName: AIProviderName, options: ProviderHealthCheckOptions = {}, - ): Promise { + ): Promise { const { timeout = this.DEFAULT_TIMEOUT, includeConnectivityTest = false, @@ -98,7 +81,7 @@ export class ProviderHealthChecker { // Check if provider has consecutive failures (blacklisting) const failureCount = this.consecutiveFailures.get(providerName) || 0; if (failureCount >= this.CONSECUTIVE_FAILURE_THRESHOLD) { - const healthStatus: ProviderHealthStatus = { + const healthStatus: ProviderHealthStatusOptions = { provider: providerName, isHealthy: false, isConfigured: false, @@ -119,7 +102,7 @@ export class ProviderHealthChecker { } const startTime = Date.now(); - const healthStatus: ProviderHealthStatus = { + const healthStatus: ProviderHealthStatusOptions = { provider: providerName, isHealthy: false, isConfigured: false, @@ -203,7 +186,7 @@ export class ProviderHealthChecker { */ private static async checkEnvironmentConfiguration( providerName: AIProviderName, - healthStatus: ProviderHealthStatus, + healthStatus: ProviderHealthStatusOptions, ): Promise { const requiredEnvVars = this.getRequiredEnvironmentVariables(providerName); @@ -262,7 +245,7 @@ export class ProviderHealthChecker { */ private static async checkApiKeyValidity( providerName: AIProviderName, - healthStatus: ProviderHealthStatus, + healthStatus: ProviderHealthStatusOptions, ): Promise { // 🎯 SPECIAL HANDLING FOR VERTEX AI: Check both auth methods if (providerName === AIProviderName.VERTEX) { @@ -376,7 +359,7 @@ export class ProviderHealthChecker { */ private static async checkConnectivity( providerName: AIProviderName, - healthStatus: ProviderHealthStatus, + healthStatus: ProviderHealthStatusOptions, timeout: number, ): Promise { const endpoint = this.getProviderHealthEndpoint(providerName); @@ -473,7 +456,7 @@ export class ProviderHealthChecker { */ private static async checkModelAvailability( providerName: AIProviderName, - healthStatus: ProviderHealthStatus, + healthStatus: ProviderHealthStatusOptions, ): Promise { // Basic model name validation and recommendations const commonModels = this.getCommonModelsForProvider(providerName); @@ -622,7 +605,7 @@ export class ProviderHealthChecker { */ private static async checkProviderSpecificConfig( providerName: AIProviderName, - healthStatus: ProviderHealthStatus, + healthStatus: ProviderHealthStatusOptions, ): Promise { switch (providerName) { case AIProviderName.VERTEX: @@ -644,7 +627,7 @@ export class ProviderHealthChecker { * Check Vertex AI configuration */ private static async checkVertexAIConfig( - healthStatus: ProviderHealthStatus, + healthStatus: ProviderHealthStatusOptions, ): Promise { logger.debug("Starting Vertex AI health check"); @@ -683,7 +666,7 @@ export class ProviderHealthChecker { * Check Vertex AI authentication */ private static async checkVertexAuthentication( - healthStatus: ProviderHealthStatus, + healthStatus: ProviderHealthStatusOptions, ): Promise { let hasValidAuth = false; @@ -711,7 +694,7 @@ export class ProviderHealthChecker { * Check Google Application Credentials file */ private static async checkGoogleApplicationCredentials( - healthStatus: ProviderHealthStatus, + healthStatus: ProviderHealthStatusOptions, ): Promise { const credentialsPath = process.env.GOOGLE_APPLICATION_CREDENTIALS; if (!credentialsPath) { @@ -743,7 +726,7 @@ export class ProviderHealthChecker { * Check individual Google credentials */ private static checkIndividualGoogleCredentials( - healthStatus: ProviderHealthStatus, + healthStatus: ProviderHealthStatusOptions, ): boolean { const hasServiceAccountKey = !!process.env.GOOGLE_SERVICE_ACCOUNT_KEY; const hasIndividualCredentials = !!( @@ -763,7 +746,7 @@ export class ProviderHealthChecker { * Check AWS Bedrock configuration */ private static async checkBedrockConfig( - healthStatus: ProviderHealthStatus, + healthStatus: ProviderHealthStatusOptions, ): Promise { logger.debug("Starting AWS Bedrock comprehensive health check"); @@ -781,7 +764,9 @@ export class ProviderHealthChecker { /** * Check AWS region configuration */ - private static checkAWSRegion(healthStatus: ProviderHealthStatus): void { + private static checkAWSRegion( + healthStatus: ProviderHealthStatusOptions, + ): void { const awsRegion = process.env.AWS_REGION; const validBedrockRegions = [ "us-east-1", @@ -811,7 +796,9 @@ export class ProviderHealthChecker { /** * Check AWS credentials */ - private static checkAWSCredentials(healthStatus: ProviderHealthStatus): void { + private static checkAWSCredentials( + healthStatus: ProviderHealthStatusOptions, + ): void { const awsAccessKeyId = process.env.AWS_ACCESS_KEY_ID; const awsSecretAccessKey = process.env.AWS_SECRET_ACCESS_KEY; const awsProfile = process.env.AWS_PROFILE; @@ -834,7 +821,9 @@ export class ProviderHealthChecker { /** * Check Bedrock models */ - private static checkBedrockModels(healthStatus: ProviderHealthStatus): void { + private static checkBedrockModels( + healthStatus: ProviderHealthStatusOptions, + ): void { const bedrockModel = process.env.BEDROCK_MODEL || process.env.BEDROCK_MODEL_ID; const supportedModels = [ @@ -860,7 +849,7 @@ export class ProviderHealthChecker { * Check Bedrock endpoint */ private static checkBedrockEndpoint( - healthStatus: ProviderHealthStatus, + healthStatus: ProviderHealthStatusOptions, ): void { const bedrockEndpoint = process.env.BEDROCK_ENDPOINT_URL; if (bedrockEndpoint && !bedrockEndpoint.startsWith("https://")) { @@ -877,7 +866,7 @@ export class ProviderHealthChecker { * Check Azure OpenAI configuration */ private static async checkAzureConfig( - healthStatus: ProviderHealthStatus, + healthStatus: ProviderHealthStatusOptions, ): Promise { const azureEndpoint = process.env.AZURE_OPENAI_ENDPOINT; if (azureEndpoint && !azureEndpoint.startsWith("https://")) { @@ -907,7 +896,7 @@ export class ProviderHealthChecker { * Check Ollama configuration */ private static async checkOllamaConfig( - healthStatus: ProviderHealthStatus, + healthStatus: ProviderHealthStatusOptions, ): Promise { const ollamaBase = process.env.OLLAMA_API_BASE || "http://localhost:11434"; if (!ollamaBase.startsWith("http")) { @@ -978,7 +967,7 @@ export class ProviderHealthChecker { private static getCachedHealth( providerName: AIProviderName, maxAge: number, - ): ProviderHealthStatus | null { + ): ProviderHealthStatusOptions | null { const cached = this.healthCache.get(providerName); if (!cached) { @@ -1658,7 +1647,7 @@ export class ProviderHealthChecker { */ static async checkAllProvidersHealth( options: ProviderHealthCheckOptions = {}, - ): Promise { + ): Promise { const providers: AIProviderName[] = [ AIProviderName.VERTEX, AIProviderName.GOOGLE_AI, @@ -1699,7 +1688,7 @@ export class ProviderHealthChecker { /** * Get a summary of provider health */ - static getHealthSummary(healthStatuses: ProviderHealthStatus[]): { + static getHealthSummary(healthStatuses: ProviderHealthStatusOptions[]): { total: number; healthy: number; configured: number; diff --git a/src/lib/utils/providerSetupMessages.ts b/src/lib/utils/providerSetupMessages.ts index 5820e36a2..79c6b5c32 100644 --- a/src/lib/utils/providerSetupMessages.ts +++ b/src/lib/utils/providerSetupMessages.ts @@ -8,7 +8,7 @@ import { GoogleAIModels, AnthropicModels, APIVersions, -} from "../types/providers.js"; +} from "../constants/enums.js"; /** * Generate enhanced error message with setup instructions diff --git a/src/lib/utils/providerUtils.ts b/src/lib/utils/providerUtils.ts index 68dae339a..30aa56b94 100644 --- a/src/lib/utils/providerUtils.ts +++ b/src/lib/utils/providerUtils.ts @@ -5,7 +5,8 @@ import { AIProviderFactory } from "../core/factory.js"; import { logger } from "./logger.js"; import type { UnknownRecord } from "../types/common.js"; -import type { AIProviderName, ProviderError } from "../types/index.js"; +import type { ProviderError } from "../types/index.js"; +import { AIProviderName } from "../constants/enums.js"; import { ProviderHealthChecker } from "./providerHealth.js"; import { API_KEY_FORMATS,