@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,960 @@
1
+ /**
2
+ * Options Enhancement Utilities
3
+ * Provides intelligent enhancement of GenerateOptions with factory patterns
4
+ * Supports domain configuration, streaming optimization, and MCP integration
5
+ */
6
+ import { ContextConverter } from "../types/contextTypes.js";
7
+ import { logger } from "./logger.js";
8
+ /**
9
+ * Options Enhancement Utility Class
10
+ * Main utility for enhancing GenerateOptions with factory patterns
11
+ */
12
+ export class OptionsEnhancer {
13
+ /**
14
+ * Thread-safe enhancement counter using SharedArrayBuffer and Atomics
15
+ *
16
+ * NOTE ON THREAD-SAFETY:
17
+ * JavaScript's main execution is single-threaded. Thread-safety using SharedArrayBuffer and Atomics
18
+ * is only relevant in environments that support multi-threading, such as web workers (in browsers)
19
+ * or worker threads (in Node.js).
20
+ *
21
+ * RATIONALE FOR THREAD-SAFETY:
22
+ * OptionsEnhancer is used across multiple worker threads in high-performance scenarios:
23
+ * - Parallel batch processing (batchEnhanceParallel function)
24
+ * - Streaming operations with concurrent enhancements
25
+ * - Factory pattern implementations that may run in web workers
26
+ * - Analytics tracking requires accurate counts across all threads
27
+ *
28
+ * SharedArrayBuffer + Atomics ensures accurate statistics without race conditions
29
+ * when enhancement operations occur simultaneously across multiple contexts.
30
+ *
31
+ * NOTE: SharedArrayBuffer requires cross-origin isolation headers in browsers:
32
+ * - Cross-Origin-Opener-Policy: same-origin
33
+ * - Cross-Origin-Embedder-Policy: require-corp
34
+ * Without these, SharedArrayBuffer will be unavailable and thread-safety will be disabled.
35
+ * In Node.js, SharedArrayBuffer is available in worker threads.
36
+ */
37
+ static enhancementCountBuffer = (() => {
38
+ // In browsers, SharedArrayBuffer is only usable if cross-origin isolation is enabled
39
+ const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
40
+ const crossOriginIsolated = isBrowser ? !!window.crossOriginIsolated : true;
41
+ if (typeof SharedArrayBuffer !== "undefined" && crossOriginIsolated) {
42
+ try {
43
+ return new SharedArrayBuffer(4); // 4 bytes for Int32
44
+ }
45
+ catch (e) {
46
+ // SharedArrayBuffer is defined but not usable (browser CORS headers not set)
47
+ if (typeof logger !== "undefined" && logger?.warn) {
48
+ logger.warn("[OptionsEnhancer] SharedArrayBuffer is defined but not usable. " +
49
+ "Ensure cross-origin isolation headers are set in browser environments. " +
50
+ "Falling back to non-thread-safe enhancement counter.");
51
+ }
52
+ return null;
53
+ }
54
+ }
55
+ else if (isBrowser && !crossOriginIsolated) {
56
+ if (typeof logger !== "undefined" && logger?.debug) {
57
+ logger.debug("[OptionsEnhancer] SharedArrayBuffer requires cross-origin isolation in browsers. " +
58
+ "Set Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp headers. " +
59
+ "Falling back to non-thread-safe enhancement counter.");
60
+ }
61
+ }
62
+ return null;
63
+ })();
64
+ static enhancementCountArray = OptionsEnhancer.enhancementCountBuffer
65
+ ? new Int32Array(OptionsEnhancer.enhancementCountBuffer)
66
+ : null;
67
+ // Fallback counter for environments without SharedArrayBuffer (ensures compatibility everywhere)
68
+ static fallbackEnhancementCount = 0;
69
+ static get enhancementCount() {
70
+ if (OptionsEnhancer.enhancementCountArray) {
71
+ return Atomics.load(OptionsEnhancer.enhancementCountArray, 0);
72
+ }
73
+ else {
74
+ return OptionsEnhancer.fallbackEnhancementCount;
75
+ }
76
+ }
77
+ static incrementEnhancementCount() {
78
+ if (OptionsEnhancer.enhancementCountArray) {
79
+ return Atomics.add(OptionsEnhancer.enhancementCountArray, 0, 1);
80
+ }
81
+ else {
82
+ return ++OptionsEnhancer.fallbackEnhancementCount;
83
+ }
84
+ }
85
+ /**
86
+ * Enhance GenerateOptions with factory patterns
87
+ * Primary method for applying enhancements
88
+ */
89
+ static enhance(options, enhancementOptions) {
90
+ const startTime = Date.now();
91
+ this.incrementEnhancementCount();
92
+ logger.debug(`Enhancing options with ${enhancementOptions.enhancementType} (count: ${this.enhancementCount})`);
93
+ try {
94
+ const result = this.applyEnhancement(options, enhancementOptions);
95
+ const processingTime = Date.now() - startTime;
96
+ logger.debug(`Enhancement completed in ${processingTime}ms: ${enhancementOptions.enhancementType}`);
97
+ return {
98
+ ...result,
99
+ metadata: {
100
+ ...result.metadata,
101
+ processingTime,
102
+ },
103
+ };
104
+ }
105
+ catch (error) {
106
+ logger.error(`Enhancement failed: ${error}`);
107
+ return this.createErrorResult(options, enhancementOptions, startTime);
108
+ }
109
+ }
110
+ /**
111
+ * Enhance options for streaming optimization
112
+ * Specialized method for streaming enhancements
113
+ */
114
+ static enhanceForStreaming(options, streamingConfig) {
115
+ return this.enhance(options, {
116
+ enhancementType: "streaming-optimization",
117
+ streamingOptions: {
118
+ enabled: true,
119
+ preferStreaming: true,
120
+ ...streamingConfig,
121
+ },
122
+ });
123
+ }
124
+ /**
125
+ * Convert legacy business context to factory options
126
+ * Migration utility for existing business-specific code
127
+ */
128
+ static migrateFromLegacy(options, legacyContext, domainType) {
129
+ return this.enhance(options, {
130
+ enhancementType: "legacy-migration",
131
+ legacyMigration: {
132
+ legacyContext: legacyContext,
133
+ domainType,
134
+ preserveFields: true,
135
+ },
136
+ performance: {
137
+ enableEvaluation: true,
138
+ enableAnalytics: true,
139
+ },
140
+ });
141
+ }
142
+ /**
143
+ * Create unified options from separate generation and streaming options
144
+ * Utility for combining different option types
145
+ */
146
+ static createUnified(generateOptions, streamOptions) {
147
+ const unified = {
148
+ ...generateOptions,
149
+ preferStreaming: false,
150
+ streamingFallback: true,
151
+ };
152
+ if (streamOptions) {
153
+ unified.streaming = {
154
+ enabled: true,
155
+ chunkSize: streamOptions.output?.streaming?.chunkSize,
156
+ bufferSize: streamOptions.output?.streaming?.bufferSize,
157
+ enableProgress: streamOptions.output?.streaming?.enableProgress,
158
+ fallbackToGenerate: true,
159
+ };
160
+ unified.preferStreaming = true;
161
+ }
162
+ return unified;
163
+ }
164
+ /**
165
+ * Enhance GenerateOptions with domain configuration
166
+ * Convenience method for domain-specific enhancements
167
+ */
168
+ static enhanceWithDomain(options, domainConfig) {
169
+ return this.enhance(options, {
170
+ enhancementType: "domain-configuration",
171
+ domainConfiguration: {
172
+ domainType: domainConfig.domainType,
173
+ keyTerms: domainConfig.keyTerms || [],
174
+ failurePatterns: domainConfig.failurePatterns || [
175
+ "unable to help",
176
+ "insufficient data",
177
+ ],
178
+ successPatterns: domainConfig.successPatterns || [
179
+ "analysis shows",
180
+ "data indicates",
181
+ ],
182
+ evaluationCriteria: domainConfig.evaluationCriteria || {},
183
+ },
184
+ performance: {
185
+ enableEvaluation: true,
186
+ enableAnalytics: true,
187
+ },
188
+ });
189
+ }
190
+ /**
191
+ * Validate enhancement compatibility
192
+ * Check if enhancement options are compatible with base options
193
+ */
194
+ static validateEnhancement(options, enhancementOptions) {
195
+ const warnings = [];
196
+ const recommendations = [];
197
+ // Check for conflicting configurations
198
+ if (enhancementOptions.enhancementType === "streaming-optimization" &&
199
+ options.disableTools) {
200
+ warnings.push("Streaming optimization with disabled tools may reduce effectiveness");
201
+ recommendations.push("Consider enabling tools for better streaming performance");
202
+ }
203
+ // Check legacy migration requirements
204
+ if (enhancementOptions.enhancementType === "legacy-migration" &&
205
+ !enhancementOptions.legacyMigration?.legacyContext) {
206
+ return {
207
+ valid: false,
208
+ warnings: ["Legacy migration requested but no legacy context provided"],
209
+ recommendations: ["Provide legacyContext for legacy migration"],
210
+ };
211
+ }
212
+ return {
213
+ valid: true,
214
+ warnings,
215
+ recommendations,
216
+ };
217
+ }
218
+ // Private helper methods
219
+ static applyEnhancement(options, enhancementOptions) {
220
+ const validation = this.validateEnhancement(options, enhancementOptions);
221
+ if (!validation.valid) {
222
+ throw new Error(`Enhancement validation failed: ${validation.warnings.join(", ")}`);
223
+ }
224
+ switch (enhancementOptions.enhancementType) {
225
+ case "streaming-optimization":
226
+ return this.applyStreamingOptimization(options, enhancementOptions);
227
+ case "mcp-integration":
228
+ return this.applyMcpIntegration(options, enhancementOptions);
229
+ case "legacy-migration":
230
+ return this.applyLegacyMigration(options, enhancementOptions);
231
+ case "context-conversion":
232
+ return this.applyContextConversion(options, enhancementOptions);
233
+ case "domain-configuration":
234
+ return this.applyDomainConfiguration(options, enhancementOptions);
235
+ default:
236
+ throw new Error(`Unknown enhancement type: ${enhancementOptions.enhancementType}`);
237
+ }
238
+ }
239
+ static applyStreamingOptimization(options, enhancementOptions) {
240
+ const streamingOptions = enhancementOptions.streamingOptions || {};
241
+ const unifiedOptions = {
242
+ ...options,
243
+ streaming: {
244
+ enabled: streamingOptions.enabled ?? true,
245
+ chunkSize: streamingOptions.chunkSize || 1024,
246
+ bufferSize: streamingOptions.bufferSize || 4096,
247
+ enableProgress: streamingOptions.enableProgress ?? true,
248
+ fallbackToGenerate: true,
249
+ },
250
+ preferStreaming: streamingOptions.preferStreaming ?? true,
251
+ streamingFallback: true,
252
+ };
253
+ // Apply performance optimizations
254
+ if (enhancementOptions.performance?.enableAnalytics) {
255
+ unifiedOptions.enableAnalytics = true;
256
+ }
257
+ return {
258
+ options: unifiedOptions,
259
+ metadata: {
260
+ enhancementApplied: true,
261
+ enhancementType: "streaming-optimization",
262
+ processingTime: 0,
263
+ configurationUsed: streamingOptions,
264
+ warnings: [],
265
+ recommendations: [
266
+ "Monitor streaming performance for optimal chunk size tuning",
267
+ ],
268
+ },
269
+ };
270
+ }
271
+ static applyMcpIntegration(options, enhancementOptions) {
272
+ const mcpOptions = enhancementOptions.mcpOptions || {};
273
+ const unifiedOptions = {
274
+ ...options,
275
+ preferStreaming: false,
276
+ streamingFallback: true,
277
+ };
278
+ // Enhance with MCP context if provided
279
+ if (mcpOptions.executionContext) {
280
+ unifiedOptions.context = {
281
+ ...unifiedOptions.context,
282
+ mcpContext: mcpOptions.executionContext,
283
+ mcpIntegrationEnabled: true,
284
+ };
285
+ }
286
+ // Enable tools if MCP integration is requested
287
+ if (mcpOptions.enableToolRegistry && options.disableTools) {
288
+ unifiedOptions.disableTools = false;
289
+ logger.info("Enabled tools for MCP integration");
290
+ }
291
+ return {
292
+ options: unifiedOptions,
293
+ metadata: {
294
+ enhancementApplied: true,
295
+ enhancementType: "mcp-integration",
296
+ processingTime: 0,
297
+ configurationUsed: mcpOptions,
298
+ warnings: [],
299
+ recommendations: [
300
+ "Ensure MCP tools are properly configured for optimal integration",
301
+ ],
302
+ },
303
+ };
304
+ }
305
+ static applyLegacyMigration(options, enhancementOptions) {
306
+ const legacyMigration = enhancementOptions.legacyMigration;
307
+ // Convert legacy context to execution context
308
+ const executionContext = ContextConverter.convertBusinessContext(legacyMigration.legacyContext, legacyMigration.domainType, {
309
+ preserveLegacyFields: legacyMigration.preserveFields,
310
+ validateDomainData: true,
311
+ includeMetadata: true,
312
+ });
313
+ const unifiedOptions = {
314
+ ...options,
315
+ context: {
316
+ ...options.context,
317
+ legacyMigration: true,
318
+ executionContext,
319
+ originalLegacyContext: legacyMigration.legacyContext,
320
+ },
321
+ factoryConfig: {
322
+ domainType: legacyMigration.domainType,
323
+ enhancementType: "legacy-migration",
324
+ preserveLegacyFields: legacyMigration.preserveFields,
325
+ validateDomainData: true,
326
+ },
327
+ preferStreaming: false,
328
+ streamingFallback: true,
329
+ };
330
+ // Apply performance settings
331
+ if (enhancementOptions.performance?.enableEvaluation) {
332
+ unifiedOptions.enableEvaluation = true;
333
+ unifiedOptions.evaluationDomain = legacyMigration.domainType;
334
+ }
335
+ if (enhancementOptions.performance?.enableAnalytics) {
336
+ unifiedOptions.enableAnalytics = true;
337
+ }
338
+ return {
339
+ options: unifiedOptions,
340
+ metadata: {
341
+ enhancementApplied: true,
342
+ enhancementType: "legacy-migration",
343
+ processingTime: 0,
344
+ configurationUsed: {
345
+ domainType: legacyMigration.domainType,
346
+ preserveFields: legacyMigration.preserveFields,
347
+ legacyContextKeys: Object.keys(legacyMigration.legacyContext),
348
+ },
349
+ warnings: [],
350
+ recommendations: [
351
+ "Review migrated context for completeness",
352
+ "Consider gradually removing legacy field dependencies",
353
+ ],
354
+ },
355
+ };
356
+ }
357
+ static applyContextConversion(options, enhancementOptions) {
358
+ // Context conversion is a specialized form of enhancement
359
+ const legacyMigration = enhancementOptions.legacyMigration || {};
360
+ const unifiedOptions = {
361
+ ...options,
362
+ preferStreaming: false,
363
+ streamingFallback: true,
364
+ };
365
+ // Apply context conversion if legacy context is provided
366
+ if (legacyMigration.legacyContext && legacyMigration.domainType) {
367
+ const executionContext = ContextConverter.convertBusinessContext(legacyMigration.legacyContext, legacyMigration.domainType, { preserveLegacyFields: legacyMigration.preserveFields });
368
+ // Add converted context to unified options
369
+ Object.assign(unifiedOptions, { executionContext });
370
+ }
371
+ return {
372
+ options: unifiedOptions,
373
+ metadata: {
374
+ enhancementApplied: true,
375
+ enhancementType: enhancementOptions.enhancementType,
376
+ processingTime: 0,
377
+ configurationUsed: legacyMigration,
378
+ warnings: [],
379
+ recommendations: [],
380
+ },
381
+ };
382
+ }
383
+ static applyDomainConfiguration(options, enhancementOptions) {
384
+ const domainConfig = enhancementOptions.domainConfiguration;
385
+ if (!domainConfig) {
386
+ throw new Error("Domain configuration is required for domain-configuration enhancement");
387
+ }
388
+ const unifiedOptions = {
389
+ ...options,
390
+ enableEvaluation: enhancementOptions.performance?.enableEvaluation ?? true,
391
+ enableAnalytics: enhancementOptions.performance?.enableAnalytics ?? true,
392
+ evaluationDomain: domainConfig.domainType,
393
+ context: {
394
+ ...options.context,
395
+ domainConfig: {
396
+ domainType: domainConfig.domainType,
397
+ keyTerms: domainConfig.keyTerms || [],
398
+ failurePatterns: domainConfig.failurePatterns || [],
399
+ successPatterns: domainConfig.successPatterns || [],
400
+ evaluationCriteria: domainConfig.evaluationCriteria || {},
401
+ },
402
+ },
403
+ preferStreaming: false,
404
+ streamingFallback: true,
405
+ };
406
+ return {
407
+ options: unifiedOptions,
408
+ metadata: {
409
+ enhancementApplied: true,
410
+ enhancementType: enhancementOptions.enhancementType,
411
+ processingTime: 0,
412
+ configurationUsed: domainConfig,
413
+ warnings: [],
414
+ recommendations: [],
415
+ },
416
+ };
417
+ }
418
+ static createErrorResult(options, enhancementOptions, startTime) {
419
+ const unifiedOptions = {
420
+ ...options,
421
+ preferStreaming: false,
422
+ streamingFallback: true,
423
+ };
424
+ return {
425
+ options: unifiedOptions,
426
+ metadata: {
427
+ enhancementApplied: false,
428
+ enhancementType: enhancementOptions.enhancementType,
429
+ processingTime: Date.now() - startTime,
430
+ configurationUsed: {},
431
+ warnings: ["Enhancement failed - using original options"],
432
+ recommendations: ["Check enhancement configuration and try again"],
433
+ },
434
+ };
435
+ }
436
+ /**
437
+ * Get enhancement statistics
438
+ * Utility for monitoring enhancement usage
439
+ */
440
+ static getStatistics() {
441
+ return {
442
+ enhancementCount: this.enhancementCount,
443
+ lastReset: Date.now(),
444
+ };
445
+ }
446
+ /**
447
+ * Reset enhancement statistics
448
+ * Utility for clearing counters
449
+ */
450
+ static resetStatistics() {
451
+ if (OptionsEnhancer.enhancementCountArray) {
452
+ Atomics.store(OptionsEnhancer.enhancementCountArray, 0, 0);
453
+ }
454
+ else {
455
+ OptionsEnhancer.fallbackEnhancementCount = 0;
456
+ }
457
+ logger.debug("Enhancement statistics reset");
458
+ }
459
+ }
460
+ /**
461
+ * Convenience functions for common enhancement patterns
462
+ */
463
+ /**
464
+ * Quick streaming enhancement
465
+ * Simplified interface for streaming optimization
466
+ */
467
+ export function enhanceForStreaming(options, chunkSize = 1024) {
468
+ return OptionsEnhancer.enhanceForStreaming(options, {
469
+ chunkSize,
470
+ enableProgress: true,
471
+ });
472
+ }
473
+ /**
474
+ * Quick legacy migration
475
+ * Simplified interface for legacy context migration
476
+ */
477
+ export function migrateLegacyContext(options, legacyContext, domainType) {
478
+ return OptionsEnhancer.migrateFromLegacy(options, legacyContext, domainType);
479
+ }
480
+ /**
481
+ * Batch enhancement utility with intelligent parallel processing
482
+ * Automatically detects independent enhancements for parallel processing
483
+ */
484
+ export function batchEnhance(options, enhancements) {
485
+ if (enhancements.length === 0) {
486
+ return OptionsEnhancer.enhance(options, {
487
+ enhancementType: "context-conversion",
488
+ });
489
+ }
490
+ if (enhancements.length === 1) {
491
+ return OptionsEnhancer.enhance(options, enhancements[0]);
492
+ }
493
+ // Analyze enhancement dependencies to determine processing strategy
494
+ const independentGroups = analyzeEnhancementDependencies(enhancements);
495
+ if (independentGroups.length === 1 &&
496
+ independentGroups[0].length === enhancements.length) {
497
+ // All enhancements are independent - use parallel processing
498
+ return batchEnhanceParallelOptimized(options, enhancements);
499
+ }
500
+ else {
501
+ // Mixed dependencies - use sequential processing with parallelization where possible
502
+ return batchEnhanceHybrid(options, enhancements, independentGroups);
503
+ }
504
+ }
505
+ /**
506
+ * Analyze enhancement dependencies to identify independent groups
507
+ */
508
+ function analyzeEnhancementDependencies(enhancements) {
509
+ const independentGroups = [];
510
+ const processed = new Set();
511
+ for (let i = 0; i < enhancements.length; i++) {
512
+ if (processed.has(i)) {
513
+ continue;
514
+ }
515
+ const currentGroup = [i];
516
+ processed.add(i);
517
+ // Check if subsequent enhancements are independent
518
+ for (let j = i + 1; j < enhancements.length; j++) {
519
+ if (processed.has(j)) {
520
+ continue;
521
+ }
522
+ if (areEnhancementsIndependent(enhancements[i], enhancements[j])) {
523
+ currentGroup.push(j);
524
+ processed.add(j);
525
+ }
526
+ }
527
+ independentGroups.push(currentGroup);
528
+ }
529
+ return independentGroups;
530
+ }
531
+ /**
532
+ * Default conflict detection plugin implementing the original hardcoded logic
533
+ */
534
+ class DefaultConflictDetectionPlugin {
535
+ name = "default-conflict-detector";
536
+ version = "1.0.0";
537
+ static ENHANCEMENT_CONFLICTS = {
538
+ "domain-configuration": ["context-conversion", "legacy-migration"],
539
+ "context-conversion": ["domain-configuration", "legacy-migration"],
540
+ "streaming-optimization": ["batch-parallel-enhancement"],
541
+ "mcp-integration": ["legacy-migration"],
542
+ "legacy-migration": [
543
+ "domain-configuration",
544
+ "context-conversion",
545
+ "mcp-integration",
546
+ ],
547
+ "batch-parallel-enhancement": [
548
+ "streaming-optimization",
549
+ "batch-hybrid-enhancement",
550
+ ],
551
+ "batch-hybrid-enhancement": ["batch-parallel-enhancement"],
552
+ "batch-dependency-enhancement": [], // Can coexist with most enhancements
553
+ };
554
+ detectConflict(enhancementA, enhancementB) {
555
+ // Same type enhancements may conflict
556
+ if (enhancementA === enhancementB) {
557
+ return false;
558
+ }
559
+ // Check configurable conflicts for enhancementA
560
+ const conflictsA = DefaultConflictDetectionPlugin.ENHANCEMENT_CONFLICTS[enhancementA] || [];
561
+ if (conflictsA.includes(enhancementB)) {
562
+ return true;
563
+ }
564
+ // Check configurable conflicts for enhancementB
565
+ const conflictsB = DefaultConflictDetectionPlugin.ENHANCEMENT_CONFLICTS[enhancementB] || [];
566
+ if (conflictsB.includes(enhancementA)) {
567
+ return true;
568
+ }
569
+ // No conflicts found
570
+ return false;
571
+ }
572
+ getConflictSeverity(enhancementA, enhancementB) {
573
+ // Legacy migration conflicts are high severity
574
+ if (enhancementA === "legacy-migration" ||
575
+ enhancementB === "legacy-migration") {
576
+ return "high";
577
+ }
578
+ // Context and domain conflicts are medium severity
579
+ if ([enhancementA, enhancementB].some((type) => ["context-conversion", "domain-configuration"].includes(type))) {
580
+ return "medium";
581
+ }
582
+ // Other conflicts are low severity
583
+ return "low";
584
+ }
585
+ suggestResolution(enhancementA, enhancementB) {
586
+ const suggestions = [];
587
+ if (enhancementA === "legacy-migration" ||
588
+ enhancementB === "legacy-migration") {
589
+ suggestions.push("Complete legacy migration first, then apply other enhancements");
590
+ suggestions.push("Consider using context-conversion instead of legacy-migration");
591
+ }
592
+ if (enhancementA === "streaming-optimization" &&
593
+ enhancementB === "batch-parallel-enhancement") {
594
+ suggestions.push("Use streaming-optimization for single requests");
595
+ suggestions.push("Use batch-parallel-enhancement for multiple independent requests");
596
+ }
597
+ if (suggestions.length === 0) {
598
+ suggestions.push("Apply enhancements sequentially instead of in parallel");
599
+ suggestions.push("Review enhancement requirements for compatibility");
600
+ }
601
+ return suggestions;
602
+ }
603
+ }
604
+ /**
605
+ * Advanced conflict detection plugin with context-aware analysis
606
+ */
607
+ class AdvancedConflictDetectionPlugin {
608
+ name = "advanced-conflict-detector";
609
+ version = "1.0.0";
610
+ detectConflict(enhancementA, enhancementB, optionsA, optionsB) {
611
+ // Context-aware conflict detection based on actual options
612
+ if (this.hasContextualConflict(enhancementA, enhancementB, optionsA, optionsB)) {
613
+ return true;
614
+ }
615
+ // Performance-based conflict detection
616
+ if (this.hasPerformanceConflict(enhancementA, enhancementB, optionsA, optionsB)) {
617
+ return true;
618
+ }
619
+ return false;
620
+ }
621
+ hasContextualConflict(enhancementA, enhancementB, optionsA, optionsB) {
622
+ // Check for overlapping context modifications
623
+ if (enhancementA === "context-conversion" &&
624
+ enhancementB === "mcp-integration" &&
625
+ optionsA?.legacyMigration?.legacyContext &&
626
+ optionsB?.mcpOptions?.executionContext) {
627
+ return true; // Both modify execution context
628
+ }
629
+ // Check for conflicting streaming settings
630
+ if (enhancementA === "streaming-optimization" &&
631
+ enhancementB === "mcp-integration" &&
632
+ optionsA?.streamingOptions?.enabled &&
633
+ optionsB?.mcpOptions?.enableToolRegistry) {
634
+ return false; // These can actually work together
635
+ }
636
+ return false;
637
+ }
638
+ hasPerformanceConflict(enhancementA, enhancementB, _optionsA, _optionsB) {
639
+ // Check for performance-affecting combinations
640
+ const highPerformanceEnhancements = [
641
+ "batch-parallel-enhancement",
642
+ "streaming-optimization",
643
+ ];
644
+ if (highPerformanceEnhancements.includes(enhancementA) &&
645
+ highPerformanceEnhancements.includes(enhancementB)) {
646
+ return true; // Multiple performance enhancements may conflict
647
+ }
648
+ return false;
649
+ }
650
+ getConflictSeverity(enhancementA, enhancementB) {
651
+ // Context conflicts are always high severity
652
+ if ([enhancementA, enhancementB].some((type) => ["context-conversion", "legacy-migration"].includes(type))) {
653
+ return "high";
654
+ }
655
+ // Performance conflicts are medium severity
656
+ if ([enhancementA, enhancementB].some((type) => ["streaming-optimization", "batch-parallel-enhancement"].includes(type))) {
657
+ return "medium";
658
+ }
659
+ return "low";
660
+ }
661
+ suggestResolution(_enhancementA, _enhancementB) {
662
+ return [
663
+ "Consider applying enhancements in phases based on priority",
664
+ "Use hybrid enhancement approach with sequential processing",
665
+ "Review options for compatibility before combining enhancements",
666
+ ];
667
+ }
668
+ }
669
+ /**
670
+ * Plugin registry for managing conflict detection plugins
671
+ */
672
+ class ConflictDetectionRegistry {
673
+ plugins = new Map();
674
+ activePlugins = [];
675
+ constructor() {
676
+ // Register default plugins
677
+ this.registerPlugin(new DefaultConflictDetectionPlugin());
678
+ this.registerPlugin(new AdvancedConflictDetectionPlugin());
679
+ // Set default active plugin
680
+ this.setActivePlugins(["default-conflict-detector"]);
681
+ }
682
+ /**
683
+ * Register a new conflict detection plugin
684
+ */
685
+ registerPlugin(plugin) {
686
+ this.plugins.set(plugin.name, plugin);
687
+ logger.debug(`Registered conflict detection plugin: ${plugin.name} v${plugin.version}`);
688
+ }
689
+ /**
690
+ * Set active plugins (in order of priority)
691
+ */
692
+ setActivePlugins(pluginNames) {
693
+ // Validate all plugins exist
694
+ const validPlugins = pluginNames.filter((name) => this.plugins.has(name));
695
+ if (validPlugins.length !== pluginNames.length) {
696
+ const missing = pluginNames.filter((name) => !this.plugins.has(name));
697
+ logger.warn(`Missing conflict detection plugins: ${missing.join(", ")}`);
698
+ }
699
+ this.activePlugins = validPlugins;
700
+ logger.debug(`Active conflict detection plugins: ${this.activePlugins.join(", ")}`);
701
+ }
702
+ /**
703
+ * Detect conflicts using active plugins
704
+ */
705
+ detectConflicts(enhancementA, enhancementB, optionsA, optionsB) {
706
+ const detectedBy = [];
707
+ const allSuggestions = [];
708
+ let maxSeverity = "low";
709
+ // Check all active plugins
710
+ for (const pluginName of this.activePlugins) {
711
+ const plugin = this.plugins.get(pluginName);
712
+ if (!plugin) {
713
+ continue;
714
+ }
715
+ const hasConflict = plugin.detectConflict(enhancementA, enhancementB, optionsA, optionsB);
716
+ if (hasConflict) {
717
+ detectedBy.push(pluginName);
718
+ // Get severity
719
+ if (plugin.getConflictSeverity) {
720
+ const severity = plugin.getConflictSeverity(enhancementA, enhancementB);
721
+ if (severity === "high" ||
722
+ (severity === "medium" && maxSeverity === "low")) {
723
+ maxSeverity = severity;
724
+ }
725
+ }
726
+ // Get suggestions
727
+ if (plugin.suggestResolution) {
728
+ const suggestions = plugin.suggestResolution(enhancementA, enhancementB);
729
+ allSuggestions.push(...suggestions);
730
+ }
731
+ }
732
+ }
733
+ return {
734
+ hasConflict: detectedBy.length > 0,
735
+ severity: maxSeverity,
736
+ detectedBy,
737
+ suggestions: Array.from(new Set(allSuggestions)), // Remove duplicates
738
+ };
739
+ }
740
+ /**
741
+ * Get information about registered plugins
742
+ */
743
+ getPluginInfo() {
744
+ return Array.from(this.plugins.values()).map((plugin) => ({
745
+ name: plugin.name,
746
+ version: plugin.version,
747
+ active: this.activePlugins.includes(plugin.name),
748
+ }));
749
+ }
750
+ }
751
+ // Global registry instance
752
+ const conflictDetectionRegistry = new ConflictDetectionRegistry();
753
+ /**
754
+ * Get the global conflict detection registry for plugin management
755
+ * Allows external systems to register custom conflict detection plugins
756
+ */
757
+ export function getConflictDetectionRegistry() {
758
+ return conflictDetectionRegistry;
759
+ }
760
+ /**
761
+ * Check if two enhancements are independent (don't affect same properties)
762
+ * Now uses plugin-based conflict detection for extensibility
763
+ */
764
+ function areEnhancementsIndependent(enhancementA, enhancementB) {
765
+ const typeA = enhancementA.enhancementType || "context-conversion";
766
+ const typeB = enhancementB.enhancementType || "context-conversion";
767
+ // Same type enhancements may conflict
768
+ if (typeA === typeB) {
769
+ return false;
770
+ }
771
+ // Use plugin-based conflict detection
772
+ const conflictResult = conflictDetectionRegistry.detectConflicts(typeA, typeB, enhancementA, enhancementB);
773
+ // Enhancements are independent if no conflicts are detected
774
+ return !conflictResult.hasConflict;
775
+ }
776
+ /**
777
+ * Optimized parallel processing for fully independent enhancements
778
+ */
779
+ function batchEnhanceParallelOptimized(options, enhancements) {
780
+ const results = enhancements.map((enhancement) => OptionsEnhancer.enhance(options, enhancement));
781
+ // Merge all enhancement results
782
+ let finalOptions = options;
783
+ const allWarnings = [];
784
+ const allRecommendations = [];
785
+ let totalProcessingTime = 0;
786
+ for (const result of results) {
787
+ // Merge options (later enhancements override earlier ones for conflicts)
788
+ finalOptions = {
789
+ ...finalOptions,
790
+ ...result.options,
791
+ // Merge context and factoryConfig carefully
792
+ context: {
793
+ ...finalOptions.context,
794
+ ...result.options.context,
795
+ },
796
+ factoryConfig: {
797
+ ...finalOptions.factoryConfig,
798
+ ...result.options.factoryConfig,
799
+ },
800
+ };
801
+ allWarnings.push(...result.metadata.warnings);
802
+ allRecommendations.push(...result.metadata.recommendations);
803
+ totalProcessingTime += result.metadata.processingTime;
804
+ }
805
+ return {
806
+ options: finalOptions,
807
+ metadata: {
808
+ enhancementApplied: true,
809
+ enhancementType: "batch-parallel-enhancement",
810
+ processingTime: totalProcessingTime,
811
+ configurationUsed: {
812
+ parallelProcessing: true,
813
+ enhancementCount: enhancements.length,
814
+ },
815
+ warnings: Array.from(new Set(allWarnings)),
816
+ recommendations: Array.from(new Set(allRecommendations)),
817
+ },
818
+ };
819
+ }
820
+ /**
821
+ * Hybrid processing for mixed dependencies
822
+ */
823
+ function batchEnhanceHybrid(options, enhancements, independentGroups) {
824
+ let currentOptions = options;
825
+ let finalResult = null;
826
+ const allWarnings = [];
827
+ const allRecommendations = [];
828
+ let totalProcessingTime = 0;
829
+ for (const group of independentGroups) {
830
+ if (group.length === 1) {
831
+ // Single enhancement - process normally
832
+ const result = OptionsEnhancer.enhance(currentOptions, enhancements[group[0]]);
833
+ currentOptions = result.options;
834
+ finalResult = result;
835
+ }
836
+ else {
837
+ // Multiple independent enhancements - process in parallel
838
+ const groupEnhancements = group.map((idx) => enhancements[idx]);
839
+ const result = batchEnhanceParallelOptimized(currentOptions, groupEnhancements);
840
+ currentOptions = result.options;
841
+ finalResult = result;
842
+ }
843
+ if (finalResult) {
844
+ allWarnings.push(...finalResult.metadata.warnings);
845
+ allRecommendations.push(...finalResult.metadata.recommendations);
846
+ totalProcessingTime += finalResult.metadata.processingTime;
847
+ }
848
+ }
849
+ if (finalResult) {
850
+ finalResult.metadata.warnings = Array.from(new Set(allWarnings));
851
+ finalResult.metadata.recommendations = Array.from(new Set(allRecommendations));
852
+ finalResult.metadata.processingTime = totalProcessingTime;
853
+ finalResult.metadata.enhancementType = "batch-hybrid-enhancement";
854
+ }
855
+ return finalResult || OptionsEnhancer.enhance(options, enhancements[0]);
856
+ }
857
+ /**
858
+ * Parallel batch enhancement utility
859
+ * Apply multiple independent enhancements in parallel for better performance
860
+ * Note: Only use for independent enhancements that don't depend on each other
861
+ */
862
+ export async function batchEnhanceParallel(baseOptions, enhancements) {
863
+ if (baseOptions.length !== enhancements.length) {
864
+ throw new Error("baseOptions and enhancements arrays must have the same length");
865
+ }
866
+ // Validate all enhancements before processing
867
+ for (let i = 0; i < baseOptions.length; i++) {
868
+ const validation = OptionsEnhancer.validateEnhancement(baseOptions[i], enhancements[i]);
869
+ if (!validation.valid) {
870
+ throw new Error(`Enhancement validation failed for item ${i}: ${validation.warnings.join(", ")}`);
871
+ }
872
+ }
873
+ // Process enhancements in parallel for independent operations
874
+ const enhancementPromises = baseOptions.map((options, index) => {
875
+ return Promise.resolve(OptionsEnhancer.enhance(options, enhancements[index]));
876
+ });
877
+ try {
878
+ const results = await Promise.all(enhancementPromises);
879
+ // Log parallel processing statistics
880
+ logger.debug(`Parallel enhancement completed: ${results.length} items processed concurrently`);
881
+ return results;
882
+ }
883
+ catch (error) {
884
+ logger.error(`Parallel enhancement failed: ${error}`);
885
+ throw error;
886
+ }
887
+ }
888
+ /**
889
+ * Batch enhancement with dependency handling
890
+ * Apply enhancements with proper dependency resolution
891
+ */
892
+ export function batchEnhanceWithDependencies(options, enhancements) {
893
+ // Validate dependency graph first
894
+ const validateDependencies = () => {
895
+ for (let i = 0; i < enhancements.length; i++) {
896
+ const enhancement = enhancements[i];
897
+ if (enhancement.dependsOn) {
898
+ for (const depIndex of enhancement.dependsOn) {
899
+ if (depIndex >= enhancements.length || depIndex < 0) {
900
+ throw new Error(`Invalid dependency: enhancement ${i} depends on non-existent enhancement ${depIndex}`);
901
+ }
902
+ if (depIndex >= i) {
903
+ throw new Error(`Circular or forward dependency detected: enhancement ${i} depends on ${depIndex}`);
904
+ }
905
+ }
906
+ }
907
+ }
908
+ };
909
+ validateDependencies();
910
+ // Build dependency graph
911
+ const processed = new Set();
912
+ const results = [];
913
+ let currentOptions = options;
914
+ // Process enhancements in dependency order
915
+ const processEnhancement = (index) => {
916
+ if (processed.has(index)) {
917
+ return;
918
+ }
919
+ const enhancement = enhancements[index];
920
+ // Process dependencies first
921
+ if (enhancement.dependsOn) {
922
+ for (const depIndex of enhancement.dependsOn) {
923
+ processEnhancement(depIndex);
924
+ }
925
+ }
926
+ // Validate enhancement before processing
927
+ const validation = OptionsEnhancer.validateEnhancement(currentOptions, enhancement);
928
+ if (!validation.valid) {
929
+ logger.warn(`Enhancement ${index} validation warnings: ${validation.warnings.join(", ")}`);
930
+ }
931
+ // Process current enhancement
932
+ const result = OptionsEnhancer.enhance(currentOptions, enhancement);
933
+ currentOptions = result.options;
934
+ results.push(result);
935
+ processed.add(index);
936
+ logger.debug(`Processed enhancement ${index}: ${enhancement.enhancementType} (${result.metadata.processingTime}ms)`);
937
+ };
938
+ // Process all enhancements
939
+ for (let i = 0; i < enhancements.length; i++) {
940
+ processEnhancement(i);
941
+ }
942
+ // Combine results
943
+ const allWarnings = results.flatMap((r) => r.metadata.warnings);
944
+ const allRecommendations = results.flatMap((r) => r.metadata.recommendations);
945
+ const totalProcessingTime = results.reduce((sum, r) => sum + r.metadata.processingTime, 0);
946
+ const finalResult = results[results.length - 1];
947
+ if (finalResult) {
948
+ finalResult.metadata.warnings = Array.from(new Set(allWarnings));
949
+ finalResult.metadata.recommendations = Array.from(new Set(allRecommendations));
950
+ finalResult.metadata.processingTime = totalProcessingTime;
951
+ finalResult.metadata.enhancementType = "batch-dependency-enhancement";
952
+ finalResult.metadata.configurationUsed = {
953
+ ...finalResult.metadata.configurationUsed,
954
+ dependencyChainLength: results.length,
955
+ enhancementTypes: results.map((r) => r.metadata.enhancementType),
956
+ };
957
+ }
958
+ logger.debug(`Dependency batch enhancement completed: ${results.length} enhancements processed in ${totalProcessingTime}ms`);
959
+ return finalResult || OptionsEnhancer.enhance(options, enhancements[0]);
960
+ }