@juspay/neurolink 7.6.1 → 7.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/CHANGELOG.md +9 -4
  2. package/README.md +78 -3
  3. package/dist/cli/commands/config.d.ts +275 -3
  4. package/dist/cli/commands/config.js +121 -0
  5. package/dist/cli/commands/mcp.js +77 -28
  6. package/dist/cli/factories/commandFactory.js +359 -6
  7. package/dist/core/analytics.js +7 -27
  8. package/dist/core/baseProvider.js +43 -4
  9. package/dist/core/constants.d.ts +46 -0
  10. package/dist/core/constants.js +47 -0
  11. package/dist/core/dynamicModels.d.ts +16 -4
  12. package/dist/core/dynamicModels.js +130 -26
  13. package/dist/core/evaluation.js +5 -1
  14. package/dist/core/evaluationProviders.d.ts +6 -2
  15. package/dist/core/evaluationProviders.js +41 -125
  16. package/dist/core/factory.d.ts +5 -0
  17. package/dist/core/factory.js +62 -50
  18. package/dist/core/modelConfiguration.d.ts +246 -0
  19. package/dist/core/modelConfiguration.js +775 -0
  20. package/dist/core/types.d.ts +22 -3
  21. package/dist/core/types.js +5 -1
  22. package/dist/factories/providerRegistry.js +3 -3
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js +1 -1
  25. package/dist/lib/core/analytics.js +7 -27
  26. package/dist/lib/core/baseProvider.js +43 -4
  27. package/dist/lib/core/constants.d.ts +46 -0
  28. package/dist/lib/core/constants.js +47 -0
  29. package/dist/lib/core/dynamicModels.d.ts +16 -4
  30. package/dist/lib/core/dynamicModels.js +130 -26
  31. package/dist/lib/core/evaluation.js +5 -1
  32. package/dist/lib/core/evaluationProviders.d.ts +6 -2
  33. package/dist/lib/core/evaluationProviders.js +41 -125
  34. package/dist/lib/core/factory.d.ts +5 -0
  35. package/dist/lib/core/factory.js +63 -50
  36. package/dist/lib/core/modelConfiguration.d.ts +246 -0
  37. package/dist/lib/core/modelConfiguration.js +775 -0
  38. package/dist/lib/core/types.d.ts +22 -3
  39. package/dist/lib/core/types.js +5 -1
  40. package/dist/lib/factories/providerRegistry.js +3 -3
  41. package/dist/lib/index.d.ts +1 -1
  42. package/dist/lib/index.js +1 -1
  43. package/dist/lib/mcp/factory.d.ts +5 -5
  44. package/dist/lib/mcp/factory.js +2 -2
  45. package/dist/lib/mcp/servers/utilities/utilityServer.d.ts +1 -1
  46. package/dist/lib/mcp/servers/utilities/utilityServer.js +1 -1
  47. package/dist/lib/mcp/toolRegistry.js +2 -2
  48. package/dist/lib/neurolink.d.ts +168 -12
  49. package/dist/lib/neurolink.js +685 -123
  50. package/dist/lib/providers/anthropic.js +52 -2
  51. package/dist/lib/providers/googleAiStudio.js +4 -0
  52. package/dist/lib/providers/googleVertex.d.ts +75 -9
  53. package/dist/lib/providers/googleVertex.js +365 -46
  54. package/dist/lib/providers/huggingFace.d.ts +52 -11
  55. package/dist/lib/providers/huggingFace.js +180 -42
  56. package/dist/lib/providers/litellm.d.ts +9 -9
  57. package/dist/lib/providers/litellm.js +103 -16
  58. package/dist/lib/providers/ollama.d.ts +52 -17
  59. package/dist/lib/providers/ollama.js +276 -68
  60. package/dist/lib/sdk/toolRegistration.d.ts +42 -0
  61. package/dist/lib/sdk/toolRegistration.js +269 -27
  62. package/dist/lib/telemetry/telemetryService.d.ts +6 -0
  63. package/dist/lib/telemetry/telemetryService.js +38 -3
  64. package/dist/lib/types/contextTypes.d.ts +75 -11
  65. package/dist/lib/types/contextTypes.js +227 -1
  66. package/dist/lib/types/domainTypes.d.ts +62 -0
  67. package/dist/lib/types/domainTypes.js +5 -0
  68. package/dist/lib/types/generateTypes.d.ts +52 -0
  69. package/dist/lib/types/index.d.ts +1 -0
  70. package/dist/lib/types/mcpTypes.d.ts +1 -1
  71. package/dist/lib/types/mcpTypes.js +1 -1
  72. package/dist/lib/types/streamTypes.d.ts +14 -0
  73. package/dist/lib/types/universalProviderOptions.d.ts +1 -1
  74. package/dist/lib/utils/errorHandling.d.ts +142 -0
  75. package/dist/lib/utils/errorHandling.js +316 -0
  76. package/dist/lib/utils/factoryProcessing.d.ts +74 -0
  77. package/dist/lib/utils/factoryProcessing.js +588 -0
  78. package/dist/lib/utils/optionsConversion.d.ts +54 -0
  79. package/dist/lib/utils/optionsConversion.js +126 -0
  80. package/dist/lib/utils/optionsUtils.d.ts +246 -0
  81. package/dist/lib/utils/optionsUtils.js +960 -0
  82. package/dist/lib/utils/providerHealth.d.ts +107 -0
  83. package/dist/lib/utils/providerHealth.js +507 -0
  84. package/dist/lib/utils/providerUtils.d.ts +17 -0
  85. package/dist/lib/utils/providerUtils.js +271 -16
  86. package/dist/lib/utils/timeout.js +1 -1
  87. package/dist/lib/utils/tokenLimits.d.ts +33 -0
  88. package/dist/lib/utils/tokenLimits.js +118 -0
  89. package/dist/mcp/factory.d.ts +5 -5
  90. package/dist/mcp/factory.js +2 -2
  91. package/dist/mcp/servers/utilities/utilityServer.d.ts +1 -1
  92. package/dist/mcp/servers/utilities/utilityServer.js +1 -1
  93. package/dist/mcp/toolRegistry.js +2 -2
  94. package/dist/neurolink.d.ts +168 -12
  95. package/dist/neurolink.js +685 -123
  96. package/dist/providers/anthropic.js +52 -2
  97. package/dist/providers/googleAiStudio.js +4 -0
  98. package/dist/providers/googleVertex.d.ts +75 -9
  99. package/dist/providers/googleVertex.js +365 -46
  100. package/dist/providers/huggingFace.d.ts +52 -11
  101. package/dist/providers/huggingFace.js +181 -43
  102. package/dist/providers/litellm.d.ts +9 -9
  103. package/dist/providers/litellm.js +103 -16
  104. package/dist/providers/ollama.d.ts +52 -17
  105. package/dist/providers/ollama.js +276 -68
  106. package/dist/sdk/toolRegistration.d.ts +42 -0
  107. package/dist/sdk/toolRegistration.js +269 -27
  108. package/dist/telemetry/telemetryService.d.ts +6 -0
  109. package/dist/telemetry/telemetryService.js +38 -3
  110. package/dist/types/contextTypes.d.ts +75 -11
  111. package/dist/types/contextTypes.js +227 -2
  112. package/dist/types/domainTypes.d.ts +62 -0
  113. package/dist/types/domainTypes.js +5 -0
  114. package/dist/types/generateTypes.d.ts +52 -0
  115. package/dist/types/index.d.ts +1 -0
  116. package/dist/types/mcpTypes.d.ts +1 -1
  117. package/dist/types/mcpTypes.js +1 -1
  118. package/dist/types/streamTypes.d.ts +14 -0
  119. package/dist/types/universalProviderOptions.d.ts +1 -1
  120. package/dist/types/universalProviderOptions.js +0 -1
  121. package/dist/utils/errorHandling.d.ts +142 -0
  122. package/dist/utils/errorHandling.js +316 -0
  123. package/dist/utils/factoryProcessing.d.ts +74 -0
  124. package/dist/utils/factoryProcessing.js +588 -0
  125. package/dist/utils/optionsConversion.d.ts +54 -0
  126. package/dist/utils/optionsConversion.js +126 -0
  127. package/dist/utils/optionsUtils.d.ts +246 -0
  128. package/dist/utils/optionsUtils.js +960 -0
  129. package/dist/utils/providerHealth.d.ts +107 -0
  130. package/dist/utils/providerHealth.js +507 -0
  131. package/dist/utils/providerUtils.d.ts +17 -0
  132. package/dist/utils/providerUtils.js +271 -16
  133. package/dist/utils/timeout.js +1 -1
  134. package/dist/utils/tokenLimits.d.ts +33 -0
  135. package/dist/utils/tokenLimits.js +118 -0
  136. package/package.json +2 -2
@@ -0,0 +1,316 @@
1
+ /**
2
+ * Robust Error Handling Utilities for NeuroLink
3
+ * Provides structured error management for tool execution and system operations
4
+ */
5
+ import { logger } from "./logger.js";
6
+ // Error categories for proper handling
7
+ export var ErrorCategory;
8
+ (function (ErrorCategory) {
9
+ ErrorCategory["VALIDATION"] = "validation";
10
+ ErrorCategory["TIMEOUT"] = "timeout";
11
+ ErrorCategory["NETWORK"] = "network";
12
+ ErrorCategory["RESOURCE"] = "resource";
13
+ ErrorCategory["PERMISSION"] = "permission";
14
+ ErrorCategory["CONFIGURATION"] = "configuration";
15
+ ErrorCategory["EXECUTION"] = "execution";
16
+ ErrorCategory["SYSTEM"] = "system";
17
+ })(ErrorCategory || (ErrorCategory = {}));
18
+ // Error severity levels
19
+ export var ErrorSeverity;
20
+ (function (ErrorSeverity) {
21
+ ErrorSeverity["LOW"] = "low";
22
+ ErrorSeverity["MEDIUM"] = "medium";
23
+ ErrorSeverity["HIGH"] = "high";
24
+ ErrorSeverity["CRITICAL"] = "critical";
25
+ })(ErrorSeverity || (ErrorSeverity = {}));
26
+ // Error codes for different scenarios
27
+ export const ERROR_CODES = {
28
+ // Tool errors
29
+ TOOL_NOT_FOUND: "TOOL_NOT_FOUND",
30
+ TOOL_EXECUTION_FAILED: "TOOL_EXECUTION_FAILED",
31
+ TOOL_TIMEOUT: "TOOL_TIMEOUT",
32
+ TOOL_VALIDATION_FAILED: "TOOL_VALIDATION_FAILED",
33
+ // Parameter errors
34
+ INVALID_PARAMETERS: "INVALID_PARAMETERS",
35
+ MISSING_REQUIRED_PARAM: "MISSING_REQUIRED_PARAM",
36
+ // System errors
37
+ MEMORY_EXHAUSTED: "MEMORY_EXHAUSTED",
38
+ NETWORK_ERROR: "NETWORK_ERROR",
39
+ PERMISSION_DENIED: "PERMISSION_DENIED",
40
+ // Provider errors
41
+ PROVIDER_NOT_AVAILABLE: "PROVIDER_NOT_AVAILABLE",
42
+ PROVIDER_AUTH_FAILED: "PROVIDER_AUTH_FAILED",
43
+ PROVIDER_QUOTA_EXCEEDED: "PROVIDER_QUOTA_EXCEEDED",
44
+ // Configuration errors
45
+ INVALID_CONFIGURATION: "INVALID_CONFIGURATION",
46
+ MISSING_CONFIGURATION: "MISSING_CONFIGURATION",
47
+ };
48
+ /**
49
+ * Enhanced error class with structured information
50
+ */
51
+ export class NeuroLinkError extends Error {
52
+ code;
53
+ category;
54
+ severity;
55
+ retriable;
56
+ context;
57
+ timestamp;
58
+ toolName;
59
+ serverId;
60
+ constructor(options) {
61
+ super(options.message);
62
+ this.name = "NeuroLinkError";
63
+ this.code = options.code;
64
+ this.category = options.category;
65
+ this.severity = options.severity;
66
+ this.retriable = options.retriable;
67
+ this.context = options.context || {};
68
+ this.timestamp = new Date();
69
+ this.toolName = options.toolName;
70
+ this.serverId = options.serverId;
71
+ // Preserve original error stack if provided
72
+ if (options.originalError) {
73
+ this.stack = options.originalError.stack;
74
+ this.context.originalMessage = options.originalError.message;
75
+ }
76
+ }
77
+ /**
78
+ * Convert to JSON for logging and serialization
79
+ */
80
+ toJSON() {
81
+ return {
82
+ code: this.code,
83
+ message: this.message,
84
+ category: this.category,
85
+ severity: this.severity,
86
+ retriable: this.retriable,
87
+ context: this.context,
88
+ timestamp: this.timestamp,
89
+ toolName: this.toolName,
90
+ serverId: this.serverId,
91
+ };
92
+ }
93
+ }
94
+ /**
95
+ * Error factory for common error scenarios
96
+ */
97
+ export class ErrorFactory {
98
+ /**
99
+ * Create a tool not found error
100
+ */
101
+ static toolNotFound(toolName, availableTools) {
102
+ return new NeuroLinkError({
103
+ code: ERROR_CODES.TOOL_NOT_FOUND,
104
+ message: `Tool '${toolName}' not found`,
105
+ category: ErrorCategory.VALIDATION,
106
+ severity: ErrorSeverity.MEDIUM,
107
+ retriable: false,
108
+ context: { toolName, availableTools },
109
+ toolName,
110
+ });
111
+ }
112
+ /**
113
+ * Create a tool execution failed error
114
+ */
115
+ static toolExecutionFailed(toolName, originalError, serverId) {
116
+ return new NeuroLinkError({
117
+ code: ERROR_CODES.TOOL_EXECUTION_FAILED,
118
+ message: `Tool '${toolName}' execution failed: ${originalError.message}`,
119
+ category: ErrorCategory.EXECUTION,
120
+ severity: ErrorSeverity.HIGH,
121
+ retriable: true,
122
+ originalError,
123
+ toolName,
124
+ serverId,
125
+ });
126
+ }
127
+ /**
128
+ * Create a tool timeout error
129
+ */
130
+ static toolTimeout(toolName, timeoutMs, serverId) {
131
+ return new NeuroLinkError({
132
+ code: ERROR_CODES.TOOL_TIMEOUT,
133
+ message: `Tool '${toolName}' timed out after ${timeoutMs}ms`,
134
+ category: ErrorCategory.TIMEOUT,
135
+ severity: ErrorSeverity.HIGH,
136
+ retriable: true,
137
+ context: { timeoutMs },
138
+ toolName,
139
+ serverId,
140
+ });
141
+ }
142
+ /**
143
+ * Create a parameter validation error
144
+ */
145
+ static invalidParameters(toolName, validationError, providedParams) {
146
+ return new NeuroLinkError({
147
+ code: ERROR_CODES.INVALID_PARAMETERS,
148
+ message: `Invalid parameters for tool '${toolName}': ${validationError.message}`,
149
+ category: ErrorCategory.VALIDATION,
150
+ severity: ErrorSeverity.MEDIUM,
151
+ retriable: false,
152
+ context: { providedParams },
153
+ originalError: validationError,
154
+ toolName,
155
+ });
156
+ }
157
+ /**
158
+ * Create a network error
159
+ */
160
+ static networkError(toolName, originalError, serverId) {
161
+ return new NeuroLinkError({
162
+ code: ERROR_CODES.NETWORK_ERROR,
163
+ message: `Network error in tool '${toolName}': ${originalError.message}`,
164
+ category: ErrorCategory.NETWORK,
165
+ severity: ErrorSeverity.HIGH,
166
+ retriable: true,
167
+ originalError,
168
+ toolName,
169
+ serverId,
170
+ });
171
+ }
172
+ /**
173
+ * Create a memory exhaustion error
174
+ */
175
+ static memoryExhausted(toolName, memoryUsageMB) {
176
+ return new NeuroLinkError({
177
+ code: ERROR_CODES.MEMORY_EXHAUSTED,
178
+ message: `Memory exhausted during tool '${toolName}' execution (${memoryUsageMB}MB used)`,
179
+ category: ErrorCategory.RESOURCE,
180
+ severity: ErrorSeverity.CRITICAL,
181
+ retriable: false,
182
+ context: { memoryUsageMB },
183
+ toolName,
184
+ });
185
+ }
186
+ }
187
+ /**
188
+ * Timeout wrapper for async operations
189
+ */
190
+ export async function withTimeout(promise, timeoutMs, timeoutError) {
191
+ const timeoutPromise = new Promise((_, reject) => {
192
+ setTimeout(() => {
193
+ reject(timeoutError || new Error(`Operation timed out after ${timeoutMs}ms`));
194
+ }, timeoutMs);
195
+ });
196
+ return Promise.race([promise, timeoutPromise]);
197
+ }
198
+ /**
199
+ * Retry mechanism for retriable operations
200
+ */
201
+ export async function withRetry(operation, options) {
202
+ const { maxAttempts, delayMs, isRetriable = () => true, onRetry } = options;
203
+ let lastError;
204
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
205
+ try {
206
+ return await operation();
207
+ }
208
+ catch (error) {
209
+ lastError = error instanceof Error ? error : new Error(String(error));
210
+ // Don't retry on the last attempt or if error is not retriable
211
+ if (attempt === maxAttempts || !isRetriable(lastError)) {
212
+ throw lastError;
213
+ }
214
+ if (onRetry) {
215
+ onRetry(attempt, lastError);
216
+ }
217
+ // Wait before retry
218
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
219
+ }
220
+ }
221
+ throw lastError;
222
+ }
223
+ /**
224
+ * Circuit breaker for preventing cascading failures
225
+ */
226
+ export class CircuitBreaker {
227
+ failureThreshold;
228
+ resetTimeoutMs;
229
+ failures = 0;
230
+ lastFailureTime = 0;
231
+ state = "closed";
232
+ constructor(failureThreshold = 5, resetTimeoutMs = 60000) {
233
+ this.failureThreshold = failureThreshold;
234
+ this.resetTimeoutMs = resetTimeoutMs;
235
+ }
236
+ async execute(operation) {
237
+ if (this.state === "open") {
238
+ if (Date.now() - this.lastFailureTime > this.resetTimeoutMs) {
239
+ this.state = "half-open";
240
+ }
241
+ else {
242
+ throw new Error("Circuit breaker is open - operation not executed");
243
+ }
244
+ }
245
+ try {
246
+ const result = await operation();
247
+ this.onSuccess();
248
+ return result;
249
+ }
250
+ catch (error) {
251
+ this.onFailure();
252
+ throw error;
253
+ }
254
+ }
255
+ onSuccess() {
256
+ this.failures = 0;
257
+ this.state = "closed";
258
+ }
259
+ onFailure() {
260
+ this.failures++;
261
+ this.lastFailureTime = Date.now();
262
+ if (this.failures >= this.failureThreshold) {
263
+ this.state = "open";
264
+ }
265
+ }
266
+ getState() {
267
+ return this.state;
268
+ }
269
+ getFailureCount() {
270
+ return this.failures;
271
+ }
272
+ }
273
+ /**
274
+ * Error handler that decides whether to retry based on error type
275
+ */
276
+ export function isRetriableError(error) {
277
+ if (error instanceof NeuroLinkError) {
278
+ return error.retriable;
279
+ }
280
+ // Check for common retriable error patterns
281
+ const retriablePatterns = [
282
+ /timeout/i,
283
+ /network/i,
284
+ /connection/i,
285
+ /temporary/i,
286
+ /rate limit/i,
287
+ /quota/i,
288
+ /503/i, // Service unavailable
289
+ /502/i, // Bad gateway
290
+ /504/i, // Gateway timeout
291
+ ];
292
+ return retriablePatterns.some((pattern) => pattern.test(error.message));
293
+ }
294
+ /**
295
+ * Enhanced error logger that provides structured logging
296
+ */
297
+ export function logStructuredError(error, context) {
298
+ const logData = {
299
+ ...error.toJSON(),
300
+ ...context,
301
+ };
302
+ switch (error.severity) {
303
+ case ErrorSeverity.CRITICAL:
304
+ logger.error(`[CRITICAL] ${error.message}`, logData);
305
+ break;
306
+ case ErrorSeverity.HIGH:
307
+ logger.error(`[HIGH] ${error.message}`, logData);
308
+ break;
309
+ case ErrorSeverity.MEDIUM:
310
+ logger.warn(`[MEDIUM] ${error.message}`, logData);
311
+ break;
312
+ case ErrorSeverity.LOW:
313
+ logger.info(`[LOW] ${error.message}`, logData);
314
+ break;
315
+ }
316
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Factory options processing utilities
3
+ *
4
+ * Processes factory configuration and ensures it flows through to AI providers
5
+ */
6
+ import type { GenerateOptions } from "../types/generateTypes.js";
7
+ import type { StreamOptions } from "../types/streamTypes.js";
8
+ import type { TextGenerationOptions } from "../core/types.js";
9
+ import type { UnknownRecord, JsonValue } from "../types/common.js";
10
+ /**
11
+ * Process factory configuration from enhanced options (with caching)
12
+ * Extracts and validates factory config for provider integration
13
+ */
14
+ export declare function processFactoryOptions(options: GenerateOptions | StreamOptions): {
15
+ hasFactoryConfig: boolean;
16
+ domainType?: string;
17
+ domainConfig?: Record<string, unknown>;
18
+ enhancementType?: string;
19
+ processedContext?: Record<string, JsonValue>;
20
+ };
21
+ /**
22
+ * Enhance TextGenerationOptions with factory configuration
23
+ * Converts enhanced GenerateOptions/StreamOptions to internal format
24
+ */
25
+ export declare function enhanceTextGenerationOptions(baseOptions: TextGenerationOptions, factoryResult: ReturnType<typeof processFactoryOptions>): TextGenerationOptions;
26
+ /**
27
+ * Check if options require factory processing
28
+ * Quick check to determine if factory enhancement is needed
29
+ */
30
+ export declare function requiresFactoryProcessing(options: GenerateOptions | StreamOptions | UnknownRecord): boolean;
31
+ /**
32
+ * Extract streaming configuration for factory processing
33
+ * Handles streaming-specific factory enhancements
34
+ */
35
+ export declare function processStreamingFactoryOptions(options: StreamOptions): {
36
+ hasStreamingConfig: boolean;
37
+ streamingEnabled?: boolean;
38
+ enhancedConfig?: StreamOptions["streaming"];
39
+ };
40
+ /**
41
+ * Convert enhanced StreamOptions back to clean StreamOptions
42
+ * Strips factory configuration while preserving enhanced context
43
+ */
44
+ export declare function createCleanStreamOptions(enhancedOptions: StreamOptions): StreamOptions;
45
+ /**
46
+ * Validate factory configuration
47
+ * Ensures factory config is valid before processing
48
+ */
49
+ export declare function validateFactoryConfig(factoryConfig: GenerateOptions["factoryConfig"]): {
50
+ isValid: boolean;
51
+ errors: string[];
52
+ };
53
+ /**
54
+ * Get factory processing cache statistics
55
+ * Useful for monitoring cache performance and debugging
56
+ */
57
+ export declare function getFactoryProcessingCacheStats(): {
58
+ hits: number;
59
+ misses: number;
60
+ evictions: number;
61
+ totalRequests: number;
62
+ size: number;
63
+ hitRate: number;
64
+ };
65
+ /**
66
+ * Clear factory processing cache
67
+ * Useful for testing or memory management
68
+ */
69
+ export declare function clearFactoryProcessingCache(): void;
70
+ /**
71
+ * Evict old entries from factory processing cache
72
+ * Useful for periodic cleanup
73
+ */
74
+ export declare function evictOldFactoryProcessingCache(maxAge?: number): number;